15 Commits

Author SHA1 Message Date
xy
cf691db0a6 feat(harmonic): 新增移动端线路详情功能并优化波形数据处理
- 添加 AppLineDetailVo 数据传输对象,支持移动端线路详情展示
- 增加 report 服务中的 buildHarmonic 相关方法重构,支持移动端线路详情查询
- 优化波形数据处理逻辑,新增波形数据抽点和裁剪功能,减少移动端数据传输量
- 修改 CommonStatisticalQueryParam 参数类,增加数据模型字段和电度事件类型支持
- 调整统计查询相关接口,支持全量和增量查询模式
- 移除 CredentialReqDTO 类,清理相关依赖
- 优化 CsAppReportServiceImpl 中的越限描述构建逻辑,使用时间转换工具
- 更新数据查询相关 Mapper XML 文件,调整数据过滤条件
- 修改设备用户服务实现,完善当前工程数据显示逻辑
- 优化 CsEquipmentDeliveryServiceImpl 中的数据集添加逻辑,支持电度数据类型
- 重构 CsEventController 和相关服务类,支持移动端波形数据分析
- 添加 Nacos 配置参数控制波形数据抽点和间隔区域处理行为
2026-06-03 10:22:18 +08:00
xy
a6f424025a feat(harmonic): 添加稳态指标方案与监测点关联功能
- 新增根据名称查询稳态指标方案的接口和实现
- 添加方案与监测点关联的保存和删除接口
- 在设备交付服务中集成稳态指标方案配置功能
- 实现监测点创建时自动关联默认方案
- 完善相关Feign客户端和服务降级处理
- 优化方法命名规范统一小写开头
2026-05-27 18:10:44 +08:00
xy
f81be47e5f refactor(harmonic): 重构事件通知服务并迁移至系统模块
- 移除 AppNotificationService 和 SmsNotificationService 服务类
- 新增消息发送服务相关接口和实现类到系统模块
- 迁移 AsyncConfig 配置类到 cs-system 模块
- 新增事件用户关系表的 Mapper、Service 接口及实现类
- 更新 CsEventPO 添加 landPoint 字段用于存储事件落点信息
- 修改事件处理逻辑使用新的消息发送 Feign 客户端
- 集成事件原因分析功能并更新数据库字段映射
- 更新设备详情 DTO 添加 nDid 属性支持
- 优化事件通知和短信发送的消息内容格式
- 移除旧的设备消息客户端依赖并使用新服务接口
2026-05-27 11:12:32 +08:00
xy
202888ca14 refactor(data): 便携式设备数据补召功能重构
- 移除接口中的方法注释以简化代码结构
- 替换Spring事务注解为动态数据源事务注解
- 删除未使用的导入包和注释掉的代码行
- 简化数据拆分服务实现类中的复杂逻辑
- 添加时间间隔处理逻辑用于不同数据表的定时入库
- 优化数据映射过程中的null值处理机制
- 重构字段值设置方法以提高类型安全性和错误处理能力
2026-05-26 16:09:26 +08:00
xy
94929e66d5 fix(service): 修复设备消息服务中的监测点空值处理
- 注释掉CsDataSetServiceImpl中多余的数据类型过滤条件
- 移除DeviceMessageServiceImpl中未使用的BusinessException导入
- 为DeviceMessageServiceImpl添加Slf4j日志注解
- 修改监测点为空时的异常抛出逻辑为日志记录并返回
- 避免因监测点为空导致的服务异常中断
2026-05-26 10:53:38 +08:00
xy
4d5950d5ad 微调 2026-05-25 20:03:54 +08:00
xy
ff7b05bbb6 feat(device): 便携式设备数据补召功能重构,补召数据拆分到13张基础数据表中 2026-05-25 19:59:47 +08:00
xy
ea2962840c feat(topology): 添加拓扑图目标指标功能并重构数据处理逻辑
- 在AppLineTopologyDiagram相关类中添加target字段用于绑定指标
- 重构DeviceMessageClient的getLineInfo方法参数结构
- 实现CsLineTopologyFeignClient的queryTopologyDiagram接口及降级处理
- 更新MqttMessageHandler中拓扑图数据处理逻辑,支持自定义指标查询
- 添加PqdData数据拆分服务IPqdDataSplitService及其实现
- 优化PortableOfflLogServiceImpl中的数据入库逻辑
- 修复CsTerminalReplyServiceImpl中时间范围查询条件
- 移除未使用的导入和代码,优化服务依赖注入
2026-05-25 14:38:35 +08:00
xy
1d8d714d66 feat(event): 添加暂降原因和类型字段支持
- 在CsEventPO实体类中新增advanceReason和advanceType字段
- 修改AnalyseComtradeCfg中的数值类型标识为大写格式(MIN/MAX/AVG/CP95)
- 将相位类型从"M"更改为"T"
- 在事件服务实现中同步暂降原因和类型数据到数据库
2026-05-21 19:56:28 +08:00
xy
23574f0819 fix(data-task): 修复数据任务中的越限标签计算和报警处理逻辑
- 修复了buildOverlimitTag方法名拼写错误,统一为buildOverLimitTag
- 添加了lineInterval参数用于越限次数到分钟数的转换计算
- 将越限次数乘以统计间隔并限制最大值为1440分钟
- 优化了CsAlarmServiceImpl中的在线率和完整性异常判断逻辑
- 重构了报警VO的数据流处理方式
- 更新了CsHarmonicServiceImpl中的枚举映射配置
- 调整了设备消息接口的参数注解配置
- 清理了无用的Jackson依赖导入
- 移除了废弃的通信离线时段计算代码
2026-05-21 15:26:54 +08:00
xy
a82ea6b217 fix(data-service): 修复相位判断逻辑并优化数据查询配置
- 统一将相位判断条件从"M"改为"T"
- 修正CT/PT变比计算逻辑,增加二次变比处理
- 移除废弃的闪变数据过滤逻辑
- 更新InfluxDB数据表名和字段名配置
- 修改服务接口参数传递方式
- 优化相位数据显示逻辑,统一相位标识处理
2026-05-20 09:26:05 +08:00
xy
16724d7d79 feat(data): 添加InfluxDB存储名称映射功能
- 在CsDataArray实体类中新增influxDbName字段用于存储InfluxDB名称
- 集成字典数据和EPD服务实现数据映射逻辑
- 修改多个服务类中的数据查询逻辑以支持别名映射
- 统一数据类型转换为大写格式提升数据一致性
- 优化时间范围计算逻辑并移除无效的数据处理代码
- 清理无用的导入包和服务依赖项
2026-05-18 18:35:40 +08:00
xy
aa36c077f2 feat(alarm): 更新告警系统以支持在线率和完整性监控
- 移除原有的中断计数功能,改为在线率和完整性告警判断
- 新增CsAlarmData类用于存储在线率和完整性详细数据
- 更新AlarmVO数据结构,替换interruptCounts为onlineRateIsWarn和integrityIsWarn字段
- 修改告警服务实现,从JSON解析List<List<String>>改为解析CsAlarmData对象
- 新增channelRunDataAlarm方法用于运行数据告警算法,处理在线率和完整性阈值判断
- 实现完整的告警数据构建逻辑,包括设备在线率计算和监测点完整性评估
- 更新统计服务中的数据去重逻辑,避免重复计算设备和监测点数据
2026-05-14 09:22:26 +08:00
xy
82e5d6c8e2 refactor(data): 优化谐波和间谐波数据一二次值处理逻辑 2026-05-09 14:20:25 +08:00
xy
76000e4fff feat(alarm): 新增告警配置管理功能
- 实现CsAlarmSetController提供新增、修改、删除、查询等REST接口
- 修复设备消息推送中的参数描述错误,将isAdmin改为推送普通用户
2026-05-08 16:31:59 +08:00
102 changed files with 4340 additions and 2009 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

@@ -4,9 +4,12 @@ import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csdevice.api.fallback.CsLineTopologyClientFallbackFactory;
import com.njcn.csdevice.pojo.po.AppLineTopologyDiagramPO;
import com.njcn.csdevice.pojo.vo.AppTopologyDiagramVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@@ -19,4 +22,8 @@ public interface CsLineTopologyFeignClient {
@PostMapping("/addList")
HttpResult<String> addList(@RequestBody List<AppLineTopologyDiagramPO> list);
@PostMapping("/queryTopologyDiagram")
@ApiOperation("查询装置拓扑图")
HttpResult<AppTopologyDiagramVO> queryTopologyDiagram(@RequestParam(value="devId") String devId);
}

View File

@@ -4,6 +4,7 @@ import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csdevice.api.fallback.DeviceMessageClientFallbackFactory;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.param.LineInfoParam;
import com.njcn.user.pojo.po.User;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
@@ -29,6 +30,6 @@ public interface DeviceMessageFeignClient {
@PostMapping("/getLineInfo")
@ApiOperation("获取监测点信息")
HttpResult<String> getLineInfo(@RequestParam("id") String id);
HttpResult<String> getLineInfo(@RequestBody LineInfoParam param);
}

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

@@ -5,6 +5,7 @@ import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csdevice.api.CsLineTopologyFeignClient;
import com.njcn.csdevice.pojo.po.AppLineTopologyDiagramPO;
import com.njcn.csdevice.pojo.vo.AppTopologyDiagramVO;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@@ -33,6 +34,12 @@ public class CsLineTopologyClientFallbackFactory implements FallbackFactory<CsLi
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<AppTopologyDiagramVO> queryTopologyDiagram(String devId) {
log.error("{}异常,降级处理,异常为:{}","查询装置拓扑图异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -5,6 +5,7 @@ import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.param.LineInfoParam;
import com.njcn.user.pojo.po.User;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
@@ -41,7 +42,7 @@ public class DeviceMessageClientFallbackFactory implements FallbackFactory<Devic
}
@Override
public HttpResult<String> getLineInfo(String id) {
public HttpResult<String> getLineInfo(LineInfoParam param) {
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

@@ -0,0 +1,21 @@
package com.njcn.csdevice.param;
import com.njcn.csdevice.pojo.po.CsLinePO;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* @author xy
*/
@Data
public class LineInfoParam {
@ApiModelProperty("nDid")
private String nDid;
@ApiModelProperty("监测点集合")
List<CsLinePO> list;
}

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

@@ -40,6 +40,9 @@ public class DevDetailDTO {
@ApiModelProperty(value = "设备MAC地址")
private String devMac;
@ApiModelProperty(value = "nDid")
private String nDid;
@ApiModelProperty(value = "监测点id集合")
private List<String> lineList;
}

View File

@@ -44,5 +44,6 @@ public class AppLineTopologyDiagramParm extends BaseEntity {
private Double lat;
private String target;
}

View File

@@ -45,5 +45,7 @@ public class AppLineTopologyDiagramPO extends BaseEntity {
@TableField(value = "lat")
private Double lat;
@TableField(value = "target")
private String target;
}

View File

@@ -1,5 +1,6 @@
package com.njcn.csdevice.pojo.po;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.bo.BaseEntity;
import lombok.Data;
@@ -43,6 +44,12 @@ public class CsDataArray extends BaseEntity {
*/
private String anotherName;
/**
* influxdb 存储的名称
*/
@TableField(exist = false)
private String influxDbName;
/**
* 字典序号
*/

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

@@ -1,8 +1,6 @@
package com.njcn.csdevice.pojo.vo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.bo.BaseEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
@@ -43,5 +41,6 @@ public class AppLineTopologyDiagramVO {
private String linePostion;
@ApiModelProperty(value="绑定的指标")
private String target;
}

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

@@ -167,6 +167,11 @@
<artifactId>message-api</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.njcn</groupId>
<artifactId>event-common</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<build>

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

@@ -65,7 +65,7 @@ public class CsLedgerController extends BaseController {
@PostMapping("/AppLineTree")
@ApiOperation("app端监测点树")
public HttpResult<List<CsLedgerVO>> appLineTree(){
String methodDescribe = getMethodDescribe("AppLineTree");
String methodDescribe = getMethodDescribe("appLineTree");
List<CsLedgerVO> list = csLedgerService.appLineTree();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}

View File

@@ -7,12 +7,8 @@ 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.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.param.DataArrayParam;
import com.njcn.csdevice.pojo.po.CsDataArray;
import com.njcn.csdevice.pojo.vo.DataArrayTreeVO;
import com.njcn.csdevice.pojo.vo.DeviceManagerDetailVO;
import com.njcn.csdevice.param.LineInfoParam;
import com.njcn.csdevice.service.DeviceMessageService;
import com.njcn.csdevice.service.ICsDataArrayService;
import com.njcn.user.pojo.po.User;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
@@ -22,7 +18,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;
@@ -47,8 +42,8 @@ public class DeviceMessageController extends BaseController {
@PostMapping("/getEventUserByDeviceId")
@ApiOperation("根据设备获取需要推送的用户id")
@ApiImplicitParams({
@ApiImplicitParam(name = "devId", value = "设备id", required = true, paramType = "query"),
@ApiImplicitParam(name = "isAdmin", value = "是否需要推送给管理员", required = true, paramType = "query")
@ApiImplicitParam(name = "devId", value = "设备id", required = true, paramType = "query"),
@ApiImplicitParam(name = "isAdmin", value = "是否需要推送给普通用户", required = true, paramType = "query")
})
public HttpResult<List<String>> getEventUserByDeviceId(@RequestParam("devId") String devId, @RequestParam("isAdmin") Boolean isAdmin){
String methodDescribe = getMethodDescribe("getEventUserByDeviceId");
@@ -69,10 +64,10 @@ public class DeviceMessageController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getLineInfo")
@ApiOperation("获取监测点信息")
@ApiImplicitParam(name = "id", value = "参数", required = true, paramType = "query")
public HttpResult<String> getLineInfo(@RequestParam("id") String id){
@ApiImplicitParam(name = "param", value = "参数", required = true)
public HttpResult<String> getLineInfo(@RequestBody LineInfoParam param){
String methodDescribe = getMethodDescribe("getLineInfo");
deviceMessageService.getLineInfo(id);
deviceMessageService.getLineInfo(param.getNDid(),param.getList());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, "success", methodDescribe);
}

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,6 +1,7 @@
package com.njcn.csdevice.service;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.user.pojo.po.User;
import java.util.List;
@@ -14,6 +15,6 @@ public interface DeviceMessageService {
List<User> getSendUserByType(DeviceMessageParam param);
void getLineInfo(String id);
void getLineInfo(String id,List<CsLinePO> list);
}

View File

@@ -0,0 +1,17 @@
package com.njcn.csdevice.service;
import com.njcn.influx.pojo.po.cs.PqdData;
import java.util.List;
import java.util.Map;
/**
* PqdData数据拆分服务
*
* @author system
* @since 2026-05-22
*/
public interface IPqdDataSplitService {
Map<String, Object> splitPqdData(List<PqdData> pqdDataList);
}

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

@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.mapper.AppLineTopologyDiagramMapper;
import com.njcn.csdevice.mapper.CsLedgerMapper;
import com.njcn.csdevice.pojo.param.AppTopologyDiagramQueryParm;
import com.njcn.csdevice.pojo.param.LinePostionParam;
import com.njcn.csdevice.pojo.po.AppLineTopologyDiagramPO;
@@ -13,11 +12,14 @@ import com.njcn.csdevice.pojo.po.CsLedger;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.pojo.vo.AppLineTopologyDiagramVO;
import com.njcn.csdevice.pojo.vo.AppTopologyDiagramVO;
import com.njcn.csdevice.pojo.vo.CsLineTopologyTemplateVO;
import com.njcn.csdevice.service.AppLineTopologyDiagramService;
import com.njcn.csdevice.service.AppTopologyDiagramService;
import com.njcn.csdevice.service.CsLinePOService;
import com.njcn.csdevice.service.ICsLedgerService;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.pojo.vo.DictTreeVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -41,6 +43,9 @@ public class AppLineTopologyDiagramServiceImpl extends ServiceImpl<AppLineTopolo
private final CsLinePOService csLinePOService;
private final AppTopologyDiagramService appTopologyDiagramService;
private final ICsLedgerService iCsLedgerService;
private final RedisUtil redisUtil;
private final DictTreeFeignClient dictTreeFeignClient;
@Override
public AppTopologyDiagramVO query(String devId) {
CsLedger one = iCsLedgerService.lambdaQuery().eq(CsLedger::getId, devId).eq(CsLedger::getState,1).one();
@@ -73,7 +78,7 @@ public class AppLineTopologyDiagramServiceImpl extends ServiceImpl<AppLineTopolo
}
public List<AppLineTopologyDiagramVO> queryByLineIds(List<String> lineIds) {
List<AppLineTopologyDiagramVO> result = new ArrayList<>();
if (lineIds != null && lineIds.size() > 0) {
if (lineIds != null && !lineIds.isEmpty()) {
result = this.getBaseMapper().queryByLineIds( lineIds);
}
return result;
@@ -83,15 +88,22 @@ public class AppLineTopologyDiagramServiceImpl extends ServiceImpl<AppLineTopolo
@Override
@Transactional(rollbackFor = Exception.class)
public void auditList(LinePostionParam linePostionParam) {
linePostionParam.getPointList().forEach(temp->{
csLinePOService.lambdaUpdate().eq(CsLinePO::getLineId,temp.getLineId()).set(CsLinePO::getName,temp.getName()).set(CsLinePO::getPosition,temp.getLinePostion()).update();
this.lambdaUpdate().eq(AppLineTopologyDiagramPO::getId,temp.getId()).
eq(AppLineTopologyDiagramPO::getLineId,temp.getLineId()).set(AppLineTopologyDiagramPO::getLat,temp.getLat()).
set(AppLineTopologyDiagramPO::getLng,temp.getLng()).set(AppLineTopologyDiagramPO::getId,linePostionParam.getId()).update();
iCsLedgerService.lambdaUpdate().eq(CsLedger::getId,temp.getLineId()).set(CsLedger::getName,temp.getName()).update();
set(AppLineTopologyDiagramPO::getLng,temp.getLng()).set(AppLineTopologyDiagramPO::getId,linePostionParam.getId())
.set(AppLineTopologyDiagramPO::getTarget,temp.getTarget())
.update();
iCsLedgerService.lambdaUpdate().eq(CsLedger::getId,temp.getLineId()).set(CsLedger::getName,temp.getName()).update();
});
//修改指标后,删除缓存数据
String deviceId = csLinePOService.getById(linePostionParam.getPointList().get(0).getLineId()).getDeviceId();
DictTreeVO dictTreeVO = dictTreeFeignClient.queryByCode("baseData").getData();
String key = deviceId + "#";
if (dictTreeVO != null) {
key = deviceId + "#" + dictTreeVO.getId();
}
redisUtil.delete(key);
}
}

View File

@@ -1,22 +1,26 @@
package com.njcn.csdevice.service.impl;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.mapper.CsDataArrayMapper;
import com.njcn.csdevice.pojo.dto.DataArrayDTO;
import com.njcn.csdevice.pojo.param.DataArrayParam;
import com.njcn.csdevice.pojo.po.CsDataArray;
import com.njcn.csdevice.pojo.po.CsDataSet;
import com.njcn.csdevice.pojo.vo.DataArrayTreeVO;
import com.njcn.csdevice.pojo.vo.DeviceManagerDetailVO;
import com.njcn.csdevice.service.ICsDataArrayService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -33,6 +37,7 @@ import java.util.stream.Collectors;
public class CsDataArrayServiceImpl extends ServiceImpl<CsDataArrayMapper, CsDataArray> implements ICsDataArrayService {
private final EpdFeignClient epdFeignClient;
private final DicDataFeignClient dicDataFeignClient;
@Override
public List<CsDataArray> getArrayBySet(String dataSet) {
@@ -52,7 +57,7 @@ public class CsDataArrayServiceImpl extends ServiceImpl<CsDataArrayMapper, CsDat
for (Map.Entry<String, List<EleEpdPqd>> entry : map.entrySet()) {
DeviceManagerDetailVO vo = new DeviceManagerDetailVO();
EleEpdPqd eleEpdPqd = entry.getValue().get(0);
if (Objects.equals(eleEpdPqd.getPhase(),"M")){
if (Objects.equals(eleEpdPqd.getPhase(),"T")){
vo.setPhasic("/");
} else {
vo.setPhasic(entry.getValue().stream().map(EleEpdPqd::getPhase).collect(Collectors.joining(",")));
@@ -104,7 +109,7 @@ public class CsDataArrayServiceImpl extends ServiceImpl<CsDataArrayMapper, CsDat
DataArrayTreeVO vo3 = new DataArrayTreeVO();
vo3.setId(item.getDataSetId() + item.getDataArrayName()+item2);
vo3.setName(item2);
if (Objects.equals(item2,"M")){
if (Objects.equals(item2,"T")){
vo3.setShowName("无相别");
} else {
vo3.setShowName(item2);
@@ -173,7 +178,34 @@ public class CsDataArrayServiceImpl extends ServiceImpl<CsDataArrayMapper, CsDat
@Override
public List<CsDataArray> findListByParam(DataArrayParam param) {
return this.baseMapper.findListByParam(param);
List<CsDataArray> list = this.baseMapper.findListByParam(param);
if (!CollectionUtils.isEmpty(list)) {
DictData pqd = dicDataFeignClient.getDicDataByCode(DicDataEnum.PQD.getCode()).getData();
if (ObjectUtil.isNotNull(pqd) && ObjectUtil.isNotNull(pqd.getId())) {
List<EleEpdPqd> epdList = epdFeignClient.dictMarkByDataType(pqd.getId()).getData();
if (!CollectionUtils.isEmpty(epdList)) {
Map<String, EleEpdPqd> epdPqdMap = epdList.stream().collect(Collectors.toMap(EleEpdPqd::getId, Function.identity()));
list.forEach(item->{
EleEpdPqd epdPqd = epdPqdMap.get(item.getDataId());
if (!Objects.isNull(epdPqd)) {
if (epdPqd.getOtherName() == null || epdPqd.getOtherName().isEmpty()) {
item.setInfluxDbName(epdPqd.getName());
} else {
String[] parts = item.getName().split("_");
String lastPart = parts[parts.length - 1];
boolean isLastNumeric = lastPart.matches("\\d+");
if (isLastNumeric) {
item.setInfluxDbName(epdPqd.getOtherName() + "_" + lastPart);
} else {
item.setInfluxDbName(epdPqd.getOtherName());
}
}
}
});
}
}
}
return list;
}
@Override

View File

@@ -38,7 +38,7 @@ public class CsDataSetServiceImpl extends ServiceImpl<CsDataSetMapper, CsDataSet
.eq(CsDataSet::getPid,modelId)
.in(CsDataSet::getType, Arrays.asList(0,2))
.eq(CsDataSet::getStoreFlag,1)
.and(i->i.eq(CsDataSet::getDataType,"Stat").or().isNull(CsDataSet::getDataType))
// .and(i->i.eq(CsDataSet::getDataType,"Stat").or().isNull(CsDataSet::getDataType))
.orderByAsc(CsDataSet::getIdx)
.list();
}

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

@@ -46,6 +46,7 @@ import com.njcn.csdevice.service.*;
import com.njcn.csdevice.util.QRCodeUtil;
import com.njcn.csdevice.utils.ExcelStyleUtil;
import com.njcn.csdevice.utils.StringUtil;
import com.njcn.csharmonic.api.CsHarmonicPlanLineFeignClient;
import com.njcn.csharmonic.api.EventUserFeignClient;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
@@ -128,6 +129,7 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
private final UserFeignClient userFeignClient;
private final OverLimitWlMapper overLimitWlMapper;
private final CsLedgerFeignClient csLedgerFeignClient;
private final CsHarmonicPlanLineFeignClient csHarmonicPlanLineFeignClient;
@Override
public void refreshDeviceDataCache() {
@@ -214,6 +216,8 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
csLinePOService.remove(csLinePOLambdaQueryWrapper);
//删除监测点限值
overLimitWlMapper.deleteBatchIds(collect);
//删除配置
csHarmonicPlanLineFeignClient.deleteByLineIds(collect);
QueryWrapper<AppLineTopologyDiagramPO> appLineTopologyDiagramPOQueryWrapper = new QueryWrapper<>();
appLineTopologyDiagramPOQueryWrapper.clear();
@@ -524,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;
@@ -316,24 +313,28 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
if(Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())){
throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
}
Double ct = finalCsLinePOList.get(0).getCtRatio();
Double pt = finalCsLinePOList.get(0).getPtRatio();
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(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();
commonQueryParam.setLineId(temp.getLineId());
commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
commonQueryParam.setColumnName(epdPqd.getName()+ (StringUtils.isEmpty(param.getFrequency()) ? "":"_"+param.getFrequency()));
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.setDataType(commonStatisticalQueryParam.getValueType());
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType().toUpperCase());
commonQueryParam.setProcess(data1.get(0).getProcess()+"");
commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
return commonQueryParam;
@@ -343,7 +344,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
String unit;
ThdDataVO vo = new ThdDataVO();
vo.setLineId(temp.getLineId());
vo.setPhase(Objects.equals("M",temp.getPhaseType())?null:temp.getPhaseType());
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());
@@ -451,21 +452,6 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
vo.setAnotherName(epdPqd.getShowName());
return vo;
}).collect(Collectors.toList());
//长时闪变
if (Objects.equals(epdPqd.getOtherName(), "plt")) {
List<Instant> timeInstants = getTimeInstants(commonStatisticalQueryParam.getStartTime(), commonStatisticalQueryParam.getEndTime(), 2, ChronoUnit.HOURS, DEFAULT_ZONE);
collect1 = collect1.stream()
.filter(vo -> timeInstants.contains(vo.getTime()))
.collect(Collectors.toList());
}
//短时闪变 || 电压波动
else if (Objects.equals(epdPqd.getOtherName(), "pst") || Objects.equals(epdPqd.getOtherName(), "fluc")) {
List<Instant> timeInstants = getTimeInstants(commonStatisticalQueryParam.getStartTime(), commonStatisticalQueryParam.getEndTime(), 10, ChronoUnit.MINUTES, DEFAULT_ZONE);
collect1 = collect1.stream()
.filter(vo -> timeInstants.contains(vo.getTime()))
.collect(Collectors.toList());
}
result.addAll(collect1);
});
}
@@ -493,8 +479,13 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
commonQueryParam.setLineId(temp.getLineId());
commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
commonQueryParam.setColumnName(epdPqd.getName()+ finalFrequency);
if (epdPqd.getName() == null || epdPqd.getName().isEmpty()) {
commonQueryParam.setColumnName(epdPqd.getName()+ finalFrequency);
} else {
commonQueryParam.setColumnName(epdPqd.getOtherName()+ finalFrequency);
}
commonQueryParam.setPhasic(epdPqd.getPhase());
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType() == null ? DataParam.portableDevStatisticalMethods:commonStatisticalQueryParam.getValueType());
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType() == null ? DataParam.portableDevStatisticalMethods.toUpperCase():commonStatisticalQueryParam.getValueType().toUpperCase());
commonQueryParam.setProcess(data1.get(0).getProcess()+"");
commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
return commonQueryParam;
@@ -503,7 +494,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
ThdDataVO vo = new ThdDataVO();
vo.setLineId(temp.getLineId());
vo.setPhase(Objects.equals("M",temp.getPhaseType())?null:temp.getPhaseType());
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());
@@ -579,24 +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
ZonedDateTime current = startDate.atStartOfDay(zone);
ZonedDateTime endDateTime = endDate.atTime(23, 59, 59).atZone(zone);
while (!current.isAfter(endDateTime)) {
instants.add(current.toInstant());
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){
@@ -659,7 +791,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
ThdDataVO vo = new ThdDataVO();
vo.setLineId(temp.getLineId());
vo.setPhase(Objects.equals("M",temp.getPhaseType())?null:temp.getPhaseType());
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());
@@ -736,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->{
@@ -759,7 +891,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
ThdDataVO vo = new ThdDataVO();
vo.setLineId(temp.getLineId());
vo.setPhase(Objects.equals("M",temp.getPhaseType())?null:temp.getPhaseType());
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());
@@ -838,23 +970,25 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
if(Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())) {
throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
}
Double ct = finalCsLinePO.getCtRatio();
Double pt = finalCsLinePO.getPtRatio();
Double ct = finalCsLinePO.getCtRatio() / (Objects.isNull(finalCsLinePO.getCt2Ratio())?1.0:finalCsLinePO.getCt2Ratio());
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());
commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
commonQueryParam.setColumnName(epdPqd.getName() + (StringUtils.isEmpty(param.getFrequency()) ? "" : "_" + param.getFrequency()));
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(trendDataQueryParam.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATETIME_PATTERN));
commonQueryParam.setEndTime(DateUtil.format(DateUtil.endOfDay(DateUtil.parse(trendDataQueryParam.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN)), DatePattern.NORM_DATETIME_PATTERN));
commonQueryParam.setDataType(trendDataQueryParam.getValueType());
commonQueryParam.setDataType(trendDataQueryParam.getValueType().toUpperCase());
commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(finalCsLinePO.getLineId()));
List<StatisticalDataDTO> deviceRtData = commonService.getNewDeviceRtDataByTime(Collections.singletonList(commonQueryParam));
@@ -862,7 +996,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
String unit;
ThdDataVO vo = new ThdDataVO();
vo.setLineId(temp.getLineId());
vo.setPhase(Objects.equals("M", temp.getPhaseType()) ? null : temp.getPhaseType());
vo.setPhase(Objects.equals("T", temp.getPhaseType()) ? null : temp.getPhaseType());
String position = finalCsLinePO.getPosition();
vo.setPosition(position);
vo.setTime(temp.getTime());
@@ -970,21 +1104,6 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
vo.setAnotherName(epdPqd.getShowName());
return vo;
}).collect(Collectors.toList());
//长时闪变
if (Objects.equals(epdPqd.getOtherName(), "plt")) {
List<Instant> timeInstants = getTimeInstants(trendDataQueryParam.getSearchBeginTime(), trendDataQueryParam.getSearchEndTime(), 2, ChronoUnit.HOURS, DEFAULT_ZONE);
collect1 = collect1.stream()
.filter(vo -> timeInstants.contains(vo.getTime()))
.collect(Collectors.toList());
}
//短时闪变 || 电压波动
else if (Objects.equals(epdPqd.getOtherName(), "pst") || Objects.equals(epdPqd.getOtherName(), "fluc")) {
List<Instant> timeInstants = getTimeInstants(trendDataQueryParam.getSearchBeginTime(), trendDataQueryParam.getSearchEndTime(), 10, ChronoUnit.MINUTES, DEFAULT_ZONE);
collect1 = collect1.stream()
.filter(vo -> timeInstants.contains(vo.getTime()))
.collect(Collectors.toList());
}
result.addAll(collect1);
}
}
@@ -1000,9 +1119,10 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
if(Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())){
throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
}
Double ct = finalCsLinePO.getCtRatio();
Double pt = finalCsLinePO.getPtRatio();
// String position = finalCsLinePO.getPosition();
Double ct = finalCsLinePO.getCtRatio() / (Objects.isNull(finalCsLinePO.getCt2Ratio())?1.0:finalCsLinePO.getCt2Ratio());
Double pt = finalCsLinePO.getPtRatio() / (Objects.isNull(finalCsLinePO.getPt2Ratio())?1.0:finalCsLinePO.getPt2Ratio());
// String position = finalCsLinePO.getPosition();
Overlimit overlimit = overLimitWlMapper.selectById(finalCsLinePO.getLineId());
if (Objects.isNull(overlimit)) {
throw new BusinessException("当前测点限值信息缺失,请联系管理员排查");
@@ -1011,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();
@@ -1038,7 +1158,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
ThdDataVO vo = new ThdDataVO();
vo.setLineId(temp.getLineId());
// vo.setLineName(finalCsLinePO.getName());
vo.setPhase(Objects.equals("M", temp.getPhaseType()) ? null : temp.getPhaseType());
vo.setPhase(Objects.equals("T", temp.getPhaseType()) ? null : temp.getPhaseType());
// vo.setPosition(position);
vo.setTime(temp.getTime());
vo.setStatMethod(commonQueryParam.getDataType());
@@ -1208,7 +1328,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
TrendDataQueryParam trendDataQueryParam = new TrendDataQueryParam();
trendDataQueryParam.setSearchBeginTime(param.getSearchBeginTime());
trendDataQueryParam.setSearchEndTime(param.getSearchEndTime());
trendDataQueryParam.setValueType(param.getValueType());
trendDataQueryParam.setValueType(param.getValueType().toUpperCase());
trendDataQueryParam.setDataLevel(param.getDataLevel());
List<SensitiveUserTrendDataQueryParam> paramList = param.getList();
List<TrendDataQueryParam> indexList = paramList.stream().map(item -> {

View File

@@ -846,6 +846,7 @@ public class CsLedgerServiceImpl extends ServiceImpl<CsLedgerMapper, CsLedger> i
device.setEquipmentName(dev.getName());
device.setEquipmentId(devId);
device.setDevMac(po.getMac());
device.setNDid(po.getNdid());
device.setProjectId("/");
device.setProjectName("/");
device.setEngineeringid("/");
@@ -854,6 +855,7 @@ public class CsLedgerServiceImpl extends ServiceImpl<CsLedgerMapper, CsLedger> i
device.setEquipmentName(dev.getName());
device.setEquipmentId(devId);
device.setDevMac(po.getMac());
device.setNDid(po.getNdid());
CsLedger project = this.findDataById(dev.getPid());
if (ObjectUtil.isNotNull(project)) {
device.setProjectId(project.getId());

View File

@@ -10,7 +10,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.access.api.CsLineLatestDataFeignClient;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
@@ -24,7 +23,11 @@ import com.njcn.csdevice.pojo.vo.PqSensitiveUserLineVO;
import com.njcn.csdevice.service.CsDevModelService;
import com.njcn.csdevice.service.CsLinePOService;
import com.njcn.csdevice.service.ICsDataSetService;
import com.njcn.csharmonic.api.CsHarmonicPlanFeignClient;
import com.njcn.csharmonic.api.CsHarmonicPlanLineFeignClient;
import com.njcn.csharmonic.api.PqSensitiveUserFeignClient;
import com.njcn.csharmonic.param.CsHarmonicPlanLineParam;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlan;
import com.njcn.device.biz.pojo.po.PqSensitiveUser;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
@@ -64,7 +67,6 @@ public class CsLinePOServiceImpl extends ServiceImpl<CsLinePOMapper, CsLinePO> i
private final ICsDataSetService csDataSetService;
private final DicDataFeignClient dicDataFeignClient;
private final CsTerminalLogsMapper csTerminalLogsMapper;
private final CsLineLatestDataFeignClient csLineLatestDataFeignClient;
private final PqSensitiveUserFeignClient pqSensitiveUserFeignClient;
private final FileStorageUtil fileStorageUtil;
@@ -72,6 +74,8 @@ public class CsLinePOServiceImpl extends ServiceImpl<CsLinePOMapper, CsLinePO> i
private final CsEquipmentDeliveryMapper csEquipmentDeliveryMapper;
private final CsDeviceUserPOMapper csDeviceUserPOMapper;
private final DictTreeFeignClient dictTreeFeignClient;
private final CsHarmonicPlanFeignClient csHarmonicPlanFeignClient;
private final CsHarmonicPlanLineFeignClient csHarmonicPlanLineFeignClient;
@Override
@@ -171,6 +175,17 @@ public class CsLinePOServiceImpl extends ServiceImpl<CsLinePOMapper, CsLinePO> i
csLedger.setState(1);
csLedger.setSort(0);
csLedgerMapper.insert(csLedger);
//3.新增稳态事件指标配置
csHarmonicPlanLineFeignClient.deleteByLineIds(Collections.singletonList(lineId));
List<CsHarmonicPlan> planList = csHarmonicPlanFeignClient.getByName("通用方案").getData();
if (CollectionUtil.isNotEmpty(planList)) {
CsHarmonicPlan plan = planList.get(0);
CsHarmonicPlanLineParam param1 = new CsHarmonicPlanLineParam();
param1.setId(plan.getId());
param1.setLineIds(Collections.singletonList(lineId));
csHarmonicPlanLineFeignClient.savePlanLines(param1);
}
return po;
}
@@ -234,6 +249,8 @@ public class CsLinePOServiceImpl extends ServiceImpl<CsLinePOMapper, CsLinePO> i
this.removeById(id);
csLedgerMapper.deleteById(id);
//删除稳态事件指标配置
csHarmonicPlanLineFeignClient.deleteByLineIds(Collections.singletonList(id));
//新增台账日志
CsTerminalLogs csTerminalLogs = new CsTerminalLogs();
@@ -473,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

@@ -1,6 +1,7 @@
package com.njcn.csdevice.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@@ -163,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);
@@ -177,30 +178,13 @@ public class CsTerminalReplyServiceImpl extends ServiceImpl<CsTerminalReplyMappe
QueryWrapper<CsTerminalReply> queryWrapper = new QueryWrapper<>();
if (StrUtil.isNotBlank(param.getSearchValue())) {
queryWrapper.like("cs_terminal_reply.line_id", param.getSearchValue());
// //获取监测点id
// List<CsLinePO> list = csLinePOService.getLineByName(param.getSearchValue());
// if (CollectionUtil.isEmpty(list)) {
// return page;
// } else {
// queryWrapper.and(pr -> {
// // 获取所有 lineId
// List<String> lineIds = list.stream()
// .map(CsLinePO::getLineId)
// .collect(Collectors.toList());
// // 使用 OR 条件连接多个 lineId
// for (int i = 0; i < lineIds.size(); i++) {
// if (i == 0) {
// pr.like("cs_terminal_reply.line_id", lineIds.get(i));
// } else {
// pr.or().like("cs_terminal_reply.line_id", lineIds.get(i));
// }
// }
// });
// }
}
queryWrapper.between("cs_terminal_reply.Create_Time"
, DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime()))
, 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();
@@ -209,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();
@@ -278,6 +265,9 @@ public class CsTerminalReplyServiceImpl extends ServiceImpl<CsTerminalReplyMappe
case "oneFile":
result = "补召单事件波形";
break;
case "harmonic":
result = "稳态数据";
break;
default:
result = "未知";
}

View File

@@ -1,7 +1,6 @@
package com.njcn.csdevice.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsDeviceUserFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.po.CsLinePO;
@@ -18,6 +17,7 @@ import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import com.njcn.user.pojo.po.app.AppInfoSet;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.*;
@@ -25,6 +25,7 @@ import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
class DeviceMessageServiceImpl implements DeviceMessageService {
private final AppUserFeignClient appUserFeignClient;
@@ -37,17 +38,17 @@ class DeviceMessageServiceImpl implements DeviceMessageService {
@Override
public List<String> getEventUserByDeviceId(String devId, Boolean isAdmin) {
List<String> list = csDeviceUserFeignClient.findUserById(devId).getData();
List<String> result = new ArrayList<>(list);
List<User> adminUser = appUserFeignClient.getAdminInfo().getData();
List<String> adminList = adminUser.stream().map(User::getId).collect(Collectors.toList());
if (isAdmin) {
List<User> adminUser = appUserFeignClient.getAdminInfo().getData();
List<String> adminList = adminUser.stream().map(User::getId).collect(Collectors.toList());
result.addAll(adminList);
List<String> list = csDeviceUserFeignClient.findUserById(devId).getData();
List<String> result = new ArrayList<>(list);
adminList.addAll(result);
}
if (CollectionUtil.isNotEmpty(result)) {
result = result.stream().distinct().collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(adminList)) {
adminList = adminList.stream().distinct().collect(Collectors.toList());
}
return result;
return adminList;
}
@Override
@@ -86,11 +87,17 @@ class DeviceMessageServiceImpl implements DeviceMessageService {
}
@Override
public void getLineInfo(String id) {
public void getLineInfo(String id, List<CsLinePO> list) {
Map<Integer,String> map = new HashMap<>();
List<CsLinePO> lineList = csLinePOService.findByNdid(id);
List<CsLinePO> lineList;
if (CollectionUtil.isNotEmpty(list) && list != null) {
lineList = list;
} else {
lineList = csLinePOService.findByNdid(id);
}
if (CollectionUtil.isEmpty(lineList)){
throw new BusinessException("监测点为空");
log.error("监测点为空");
return;
}
for (CsLinePO item : lineList) {
if (Objects.isNull(item.getPosition()) || item.getPosition().isEmpty()){

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,27 +2,27 @@ package com.njcn.csdevice.service.impl;
import cn.hutool.core.util.IdUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.advance.api.EventCauseFeignClient;
import com.njcn.advance.pojo.dto.EventAnalysisDTO;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.constant.DataParam;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.mapper.PortableOfflLogMapper;
import com.njcn.csdevice.param.UploadDataParam;
import com.njcn.csdevice.pojo.dto.CsEquipmentDeliveryDTO;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.pojo.po.PortableOffMainLog;
import com.njcn.csdevice.pojo.po.PortableOfflLog;
import com.njcn.csdevice.pojo.po.WlRecord;
import com.njcn.csdevice.service.CsLinePOService;
import com.njcn.csdevice.service.IPortableOfflLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.csdevice.param.UploadDataParam;
import com.njcn.csdevice.service.IWlRecordService;
import com.njcn.csdevice.service.PortableOffMainLogService;
import com.njcn.csdevice.service.*;
import com.njcn.csdevice.util.InfluxDbParamUtil;
import com.njcn.csharmonic.api.EventFeignClient;
import com.njcn.csharmonic.api.OfflineDataUploadFeignClient;
@@ -36,13 +36,17 @@ import com.njcn.csharmonic.offline.mincfg.AnalyseComtradeCfg;
import com.njcn.csharmonic.offline.mincfg.vo.CmnModeCfg;
import com.njcn.csharmonic.offline.vo.Response;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.influx.imapper.EvtDataMapper;
import com.njcn.influx.imapper.PqdDataMapper;
import com.njcn.event.common.mapper.WlRmpEventDetailMapper;
import com.njcn.event.pojo.po.RmpEventDetailPO;
import com.njcn.influx.imapper.*;
import com.njcn.influx.pojo.po.*;
import com.njcn.influx.pojo.po.cs.EntData;
import com.njcn.influx.pojo.po.cs.PqdData;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.EleEvtFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.web.pojo.param.BaseParam;
import lombok.RequiredArgsConstructor;
@@ -50,11 +54,10 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
@@ -81,29 +84,37 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
private final DecimalFormat df = new DecimalFormat("#0.000");
private final FileStorageUtil fileStorageUtil;
private final DicDataFeignClient dicDataFeignClient;
private final OfflineDataUploadFeignClient offlineDataUploadFeignClient;
private final EleEvtFeignClient eleEvtFeignClient;
private final EventFeignClient eventFeignClient;
private final EquipmentFeignClient equipmentFeignClient;
private final InfluxDbParamUtil influxDbParamUtil;
private final PqdDataMapper pqdDataMapper;
private final EvtDataMapper evtDataMapper;
private final DataVMapper dataVMapper;
private final DataIMapper dataIMapper;
private final DataHarmRateVMapper dataHarmRateV;
private final DataHarmRateIMapper dataHarmRateI;
private final DataInHarmVMapper dataInHarmV;
private final DataHarmPowerPMapper dataHarmPowerP;
private final DataHarmPowerQMapper dataHarmPowerQ;
private final DataHarmPowerSMapper dataHarmPowerS;
private final DataFlickerMapper dataFlicker;
private final DataFlucMapper dataFluc;
private final DataPltMapper dataPlt;
private final DataHarmPhasicVMapper dataHarmPhasicV;
private final DataHarmPhasicIMapper dataHarmPhasicI;
private final IPqdDataSplitService pqdDataSplitService;
private final MqttPublisher publisher;
private final PortableOffMainLogService portableOffMainLogService;
private final IWlRecordService wlRecordService;
private final CsLinePOService csLinePOService;
private final WlRmpEventDetailMapper wlRmpEventDetailMapper;
private final EventCauseFeignClient eventCauseFeignClient;
@Override
public Page<PortableOfflLog> queryPage(BaseParam baseParam) {
@@ -177,7 +188,7 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
}
@Override
@Transactional(rollbackFor = {Exception.class})
@DSTransactional
public void importEquipment(UploadDataParam uploadDataParam){
String lineId = uploadDataParam.getLineId();
//获取监测点信息
@@ -337,7 +348,6 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
.eq(WlRecord::getEndTime,wlRecord.getEndTime()).update();
wlRecordService.save(wlRecord);
//如果明确返回了state 那么当前文件解析出错
if(response.getState() != null){
portableOfflLog.setState(response.getState());
@@ -353,7 +363,8 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
List<List<PqdData>> partition = ListUtils.partition(pqdData, 1500);
for (List<PqdData> sliceList : partition) {
List<PqdData> sublistAsOriginalListType = new ArrayList<>(sliceList);
pqdDataMapper.insertBatch(sublistAsOriginalListType);
Map<String, Object> map = pqdDataSplitService.splitPqdData(sublistAsOriginalListType);
insertData(map);
}
//min结果集解析入库后就不需要在解析了
minFlag = false;
@@ -381,6 +392,8 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
}
List<NewTaglogbuffer> newTaglogbuffers = (List<NewTaglogbuffer>) response.getObj();
if(newTaglogbuffers != null && !newTaglogbuffers.isEmpty()){
List<DictData> list1 = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_REASON.getCode()).getData();
List<DictData> list2 = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()).getData();
//否则正常标记为成功解析
portableOfflLog.setState(1);
portableOfflLog.setAllCount(newTaglogbuffers.size());
@@ -451,14 +464,32 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
}
}
csEventPO.setWavePath(wavePath);
if (Objects.equals(csEventPO.getTag(),DataParam.dipStrName)) {
EventAnalysisDTO var1 = new EventAnalysisDTO();
var1.setWlFilePath(wavePath);
EventAnalysisDTO dto = eventCauseFeignClient.analysisCauseAndType(var1).getData();
String id1 = list1.stream()
.filter(item -> Objects.equals(item.getAlgoDescribe(), dto.getCause()))
.map(DictData::getId)
.findFirst()
.orElse(null);
csEventPO.setAdvanceReason(id1);
String id2 = list2.stream()
.filter(item -> Objects.equals(item.getAlgoDescribe(), dto.getType()))
.map(DictData::getId)
.findFirst()
.orElse(null);
csEventPO.setAdvanceType(id2);
}
//默认暂态事件
csEventPO.setType(0);
String clDid = influxDbParamUtil.getClDidByLineId(uploadDataParam.getLineId());
csEventPO.setClDid(clDid == null ? null : Integer.parseInt(clDid));
csEventPO.setProcess(csEquipmentDeliveryDTO.getProcess());
csEventPOS.add(csEventPO);
EntData entData = new EntData();
entData.setUuid(csEventPO.getId());
entData.setTime(new Date().toInstant());
@@ -503,12 +534,19 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
log.info("类型log,插入infulxDb的evtData");
try {
evtDataMapper.insertOne(entData);
//添加其余数据
csEventPO.setPhase(entData.getEvtParamPhase());
csEventPO.setPersistTime(entData.getEvtParamTm());
csEventPO.setAmplitude(entData.getEvtParamVVaDepth());
csEventPOS.add(csEventPO);
} catch (Exception e) {
e.printStackTrace();
}
}
log.info("类型log,插入mysql事件表cs_event");
eventFeignClient.saveBatchEventList(csEventPOS);
//同步数据到 r_mp_event_detail
csEventPOS.forEach(this::insertEvent);
}
}
}
@@ -529,6 +567,62 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
portableOffMainLogService.save(portableOffMainLog);
}
public void insertEvent(CsEventPO item) {
RmpEventDetailPO rmpEventDetailPo = new RmpEventDetailPO();
rmpEventDetailPo.setEventId(item.getId());
rmpEventDetailPo.setMeasurementPointId(item.getLineId());
rmpEventDetailPo.setStartTime(item.getStartTime());
rmpEventDetailPo.setEventType(getEventType(item.getTag()));
rmpEventDetailPo.setFeatureAmplitude(item.getAmplitude());
rmpEventDetailPo.setDuration(item.getPersistTime());
rmpEventDetailPo.setEventDescribe(getTag(item.getTag()));
rmpEventDetailPo.setDealFlag(0);
rmpEventDetailPo.setFileFlag(0);
rmpEventDetailPo.setPhase(item.getPhase());
rmpEventDetailPo.setAdvanceReason(item.getAdvanceReason());
rmpEventDetailPo.setAdvanceType(item.getAdvanceType());
wlRmpEventDetailMapper.insert(rmpEventDetailPo);
}
public String getTag(String tag) {
switch (tag) {
case "Evt_Sys_DipStr":
tag = DicDataEnum.VOLTAGE_DIP.getCode();
break;
case "Evt_Sys_SwlStr":
tag = DicDataEnum.VOLTAGE_RISE.getCode();
break;
case "Evt_Sys_IntrStr":
tag = DicDataEnum.SHORT_INTERRUPTIONS.getCode();
break;
default:
tag = "Un_Know";
break;
}
return tag;
}
public String getEventType(String tag) {
switch (tag) {
case "Evt_Sys_DipStr":
DictData dip = dicDataFeignClient.getDicDataByCode(DicDataEnum.VOLTAGE_DIP.getCode()).getData();
tag = dip.getId();
break;
case "Evt_Sys_SwlStr":
DictData rise = dicDataFeignClient.getDicDataByCode(DicDataEnum.VOLTAGE_RISE.getCode()).getData();
tag = rise.getId();
break;
case "Evt_Sys_IntrStr":
DictData interruptions = dicDataFeignClient.getDicDataByCode(DicDataEnum.SHORT_INTERRUPTIONS.getCode()).getData();
tag = interruptions.getId();
break;
default:
tag = "Un_Know";
break;
}
return tag;
}
@Override
public Page<PortableOffMainLog> queryMainLogPage(BaseParam baseParam) {
Page<PortableOffMainLog> returnpage = new Page<> (baseParam.getPageNum(), baseParam.getPageSize ());
@@ -587,7 +681,7 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
String dictDataCode = null;
switch (volConType) {
case 0:
dictDataCode = "star";
dictDataCode = "Trans_Business";
break;
case 1:
dictDataCode = "Star_Triangle";
@@ -604,4 +698,87 @@ public class PortableOfflLogServiceImpl extends ServiceImpl<PortableOfflLogMappe
}
return Objects.isNull(result)?null:result;
}
public void insertData(Map<String, Object> map) {
//13张表
map.forEach((key, value) -> {
switch (key) {
case "data_v":
dataVMapper.insertBatch((List<DataV>) value);
break;
case "data_i":
dataIMapper.insertBatch((List<DataI>) value);
break;
case "data_flicker":
//10分钟入一组
List<DataFlicker> list = (List<DataFlicker>) value;
if (!CollectionUtils.isEmpty(list)) {
list.forEach(item->{
Instant time = getTime(item.getTime(),600);
item.setTime(time);
});
dataFlicker.insertBatch(list);
}
break;
case "data_fluc":
//10分钟入一组
List<DataFluc> list2 = (List<DataFluc>) value;
if (!CollectionUtils.isEmpty(list2)) {
list2.forEach(item->{
Instant time = getTime(item.getTime(),600);
item.setTime(time);
});
dataFluc.insertBatch(list2);
}
break;
case "data_harmphasic_i":
dataHarmPhasicI.insertBatch((List<DataHarmPhasicI>) value);
break;
case "data_harmphasic_v":
dataHarmPhasicV.insertBatch((List<DataHarmPhasicV>) value);
break;
case "data_harmpower_p":
dataHarmPowerP.insertBatch((List<DataHarmPowerP>) value);
break;
case "data_harmpower_q":
dataHarmPowerQ.insertBatch((List<DataHarmPowerQ>) value);
break;
case "data_harmpower_s":
dataHarmPowerS.insertBatch((List<DataHarmPowerS>) value);
break;
case "data_harmrate_v":
dataHarmRateV.insertBatch((List<DataHarmRateV>) value);
break;
case "data_harmrate_i":
dataHarmRateI.insertBatch((List<DataHarmRateI>) value);
break;
case "data_inharm_v":
dataInHarmV.insertBatch((List<DataInHarmV>) value);
break;
case "data_plt":
//2小时入一组
List<DataPlt> list3 = (List<DataPlt>) value;
if (!CollectionUtils.isEmpty(list3)) {
list3.forEach(item->{
Instant time = getTime(item.getTime(),7200);
item.setTime(time);
});
dataPlt.insertBatch(list3);
}
break;
case "pqd_data":
pqdDataMapper.insertBatch((List<PqdData>) value);
break;
default:
log.warn("不支持的目标表: {}", key);
break;
}
});
}
public Instant getTime(Instant time, Integer interval) {
long originalTimeSec = time.getEpochSecond();
long newTimeSec = (originalTimeSec / interval) * interval;
return Instant.ofEpochSecond(newTimeSec);
}
}

View File

@@ -0,0 +1,470 @@
package com.njcn.csdevice.service.impl;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.njcn.csdevice.service.IPqdDataSplitService;
import com.njcn.influx.pojo.po.*;
import com.njcn.influx.pojo.po.cs.PqdData;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.vo.EleEpdPqdListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* PqdData数据拆分服务实现
*
* @author system
* @since 2026-05-22
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PqdDataSplitServiceImpl implements IPqdDataSplitService {
private final RedisUtil redisUtil;
private final EpdFeignClient epdFeignClient;
private final DicDataFeignClient dicDataFeignClient;
@Override
public Map<String, Object> splitPqdData(List<PqdData> pqdDataList) {
//获取表映射关系
Map<String,String> map1 = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD)), Map.class);
//获取字段映射关系
DictData pqd = dicDataFeignClient.getDicDataByCode(DicDataEnum.PQD.getCode()).getData();
List<EleEpdPqdListVO> list = epdFeignClient.selectAll().getData();
List<EleEpdPqd> epdList = list.stream().filter(item -> Objects.equals(item.getDataType(), pqd.getId()))
.findFirst()
.map(EleEpdPqdListVO::getEleEpdPqdVOS)
.orElse(new ArrayList<>());
// 处理 harmStart 和 harmEnd
List<EleEpdPqd> resultList = epdList.stream()
.flatMap(item -> {
if (item.getHarmStart() != null && item.getHarmEnd() != null) {
List<EleEpdPqd> expandedList = new ArrayList<>();
for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
EleEpdPqd newItem = copyEleEpdPqd(item);
newItem.setName(item.getName() + "_" + i);
newItem.setOtherName(item.getOtherName() + "_" + i);
expandedList.add(newItem);
}
return expandedList.stream();
} else {
return Stream.of(item);
}
})
.collect(Collectors.toList());
Map<String,List<EleEpdPqd>> map2 = resultList.stream().collect(Collectors.groupingBy(EleEpdPqd::getName,LinkedHashMap::new,Collectors.toList()));
Map<String,Object> map3 = new HashMap<>();
List<Object> list1 = new ArrayList<>();
List<Object> list2 = new ArrayList<>();
List<Object> list3 = new ArrayList<>();
List<Object> list4 = new ArrayList<>();
List<Object> list5 = new ArrayList<>();
List<Object> list6 = new ArrayList<>();
List<Object> list7 = new ArrayList<>();
List<Object> list8 = new ArrayList<>();
List<Object> list9 = new ArrayList<>();
List<Object> list10 = new ArrayList<>();
List<Object> list11 = new ArrayList<>();
List<Object> list12 = new ArrayList<>();
List<Object> list13 = new ArrayList<>();
List<Object> list14 = new ArrayList<>();
for (PqdData item : pqdDataList) {
Map<String, Object> map = extractFieldValues(item);
DataV dataV = new DataV();
dataV.setTime(item.getTime());
dataV.setLineId(item.getLineId());
dataV.setPhaseType(item.getPhaseType());
dataV.setValueType(item.getValueType());
dataV.setClDid(item.getClDid());
dataV.setProcess(item.getProcess());
dataV.setQualityFlag("0");
DataI dataI = new DataI();
dataI.setTime(item.getTime());
dataI.setLineId(item.getLineId());
dataI.setPhaseType(item.getPhaseType());
dataI.setValueType(item.getValueType());
dataI.setClDid(item.getClDid());
dataI.setProcess(item.getProcess());
dataI.setQualityFlag("0");
DataFlicker dataFlicker = new DataFlicker();
dataFlicker.setTime(item.getTime());
dataFlicker.setLineId(item.getLineId());
dataFlicker.setPhaseType(item.getPhaseType());
dataFlicker.setValueType(item.getValueType());
dataFlicker.setClDid(item.getClDid());
dataFlicker.setProcess(item.getProcess());
dataFlicker.setQualityFlag("0");
DataFluc dataFluc = new DataFluc();
dataFluc.setTime(item.getTime());
dataFluc.setLineId(item.getLineId());
dataFluc.setPhaseType(item.getPhaseType());
dataFluc.setValueType(item.getValueType());
dataFluc.setClDid(item.getClDid());
dataFluc.setProcess(item.getProcess());
dataFluc.setQualityFlag("0");
DataHarmPhasicI dataHarmPhasicI = new DataHarmPhasicI();
dataHarmPhasicI.setTime(item.getTime());
dataHarmPhasicI.setLineId(item.getLineId());
dataHarmPhasicI.setPhaseType(item.getPhaseType());
dataHarmPhasicI.setValueType(item.getValueType());
dataHarmPhasicI.setClDid(item.getClDid());
dataHarmPhasicI.setProcess(item.getProcess());
dataHarmPhasicI.setQualityFlag("0");
DataHarmPhasicV dataHarmPhasicV = new DataHarmPhasicV();
dataHarmPhasicV.setTime(item.getTime());
dataHarmPhasicV.setLineId(item.getLineId());
dataHarmPhasicV.setPhaseType(item.getPhaseType());
dataHarmPhasicV.setValueType(item.getValueType());
dataHarmPhasicV.setClDid(item.getClDid());
dataHarmPhasicV.setProcess(item.getProcess());
dataHarmPhasicV.setQualityFlag("0");
DataHarmPowerP dataHarmPowerP = new DataHarmPowerP();
dataHarmPowerP.setTime(item.getTime());
dataHarmPowerP.setLineId(item.getLineId());
dataHarmPowerP.setPhaseType(item.getPhaseType());
dataHarmPowerP.setValueType(item.getValueType());
dataHarmPowerP.setClDid(item.getClDid());
dataHarmPowerP.setProcess(item.getProcess());
dataHarmPowerP.setQualityFlag("0");
DataHarmPowerQ dataHarmPowerQ = new DataHarmPowerQ();
dataHarmPowerQ.setTime(item.getTime());
dataHarmPowerQ.setLineId(item.getLineId());
dataHarmPowerQ.setPhaseType(item.getPhaseType());
dataHarmPowerQ.setValueType(item.getValueType());
dataHarmPowerQ.setClDid(item.getClDid());
dataHarmPowerQ.setProcess(item.getProcess());
dataHarmPowerQ.setQualityFlag("0");
DataHarmPowerS dataHarmPowerS = new DataHarmPowerS();
dataHarmPowerS.setTime(item.getTime());
dataHarmPowerS.setLineId(item.getLineId());
dataHarmPowerS.setPhaseType(item.getPhaseType());
dataHarmPowerS.setValueType(item.getValueType());
dataHarmPowerS.setClDid(item.getClDid());
dataHarmPowerS.setProcess(item.getProcess());
dataHarmPowerS.setQualityFlag("0");
DataHarmRateV dataHarmRateV = new DataHarmRateV();
dataHarmRateV.setTime(item.getTime());
dataHarmRateV.setLineId(item.getLineId());
dataHarmRateV.setPhaseType(item.getPhaseType());
dataHarmRateV.setValueType(item.getValueType());
dataHarmRateV.setClDid(item.getClDid());
dataHarmRateV.setProcess(item.getProcess());
dataHarmRateV.setQualityFlag("0");
DataHarmRateI dataHarmRateI = new DataHarmRateI();
dataHarmRateI.setTime(item.getTime());
dataHarmRateI.setLineId(item.getLineId());
dataHarmRateI.setPhaseType(item.getPhaseType());
dataHarmRateI.setValueType(item.getValueType());
dataHarmRateI.setClDid(item.getClDid());
dataHarmRateI.setProcess(item.getProcess());
dataHarmRateI.setQualityFlag("0");
DataInHarmV dataInHarmV = new DataInHarmV();
dataInHarmV.setTime(item.getTime());
dataInHarmV.setLineId(item.getLineId());
dataInHarmV.setPhaseType(item.getPhaseType());
dataInHarmV.setValueType(item.getValueType());
dataInHarmV.setClDid(item.getClDid());
dataInHarmV.setProcess(item.getProcess());
dataInHarmV.setQualityFlag("0");
DataPlt dataPlt = new DataPlt();
dataPlt.setTime(item.getTime());
dataPlt.setLineId(item.getLineId());
dataPlt.setPhaseType(item.getPhaseType());
dataPlt.setValueType(item.getValueType());
dataPlt.setClDid(item.getClDid());
dataPlt.setProcess(item.getProcess());
dataPlt.setQualityFlag("0");
PqdData pqdData = new PqdData();
pqdData.setTime(item.getTime());
pqdData.setLineId(item.getLineId());
pqdData.setPhaseType(item.getPhaseType());
pqdData.setValueType(item.getValueType());
pqdData.setClDid(item.getClDid());
pqdData.setProcess(item.getProcess());
pqdData.setQualityFlag("0");
boolean hasDataV = false;
boolean hasDataI = false;
boolean hasData1 = false;
boolean hasData2 = false;
boolean hasData3 = false;
boolean hasData4 = false;
boolean hasData5 = false;
boolean hasData6 = false;
boolean hasData7 = false;
boolean hasData8 = false;
boolean hasData9 = false;
boolean hasData10 = false;
boolean hasData11 = false;
boolean hasData12 = false;
for (Map.Entry<String, Object> entry : map.entrySet()) {
String fieldName = entry.getKey();
Object value = entry.getValue();
String capitalizedFieldName = StringUtils.capitalize(fieldName);
// 跳过公共字段和 null 值
if (isCommonField(fieldName) || value == null) {
continue;
}
String table = map1.get(capitalizedFieldName);
if (StrUtil.isBlank(table)) {
continue;
}
List<EleEpdPqd> epdPqdList = map2.get(capitalizedFieldName);
if (CollectionUtils.isEmpty(epdPqdList)) {
continue;
}
String influxdbName2 = epdPqdList.get(0).getOtherName();
if (StrUtil.isBlank(influxdbName2) || influxdbName2.equals(capitalizedFieldName)) {
influxdbName2 = capitalizedFieldName;
}
if (Objects.equals(table, "data_v")) {
setFieldValue(dataV, influxdbName2, value, true);
hasDataV = true;
}
if (Objects.equals(table, "data_i")) {
setFieldValue(dataI, influxdbName2, value, true);
hasDataI = true;
}
if (Objects.equals(table, "data_flicker")) {
setFieldValue(dataFlicker, influxdbName2, value, true);
hasData1 = true;
}
if (Objects.equals(table, "data_fluc")) {
setFieldValue(dataFluc, influxdbName2, value, true);
hasData2 = true;
}
if (Objects.equals(table, "data_harmphasic_i")) {
setFieldValue(dataHarmPhasicI, influxdbName2, value, true);
hasData3 = true;
}
if (Objects.equals(table, "data_harmphasic_v")) {
setFieldValue(dataHarmPhasicV, influxdbName2, value, true);
hasData4 = true;
}
if (Objects.equals(table, "data_harmpower_p")) {
setFieldValue(dataHarmPowerP, influxdbName2, value, true);
hasData5 = true;
}
if (Objects.equals(table, "data_harmpower_q")) {
setFieldValue(dataHarmPowerQ, influxdbName2, value, true);
hasData6 = true;
}
if (Objects.equals(table, "data_harmpower_s")) {
setFieldValue(dataHarmPowerS, influxdbName2, value, true);
hasData7 = true;
}
if (Objects.equals(table, "data_harmrate_v")) {
setFieldValue(dataHarmRateV, influxdbName2, value, true);
hasData8 = true;
}
if (Objects.equals(table, "data_harmrate_i")) {
setFieldValue(dataHarmRateI, influxdbName2, value, true);
hasData9 = true;
}
if (Objects.equals(table, "data_inharm_v")) {
setFieldValue(dataInHarmV, influxdbName2, value, true);
hasData10 = true;
}
if (Objects.equals(table, "data_plt")) {
setFieldValue(dataPlt, influxdbName2, value, true);
hasData11 = true;
}
if (Objects.equals(table, "pqd_data")) {
setFieldValue(pqdData, StringUtils.uncapitalize(influxdbName2), value, false);
hasData12 = true;
}
}
if (hasDataV) {
list1.add(dataV);
}
if (hasDataI) {
list2.add(dataI);
}
if (hasData1) {
list3.add(dataFlicker);
}
if (hasData2) {
list4.add(dataFluc);
}
if (hasData3) {
list5.add(dataHarmPhasicI);
}
if (hasData4) {
list6.add(dataHarmPhasicV);
}
if (hasData5) {
list7.add(dataHarmPowerP);
}
if (hasData6) {
list8.add(dataHarmPowerQ);
}
if (hasData7) {
list9.add(dataHarmPowerS);
}
if (hasData8) {
list10.add(dataHarmRateV);
}
if (hasData9) {
list11.add(dataHarmRateI);
}
if (hasData10) {
list12.add(dataInHarmV);
}
if (hasData11) {
list13.add(dataPlt);
}
if (hasData12) {
list14.add(pqdData);
}
}
map3.put("data_v", list1);
map3.put("data_i", list2);
map3.put("data_flicker", list3);
map3.put("data_fluc", list4);
map3.put("data_harmphasic_i", list5);
map3.put("data_harmphasic_v", list6);
map3.put("data_harmpower_p", list7);
map3.put("data_harmpower_q", list8);
map3.put("data_harmpower_s", list9);
map3.put("data_harmrate_v", list10);
map3.put("data_harmrate_i", list11);
map3.put("data_inharm_v", list12);
map3.put("data_plt", list13);
map3.put("pqd_data", list14);
return map3;
}
private Map<String, Object> extractFieldValues(PqdData pqdData) {
Map<String, Object> fieldValues = new HashMap<>();
Field[] fields = PqdData.class.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(pqdData);
if (value != null) {
fieldValues.put(field.getName(), value);
} else {
fieldValues.put(field.getName(), 0.0d);
}
} catch (IllegalAccessException e) {
log.warn("获取字段 {} 的值失败", field.getName(), e);
}
}
return fieldValues;
}
private boolean isCommonField(String fieldName) {
Set<String> commonFields = new HashSet<>(Arrays.asList(
"time", "lineId", "phasicType", "valueType", "clDid",
"process", "qualityFlag"
));
return commonFields.contains(fieldName);
}
private void setFieldValue(Object obj, String fieldName, Object value, boolean isCamelCase) {
try {
String camelCaseFieldName = fieldName;
if (isCamelCase) {
camelCaseFieldName = toCamelCase(fieldName);
}
Field field = obj.getClass().getDeclaredField(camelCaseFieldName);
field.setAccessible(true);
if (value == null) {
Class<?> fieldType = field.getType();
if (fieldType == Double.class || fieldType == double.class) {
value = 0.0D;
} else if (fieldType == Integer.class || fieldType == int.class) {
value = 0;
} else if (fieldType == Float.class || fieldType == float.class) {
value = 0.0F;
} else if (fieldType == Long.class || fieldType == long.class) {
value = 0L;
} else {
return;
}
}
field.set(obj, value);
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
log.warn("设置字段 {} 的值失败", fieldName, e);
}
}
public static 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();
}
private EleEpdPqd copyEleEpdPqd(EleEpdPqd source) {
if (source == null) {
return null;
}
EleEpdPqd target = new EleEpdPqd();
BeanUtils.copyProperties(source, target);
return target;
}
}

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;
@@ -79,17 +78,11 @@ public class RStatIntegrityDServiceImpl extends MppServiceImpl<RStatIntegrityDMa
RStatIntegrityD data = new RStatIntegrityD();
//治理监测点
if (item.getClDid() == 0) {
statisticalDataDTO = commonService.getDataCounts(item.getLineId(),"apf_data","Apf_Freq","value","M","avg",item.getClDid().toString(),process.toString(),time+" 00:00:00",time+" 23:59:59");
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","Pq_Freq","value","M","avg",item.getClDid().toString(),process.toString(),time+" 00:00:00",time+" 23:59:59");
}
//治理、无线监测点
else {
statisticalDataDTO = commonService.getDataCounts(item.getLineId(),"pqd_data","Pq_Freq","value","M","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

@@ -132,7 +132,8 @@ public class RStatOnlineRateDServiceImpl extends MppServiceImpl<RStatOnlineRateD
}
}
} else {
onlineMinutes = 0;
//如果设备连一条记录没有,那就根本没接入,不需要统计
continue;
}
}

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()));
@@ -482,11 +482,15 @@ public class WlRecordServiceImpl extends ServiceImpl<WlRecordMapper, WlRecord> i
CommonQueryParam commonQueryParam = new CommonQueryParam();
commonQueryParam.setLineId(temp.getLineId());
commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
commonQueryParam.setColumnName(epdPqd.getName()+ (param.getFrequency() == null ? "":"_"+param.getFrequency()));
if (epdPqd.getName() == null || epdPqd.getName().isEmpty()) {
commonQueryParam.setColumnName(epdPqd.getName()+ (param.getFrequency() == null ? "":"_"+param.getFrequency()));
} else {
commonQueryParam.setColumnName(epdPqd.getOtherName()+ (param.getFrequency() == null ? "":"_"+param.getFrequency()));
}
commonQueryParam.setPhasic(epdPqd.getPhase());
commonQueryParam.setStartTime(LocalDateTimeUtil.format(wl.getStartTime(), DateTimeFormatter.ofPattern(DataParam.timeFormat)));
commonQueryParam.setEndTime(LocalDateTimeUtil.format(wl.getEndTime(), DateTimeFormatter.ofPattern(DataParam.timeFormat)));
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType());
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType().toUpperCase());
commonQueryParam.setProcess(data1.get(0).getProcess()+"");
commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
return commonQueryParam;
@@ -500,7 +504,7 @@ public class WlRecordServiceImpl extends ServiceImpl<WlRecordMapper, WlRecord> i
String unit;
ThdDataVO vo = new ThdDataVO();
vo.setLineId(temp.getLineId());
vo.setPhase(Objects.equals("M",temp.getPhaseType())?null:temp.getPhaseType());
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());
@@ -677,13 +681,13 @@ public class WlRecordServiceImpl extends ServiceImpl<WlRecordMapper, WlRecord> i
if(Objects.isNull(list.get(i).getEndTime())){
LocalDateTime now = LocalDateTime.now();
String sqlNow = now.format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper("pqd_data",StatisticalDataDTO.class);
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper("data_v",StatisticalDataDTO.class);
influxQueryWrapper.select(StatisticalDataDTO::getLineId)
.select(StatisticalDataDTO::getPhaseType)
.select(StatisticalDataDTO::getValueType)
.last("Pq_Freq")
.last("freq")
.eq(InfluxDBTableConstant.LINE_ID,lineId)
.eq(InfluxDBTableConstant.PHASIC_TYPE,"M")
.eq(InfluxDBTableConstant.PHASIC_TYPE,"T")
.between(InfluxDBTableConstant.TIME,startSql,sqlNow);
System.out.println(influxQueryWrapper.generateSql());
StatisticalDataDTO statisticalDataDTO = commonMapper.getLineRtData(influxQueryWrapper);
@@ -704,13 +708,13 @@ public class WlRecordServiceImpl extends ServiceImpl<WlRecordMapper, WlRecord> i
//如果不存在结束时间,则取后面一条的起始时间作为结束判断标识
if(Objects.isNull(list.get(i).getEndTime())){
String end = list.get(i+1).getStartTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper("pqd_data",StatisticalDataDTO.class);
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper("data_v",StatisticalDataDTO.class);
influxQueryWrapper.select(StatisticalDataDTO::getLineId)
.select(StatisticalDataDTO::getPhaseType)
.select(StatisticalDataDTO::getValueType)
.last("Pq_Freq")
.last("freq")
.eq(InfluxDBTableConstant.LINE_ID,lineId)
.eq(InfluxDBTableConstant.PHASIC_TYPE,"M")
.eq(InfluxDBTableConstant.PHASIC_TYPE,"T")
.between(InfluxDBTableConstant.TIME,startSql,end);
System.out.println(influxQueryWrapper.generateSql());
StatisticalDataDTO statisticalDataDTO = commonMapper.getLineRtData(influxQueryWrapper);

View File

@@ -9,6 +9,8 @@ import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author xy
*/
@@ -19,4 +21,8 @@ public interface CsHarmonicPlanFeignClient {
@ApiOperation("根据ID查询稳态指标方案")
HttpResult<CsHarmonicPlan> getById(@RequestParam("id") String id);
@GetMapping("/getByName")
@ApiOperation("根据名称查询稳态指标方案")
HttpResult<List<CsHarmonicPlan>> getByName(@RequestParam("name") String name);
}

View File

@@ -3,11 +3,17 @@ package com.njcn.csharmonic.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csharmonic.api.fallback.CsHarmonicPlanLineFeignClientFallbackFactory;
import com.njcn.csharmonic.param.CsHarmonicPlanLineParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author xy
*/
@@ -18,4 +24,12 @@ public interface CsHarmonicPlanLineFeignClient {
@ApiOperation("根据监测点ID查询方案ID")
HttpResult<String> getPlanIdByLineId(@RequestParam("lineId") String lineId);
@PostMapping("/savePlanLines")
@ApiOperation("新增方案与监测点关联")
HttpResult<Boolean> savePlanLines(@RequestBody @Validated CsHarmonicPlanLineParam param);
@PostMapping("/deleteByLineIds")
@ApiOperation("根据监测点ID集合删除关联")
HttpResult<Boolean> deleteByLineIds(@RequestBody List<String> lineIds);
}

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,9 +3,7 @@ package com.njcn.csharmonic.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.csharmonic.api.CsHarmonicFeignClient;
import com.njcn.csharmonic.api.CsHarmonicPlanFeignClient;
import com.njcn.csharmonic.pojo.po.CsHarmonic;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlan;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
@@ -34,6 +32,12 @@ public class CsHarmonicPlanFeignClientFallbackFactory implements FallbackFactory
log.error("{}异常,降级处理,异常为:{}","根据ID查询稳态指标方案异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<CsHarmonicPlan>> getByName(String name) {
log.error("{}异常,降级处理,异常为:{}","根据名称查询稳态指标方案异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -4,10 +4,13 @@ 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.csharmonic.api.CsHarmonicPlanLineFeignClient;
import com.njcn.csharmonic.param.CsHarmonicPlanLineParam;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author xy
*/
@@ -28,6 +31,18 @@ public class CsHarmonicPlanLineFeignClientFallbackFactory implements FallbackFac
log.error("{}异常,降级处理,异常为:{}","根据监测点ID查询方案ID异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<Boolean> savePlanLines(CsHarmonicPlanLineParam param) {
log.error("{}异常,降级处理,异常为:{}","新增方案与监测点关联异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<Boolean> deleteByLineIds(List<String> lineIds) {
log.error("{}异常,降级处理,异常为:{}","根据监测点ID集合删除关联异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -57,10 +57,10 @@ public class AnalyseComtradeCfg {
List<PqdData> result = new ArrayList<>();
minDataHashMap.forEach((dateTime,data)->{
List<PqdData> pqdDataA = convertDataByValueType(data.getMin(), "min",dateTime);
List<PqdData> pqdDataB = convertDataByValueType(data.getMax(), "max",dateTime);
List<PqdData> pqdDataC = convertDataByValueType(data.getAvg(), "avg",dateTime);
List<PqdData> pqdDataT = convertDataByValueType(data.getCp95(), "cp95",dateTime);
List<PqdData> pqdDataA = convertDataByValueType(data.getMin(), "MIN",dateTime);
List<PqdData> pqdDataB = convertDataByValueType(data.getMax(), "MAX",dateTime);
List<PqdData> pqdDataC = convertDataByValueType(data.getAvg(), "AVG",dateTime);
List<PqdData> pqdDataT = convertDataByValueType(data.getCp95(), "CP95",dateTime);
result.addAll(pqdDataA);
result.addAll(pqdDataB);
result.addAll(pqdDataC);
@@ -91,7 +91,7 @@ public class AnalyseComtradeCfg {
hashMapC.put("time",dateTime.toInstant());
HashMap hashMapM = new HashMap<>();
hashMapM.put("phaseType","M");
hashMapM.put("phaseType","T");
hashMapM.put("valueType",valueType);
hashMapM.put("time",dateTime.toInstant());

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

@@ -43,7 +43,7 @@ public class CsAlarm implements Serializable {
private String interruptEvent;
/**
* 中断事件描述
* 告警事件描述
*/
private String alarmEvent;

View File

@@ -0,0 +1,61 @@
package com.njcn.csharmonic.pojo.po;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author xy
*/
@Data
public class CsAlarmData implements Serializable {
//设备id
private String deviceId;
// 在线率异常记录
private OnlineRateAlarm onlineRate;
// 完整性异常记录
private IntegrityAlarm integrity;
/**
* 在线率异常信息
*/
@Data
public static class OnlineRateAlarm implements Serializable {
// 实际在线率值
private Double value;
// 阈值
private Double threshold;
// 是否异常
private Boolean isAbnormal;
}
/**
* 完整性异常信息
*/
@Data
public static class IntegrityAlarm implements Serializable {
// 阈值
private Double threshold;
// 各监测点的完整性数据
private List<MonitorPointIntegrity> monitorPoints;
/**
* 监测点完整性信息
*/
@Data
public static class MonitorPointIntegrity implements Serializable {
// 监测点ID
private String monitorPointId;
// 监测点名称
private String monitorName;
// 该监测点的完整性值
private Double value;
// 是否异常
private Boolean isAbnormal;
}
}
}

View File

@@ -129,4 +129,19 @@ public class CsEventPO extends BaseEntity {
*/
@TableField(value = "phase")
private String phase;
/**
* 暂降原因
*/
@TableField(value = "advance_reason")
private String advanceReason;
/**
* 暂降类型
*/
@TableField(value = "advance_type")
private String advanceType;
@TableField(value = "land_point")
private String landPoint;
}

View File

@@ -1,11 +1,11 @@
package com.njcn.csharmonic.pojo.vo;
import com.njcn.csharmonic.pojo.po.CsAlarmData;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@@ -24,8 +24,11 @@ public class AlarmVO implements Serializable {
@ApiModelProperty(value = "告警设备台数")
private Integer warnNums;
@ApiModelProperty(value = "通讯中断告警次数")
private Integer interruptCounts;
@ApiModelProperty(value = "在线率是否告警")
private Boolean onlineRateIsWarn;
@ApiModelProperty(value = "完整性是否告警")
private Boolean integrityIsWarn;
@ApiModelProperty(value = "终端告警次数")
private Integer warnCounts;
@@ -57,11 +60,8 @@ public class AlarmVO implements Serializable {
@ApiModelProperty(value = "告警详情")
private List<WarnDetail> warnDetails = new ArrayList<>();
@ApiModelProperty(value = "中断次数")
private Integer interruptCounts = 0;
@ApiModelProperty(value = "中断详情")
private List<String> interruptDetails = new ArrayList<>();
@ApiModelProperty(value = "在线率、完整性详情")
private CsAlarmData dataDetails;
@Data
public static class WarnDetail implements Serializable {

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

@@ -136,4 +136,7 @@ public class EventDetailVO {
@ApiModelProperty("F47描述")
private String f47;
@ApiModelProperty("事件落点")
private String landPoint;
}

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

@@ -112,4 +112,17 @@ public class CsHarmonicPlanController extends BaseController {
List<CsHarmonicPlan> list = csHarmonicPlanService.listAllOrderBySort();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
/**
* 根据ID查询稳态指标方案(包含监测点列表)
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/getByName")
@ApiOperation("根据名称查询稳态指标方案")
@ApiImplicitParam(name = "name", value = "name", required = true)
public HttpResult<List<CsHarmonicPlan>> getByName(@RequestParam("name") String name) {
String methodDescribe = getMethodDescribe("getByName");
List<CsHarmonicPlan> plan = csHarmonicPlanService.getByName(name);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, plan, 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

@@ -7,7 +7,10 @@ import com.github.tocrhz.mqtt.annotation.MqttSubscribe;
import com.github.tocrhz.mqtt.annotation.NamedValue;
import com.github.tocrhz.mqtt.annotation.Payload;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.CsLineTopologyFeignClient;
import com.njcn.csdevice.api.DevCapacityFeignClient;
import com.njcn.csdevice.pojo.vo.AppTopologyDiagramVO;
import com.njcn.csharmonic.param.CommonStatisticalQueryParam;
import com.njcn.csharmonic.param.FrequencyStatisticalQueryParam;
import com.njcn.csharmonic.pojo.dto.RealTimeDataDTO;
@@ -21,6 +24,10 @@ import com.njcn.csharmonic.service.TemperatureService;
import com.njcn.influx.pojo.dto.StatisticalDataDTO;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.api.CsStatisticalSetFeignClient;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.zlevent.api.FileFeignClient;
import lombok.AllArgsConstructor;
@@ -33,6 +40,7 @@ import org.springframework.util.CollectionUtils;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -56,6 +64,9 @@ public class MqttMessageHandler {
private final DecimalFormat df = new DecimalFormat("#0.000");
private final FileFeignClient fileFeignClient;
private final CsEventPOService csEventPOService;
private final CsLineTopologyFeignClient csLineTopologyClient;
private final CsLineFeignClient csLineFeignClient;
private final DicDataFeignClient dicDataFeignClient;
/**
* 实时数据应答
@@ -109,111 +120,6 @@ public class MqttMessageHandler {
publisher.send("/zl/TemperData/" + pageId, gson.toJson(recallReplyDTO), 1, false);
}
/**
* 实时数据应答
*/
// @MqttSubscribe(value = "/zl/askDevData/{devId}",qos = 1)
// public void responseTopoData(String topic, @NamedValue("devId") String devId, MqttMessage message, @Payload String payload) {
// String topoDataJson =redisUtil.getStringByKey (devId);
// if(StringUtils.isEmpty(topoDataJson)){
// List<ThdDataVO> result = new ArrayList<>();
// List<ThdDataVO> tempList = new ArrayList<>();
//
// //1.查询拓扑图配置的指标:拓扑图扑图配置7677f94c749dedaff30f911949cbd724
// List<EleEpdPqd> data = csStatisticalSetFeignClient.queryStatisticalSelect("b934664f9592d1c5e92caa90695b7103").getData();
// data.forEach(temp->{
// if(Objects.nonNull(temp.getHarmStart())&&Objects.nonNull(temp.getHarmEnd())){
// FrequencyStatisticalQueryParam frequencyStatisticalQueryParam = new FrequencyStatisticalQueryParam();
// frequencyStatisticalQueryParam.setDevId(devId);
// frequencyStatisticalQueryParam.setStatisticalId(temp.getId());
// frequencyStatisticalQueryParam.setValueType("avg");
// frequencyStatisticalQueryParam.setFrequencyStart(temp.getHarmStart());
// frequencyStatisticalQueryParam.setFrequencyEnd(temp.getHarmEnd());
// List<ThdDataVO> thdDataVOList = stableDataService.QuerySqlData(frequencyStatisticalQueryParam);
// tempList.addAll(thdDataVOList);
//
// }else {
// CommonStatisticalQueryParam commonStatisticalQueryParam = new CommonStatisticalQueryParam();
// commonStatisticalQueryParam.setDevId(devId);
// commonStatisticalQueryParam.setStatisticalId(temp.getId());
// commonStatisticalQueryParam.setValueType("avg");
// List<ThdDataVO> listFuture= stableDataService.queryFisrtCommonStatistical(commonStatisticalQueryParam);
// tempList.addAll(listFuture);
// }
//
// });
// //过滤M相
// List<ThdDataVO> m = tempList.stream().filter(temp -> Objects.equals(temp.getPhase(), "M")).collect(Collectors.toList());
// m.stream().forEach(temp->{
// Stream.of("A","B","C").forEach(phase->{
// ThdDataVO thdDataVO = new ThdDataVO();
// BeanUtils.copyProperties(temp,thdDataVO);
// thdDataVO.setPhase(phase);
// result.add(thdDataVO);
// });
// });
// List<ThdDataVO> apfThdI = tempList.stream().filter(temp -> Objects.equals(temp.getStatisticalName(), "Apf_ThdA_Load(%)")).collect(Collectors.toList());
// Map<String, List<ThdDataVO>> collect3 = apfThdI.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
// collect3.forEach((k,v)->{
// if(!CollectionUtil.isEmpty(v)){
// double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
// ThdDataVO thdDataVO = new ThdDataVO();
// BeanUtils.copyProperties(v.get(0),thdDataVO);
// thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
// thdDataVO.setPhase("avg");
// result.add(thdDataVO);
// }
// });
// List<ThdDataVO> apfRmsI = tempList.stream().filter(temp -> Objects.equals(temp.getStatisticalName(), "Apf_RmsI_TolOut(A)")).collect(Collectors.toList());
// Map<String, List<ThdDataVO>> collect2 = apfRmsI.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
// collect2.forEach((k,v)->{
// if(!CollectionUtil.isEmpty(v)){
// double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
// ThdDataVO thdDataVO = new ThdDataVO();
// BeanUtils.copyProperties(v.get(0),thdDataVO);
// thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
// thdDataVO.setPhase("avg");
// result.add(thdDataVO);
// }
// });
// List<ThdDataVO> apfThdISys = tempList.stream().filter(temp -> Objects.equals(temp.getStatisticalName(), "Apf_ThdA_Sys(%)")).collect(Collectors.toList());
// Map<String, List<ThdDataVO>> collect4 = apfThdISys.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
// collect4.forEach((k,v)->{
// if(!CollectionUtil.isEmpty(v)){
// double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
// ThdDataVO thdDataVO = new ThdDataVO();
// BeanUtils.copyProperties(v.get(0),thdDataVO);
// thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
// thdDataVO.setPhase("avg");
// result.add(thdDataVO);
//
// }
// });
// Double capacity = devCapacityFeignClient.getDevCapacity(devId).getData();
// apfRmsI.forEach(temp->{
// ThdDataVO thdDataVO = new ThdDataVO();
// BeanUtils.copyProperties(temp,thdDataVO);
// thdDataVO.setUnit("%");
// thdDataVO.setStatisticalName("load_Rate");
// thdDataVO.setAnotherName("负载率");
// if (capacity<=0){
// thdDataVO.setStatisticalData(3.1415926);
// }else {
// double v = temp.getStatisticalData()*100 / capacity;
// thdDataVO.setStatisticalData(Double.valueOf(df.format(v)));
// }
// result.add(thdDataVO);
// });
// List<ThdDataVO> notM = tempList.stream().filter(temp -> !Objects.equals(temp.getPhase(), "M")).collect(Collectors.toList());
// result.addAll(notM);
// Gson gson = new Gson();
// topoDataJson = gson.toJson(result);
// redisUtil.saveByKeyWithExpire(devId, (Object) topoDataJson, 30L);
// }
// publisher.send("/zl/devData/"+devId,topoDataJson,1,false);
// }
/**
* 实时数据应答
*/
@@ -225,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();
@@ -248,8 +154,8 @@ public class MqttMessageHandler {
});
//过滤M
List<ThdDataVO> m = tempList.stream().filter(temp -> Objects.equals(temp.getPhase(), "M")).collect(Collectors.toList());
//过滤T
List<ThdDataVO> m = tempList.stream().filter(temp -> Objects.equals(temp.getPhase(), "T")).collect(Collectors.toList());
m.stream().forEach(temp -> {
Stream.of("A", "B", "C").forEach(phase -> {
ThdDataVO thdDataVO = new ThdDataVO();
@@ -260,41 +166,134 @@ public class MqttMessageHandler {
});
//如果是基础数据则添加拓扑图的数据
if (Objects.equals("fc8c86dbc3f2d9810f5cd8f53c295415", typeId)) {
List<ThdDataVO> apfThdI = tempList.stream().filter(temp -> Objects.equals(temp.getStatisticalName(), "Apf_ThdA_Load(%)")).collect(Collectors.toList());
Map<String, List<ThdDataVO>> collect3 = apfThdI.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect3.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
}
});
List<ThdDataVO> apfRmsI = tempList.stream().filter(temp -> Objects.equals(temp.getStatisticalName(), "Apf_RmsI_TolOut(A)")).collect(Collectors.toList());
Map<String, List<ThdDataVO>> collect2 = apfRmsI.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect2.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
}
});
List<ThdDataVO> apfThdISys = tempList.stream().filter(temp -> Objects.equals(temp.getStatisticalName(), "Apf_ThdA_Sys(%)")).collect(Collectors.toList());
Map<String, List<ThdDataVO>> collect4 = apfThdISys.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect4.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
List<DictData> dictData = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_POSITION.getCode()).getData();
Map<String, DictData> codeToDictData = dictData.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
//添加拓扑图上自定义的指标
//根据设备id查询拓扑图
AppTopologyDiagramVO vo = csLineTopologyClient.queryTopologyDiagram(devId).getData();
vo.getAppsLineTopologyDiagramPO().forEach(item -> {
String linePositionCode = codeToDictData.get(item.getLinePostion()).getCode();
if (Objects.equals(linePositionCode, DicDataEnum.OUTPUT_SIDE.getCode())) {
//输出侧
if (item.getTarget() != null && !item.getTarget().isEmpty()) {
List<ThdDataVO> l1 = new ArrayList<>();
//根据指标查询
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(item.getTarget())).getData();
data1.forEach(temp -> {
CommonStatisticalQueryParam commonStatisticalQueryParam = new CommonStatisticalQueryParam();
commonStatisticalQueryParam.setDevId(devId);
commonStatisticalQueryParam.setStatisticalId(temp.getId());
commonStatisticalQueryParam.setValueType("avg");
List<ThdDataVO> listFuture = stableDataService.queryFisrtCommonStatistical(commonStatisticalQueryParam);
l1.addAll(listFuture);
});
Map<String, List<ThdDataVO>> collect3 = l1.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect3.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
}
});
} else {
Map<String, List<ThdDataVO>> collect2 = apfRmsI.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect2.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
}
});
}
} else if (Objects.equals(linePositionCode, DicDataEnum.GRID_SIDE.getCode())) {
//电网侧
if (item.getTarget() != null && !item.getTarget().isEmpty()) {
//根据指标查询
List<ThdDataVO> l1 = new ArrayList<>();
//根据指标查询
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(item.getTarget())).getData();
data1.forEach(temp -> {
CommonStatisticalQueryParam commonStatisticalQueryParam = new CommonStatisticalQueryParam();
commonStatisticalQueryParam.setDevId(devId);
commonStatisticalQueryParam.setStatisticalId(temp.getId());
commonStatisticalQueryParam.setValueType("avg");
List<ThdDataVO> listFuture = stableDataService.queryFisrtCommonStatistical(commonStatisticalQueryParam);
l1.addAll(listFuture);
});
Map<String, List<ThdDataVO>> collect3 = l1.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect3.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
}
});
} else {
List<ThdDataVO> apfThdISys = tempList.stream().filter(temp -> Objects.equals(temp.getStatisticalName(), "Apf_ThdA_Sys(%)")).collect(Collectors.toList());
Map<String, List<ThdDataVO>> collect4 = apfThdISys.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect4.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
}
});
}
} else if (Objects.equals(linePositionCode, DicDataEnum.LOAD_SIDE.getCode())) {
//负载侧
if (item.getTarget() != null && !item.getTarget().isEmpty()) {
//根据指标查询
List<ThdDataVO> l1 = new ArrayList<>();
//根据指标查询
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(item.getTarget())).getData();
data1.forEach(temp -> {
CommonStatisticalQueryParam commonStatisticalQueryParam = new CommonStatisticalQueryParam();
commonStatisticalQueryParam.setDevId(devId);
commonStatisticalQueryParam.setStatisticalId(temp.getId());
commonStatisticalQueryParam.setValueType("avg");
List<ThdDataVO> listFuture = stableDataService.queryFisrtCommonStatistical(commonStatisticalQueryParam);
l1.addAll(listFuture);
});
Map<String, List<ThdDataVO>> collect3 = l1.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect3.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
}
});
} else {
List<ThdDataVO> apfThdI = tempList.stream().filter(temp -> Objects.equals(temp.getStatisticalName(), "Apf_ThdA_Load(%)")).collect(Collectors.toList());
Map<String, List<ThdDataVO>> collect3 = apfThdI.stream().collect(Collectors.groupingBy(ThdDataVO::getLineId));
collect3.forEach((k, v) -> {
if (!CollectionUtil.isEmpty(v)) {
double asDouble = v.stream().mapToDouble(ThdDataVO::getStatisticalData).average().getAsDouble();
ThdDataVO thdDataVO = new ThdDataVO();
BeanUtils.copyProperties(v.get(0), thdDataVO);
thdDataVO.setStatisticalData(Double.valueOf(df.format(asDouble)));
thdDataVO.setPhase("avg");
result.add(thdDataVO);
}
});
}
}
});
Double capacity = devCapacityFeignClient.getDevCapacity(devId).getData();
@@ -314,7 +313,7 @@ public class MqttMessageHandler {
});
}
List<ThdDataVO> notM = tempList.stream().filter(temp -> !Objects.equals(temp.getPhase(), "M")).collect(Collectors.toList());
List<ThdDataVO> notM = tempList.stream().filter(temp -> !Objects.equals(temp.getPhase(), "T")).collect(Collectors.toList());
result.addAll(notM);
Gson gson = new Gson();
topoDataJson = gson.toJson(result);
@@ -323,7 +322,6 @@ public class MqttMessageHandler {
publisher.send("/zl/devData/" + devId + "/" + typeId, topoDataJson, 1, false);
}
public String getCldidName(String cldid) {
switch (cldid) {

View File

@@ -168,7 +168,8 @@
b.type type,
b.LEVEL LEVEL,
b.location location,
c.dev_type devType
c.dev_type devType,
b.land_point landPoint
<if test="csEventUserQueryPage != null and csEventUserQueryPage.type != null and csEventUserQueryPage.type != '' and csEventUserQueryPage.type ==0">
,d.NAME lineName
</if>

View File

@@ -1,113 +0,0 @@
package com.njcn.csharmonic.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import com.njcn.access.pojo.dto.NoticeUserDto;
import com.njcn.access.utils.SendMessageUtil;
import com.njcn.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.user.pojo.po.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author xy
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class AppNotificationService {
private final EpdFeignClient epdFeignClient;
private final SendMessageUtil sendMessageUtil;
private final DeviceMessageFeignClient deviceMessageClient;
private final CsEventUserPOService csEventUserPOService;
@Async("eventNotificationExecutor")
public void asyncSaveEventUserAndNotify(String eventId
, List<String> eventUser
, DevDetailDTO devDetailDto
, LocalDateTime time
, Integer eventType
, Double amplitude
, Double persistTime) {
NoticeUserDto noticeUserDto = new NoticeUserDto();
NoticeUserDto.Payload payload = new NoticeUserDto.Payload();
List<CsEventUserPO> result = new ArrayList<>();
eventUser.forEach(item -> {
CsEventUserPO csEventUser = new CsEventUserPO();
csEventUser.setUserId(item);
csEventUser.setStatus(0);
csEventUser.setEventId(eventId);
result.add(csEventUser);
});
DeviceMessageParam param = new DeviceMessageParam();
param.setUserList(eventUser);
param.setEventType(0);
List<User> users = deviceMessageClient.getSendUserByType(param).getData();
if (CollectionUtil.isNotEmpty(users)) {
List<String> devCodeList = users.stream().map(User::getDevCode).distinct().collect(Collectors.toList());
noticeUserDto.setPushClientId(devCodeList);
noticeUserDto.setTitle("暂态事件");
}
String eventName = epdFeignClient.findByName(getTag(eventType)).getData().getShowName();
String content = devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName()
+ "" + time.format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生暂态事件,事件类型:"
+ eventName
+ ",特征幅值:" + amplitude + "%"
+ ",持续时间:" + persistTime + "s";
noticeUserDto.setContent(content);
payload.setType(0);
payload.setPath("/pages/index/message1?type=" + payload.getType());
noticeUserDto.setPayload(payload);
if (CollectionUtil.isNotEmpty(noticeUserDto.getPushClientId())) {
List<String> filteredList = noticeUserDto.getPushClientId().stream()
.filter(s -> s != null && !s.isEmpty())
.distinct()
.collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(filteredList)) {
noticeUserDto.setPushClientId(filteredList);
sendMessageUtil.sendEventToUser(noticeUserDto);
}
}
if (CollectionUtil.isNotEmpty(result)) {
csEventUserPOService.saveBatch(result);
}
}
public String getTag(Integer type) {
String tag;
switch (type) {
case 1:
tag = "Evt_Sys_DipStr";
break;
case 2:
tag = "Evt_Sys_SwlStr";
break;
case 3:
tag = "Evt_Sys_IntrStr";
break;
case 4:
tag = "Transient";
break;
default:
tag = "Un_Know";
break;
}
return tag;
}
}

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

@@ -60,4 +60,6 @@ public interface ICsHarmonicPlanService extends IService<CsHarmonicPlan> {
* @return 方案详情
*/
CsHarmonicPlan getByIdWithLines(String id);
List<CsHarmonicPlan> getByName(String name);
}

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

@@ -1,60 +0,0 @@
package com.njcn.csharmonic.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.njcn.csdevice.api.SmsSendFeignClient;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.cssystem.api.AppMsgSetFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author xy
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class SmsNotificationService {
private final AppMsgSetFeignClient appMsgSetFeignClient;
private final UserFeignClient userFeignClient;
private final SmsSendFeignClient smsSendFeignClient;
@Value("${msg.msg_sign:南京灿能电力}")
private String msgSign;
@Async("smsNotificationExecutor")
public void asyncSendSmsNotification(String deviceId
, DevDetailDTO devDetailDto
, LocalDateTime eventTime
, Double amplitude
, Double persistTime) {
List<String> userIdList = appMsgSetFeignClient.queryUserIdsByDeviceId(deviceId).getData();
if (CollectionUtil.isNotEmpty(userIdList)) {
List<User> userList = userFeignClient.getUserListByIds(userIdList).getData();
if (CollectionUtil.isNotEmpty(userList)) {
List<User> userList1 = userList.stream()
.filter(item -> StrUtil.isNotBlank(item.getPhone()) && Objects.equals(item.getSmsNotice(), 1))
.collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(userList1)) {
String msgContent = "" + msgSign + "" + devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName()
+ "" + eventTime.format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生暂降事件"
+ ",特征幅值:" + amplitude + "%"
+ ",持续时间:" + persistTime + "s";
userList1.forEach(item -> {
smsSendFeignClient.sendSmsSimple(item.getPhone(), msgContent, "verify_code");
});
}
}
}
}
}

View File

@@ -19,6 +19,7 @@ import com.njcn.csdevice.pojo.po.CsLedger;
import com.njcn.csdevice.pojo.vo.CsLedgerVO;
import com.njcn.csharmonic.mapper.CsAlarmMapper;
import com.njcn.csharmonic.pojo.po.CsAlarm;
import com.njcn.csharmonic.pojo.po.CsAlarmData;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.AlarmVO;
@@ -102,8 +103,7 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
List<CsEventUserPO> userEvents = csEventUserPOService.queryEventListByUserId(RequestUtil.getUserIndex(), list.stream().map(CsAlarm::getId).collect(Collectors.toList()));
List<String> finalDevList = devList;
List<AlarmVO> result = list.stream()
.map(alarm -> {
List<AlarmVO> result = list.stream().map(alarm -> {
AlarmVO alarmVO = new AlarmVO();
alarmVO.setEventId(alarm.getId());
alarmVO.setDate(alarm.getTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
@@ -118,13 +118,12 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
alarmVO.setDevIds(matchedDevIds);
alarmVO.setIsRead(userEvents.stream().filter(item1->item1.getEventId().equals(alarm.getId())).findFirst().map(CsEventUserPO::getStatus).orElse(1));
int interruptCounts = 0;
int warnCounts = 0;
ObjectMapper objectMapper = new ObjectMapper();
List<List<String>> resultList;
List<CsAlarmData> resultList;
List<List<String>> resultList2;
try {
resultList = objectMapper.readValue(alarm.getInterruptEvent(), new TypeReference<List<List<String>>>() {});
resultList = objectMapper.readValue(alarm.getInterruptEvent(), new TypeReference<List<CsAlarmData>>() {});
resultList2 = objectMapper.readValue(alarm.getAlarmEvent(), new TypeReference<List<List<String>>>() {});
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
@@ -133,12 +132,26 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
for (String matchedDevId : matchedDevIds) {
for (int j = 0; j < devIds.length; j++) {
if (Objects.equals(matchedDevId, devIds[j])) {
interruptCounts = interruptCounts + (Objects.isNull(resultList.get(j)) ? 0 : resultList.get(j).get(0).split("").length);
warnCounts = warnCounts + (Objects.isNull(resultList2.get(j)) ? 0 : resultList2.get(j).size());
}
}
}
alarmVO.setInterruptCounts(interruptCounts);
List<CsAlarmData.OnlineRateAlarm> list1 = new ArrayList<>();
List<CsAlarmData.IntegrityAlarm.MonitorPointIntegrity> list2 = new ArrayList<>();
//根据resultList 来查询在线率和完整是否有true的如果有就设置alarmVO的属性
resultList.forEach(item->{
list1.add(item.getOnlineRate());
list2.addAll(item.getIntegrity().getMonitorPoints());
// 判断 onlineRate 是否有异常
boolean hasOnlineRateAbnormal = list1.stream()
.anyMatch(CsAlarmData.OnlineRateAlarm::getIsAbnormal);
// 判断 monitorPoints 是否有异常
boolean hasMonitorPointAbnormal = list2.stream()
.anyMatch(CsAlarmData.IntegrityAlarm.MonitorPointIntegrity::getIsAbnormal);
alarmVO.setOnlineRateIsWarn(hasOnlineRateAbnormal);
alarmVO.setIntegrityIsWarn(hasMonitorPointAbnormal);
});
alarmVO.setWarnCounts(warnCounts);
return alarmVO;
})
@@ -147,35 +160,6 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
.collect(Collectors.toList());
page1.setRecords(result);
}
// if (CollectionUtil.isNotEmpty(list)) {
// //获取用户推送事件
// List<CsEventUserPO> userEvents = csEventUserPOService.queryEventListByUserId(RequestUtil.getUserIndex(), list.stream().map(CsAlarm::getId).collect(Collectors.toList()));
//
// List<String> finalDevList = devList;
// List<AlarmVO> result = list.stream()
// .map(alarm -> {
// AlarmVO alarmVO = new AlarmVO();
// alarmVO.setEventId(alarm.getId());
// alarmVO.setDate(alarm.getTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//
// String devListStr = alarm.getDevList();
// String[] devIds = devListStr.split(",");
// List<String> matchedDevIds = Arrays.stream(devIds)
// .filter(devId -> StrUtil.isNotBlank(devId.trim()))
// .filter(finalDevList::contains)
// .collect(Collectors.toList());
// alarmVO.setWarnNums(matchedDevIds.size());
// alarmVO.setDevIds(matchedDevIds);
// alarmVO.setIsRead(userEvents.stream().filter(item1->item1.getEventId().equals(alarm.getId())).findFirst().map(CsEventUserPO::getStatus).orElse(1));
// return alarmVO;
// })
// .filter(alarmVO -> alarmVO.getWarnNums() > 0)
// .sorted((a1, a2) -> a2.getDate().compareTo(a1.getDate()))
// .collect(Collectors.toList());
// page1.setRecords(result);
// }
}
}
return page1;
@@ -212,20 +196,16 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
if (ObjectUtil.isNotNull(alarm.getInterruptEvent())) {
String interruptEvent = alarm.getInterruptEvent();
List<List<String>> resultList = new ArrayList<>();
List<CsAlarmData> resultList = new ArrayList<>();
if (StrUtil.isNotBlank(interruptEvent)) {
try {
ObjectMapper objectMapper = new ObjectMapper();
resultList = objectMapper.readValue(interruptEvent, new TypeReference<List<List<String>>>() {});
resultList = objectMapper.readValue(interruptEvent, new TypeReference<List<CsAlarmData>>() {});
alarmDetail.setDataDetails(resultList.get(i));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
List<String> interruptDetails = resultList.get(i);
if (CollectionUtil.isNotEmpty(interruptDetails)) {
alarmDetail.setInterruptCounts(interruptDetails.get(0).split("").length);
alarmDetail.setInterruptDetails(interruptDetails);
}
}
if (ObjectUtil.isNotNull(alarm.getAlarmEvent())) {
String alarmEvent = alarm.getAlarmEvent();

View File

@@ -13,10 +13,11 @@ import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.advance.api.EventCauseFeignClient;
import com.njcn.advance.pojo.dto.EventAnalysisDTO;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.po.CsLinePO;
@@ -33,11 +34,12 @@ 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.service.AppNotificationService;
import com.njcn.csharmonic.service.CsEventPOService;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.csharmonic.service.SmsNotificationService;
import com.njcn.cssystem.api.MsgSendFeignClient;
import com.njcn.cssystem.pojo.param.MsgSendParam;
import com.njcn.event.common.mapper.WlRmpEventDetailMapper;
import com.njcn.event.common.service.EventAnalysisService;
import com.njcn.event.file.component.WaveFileComponent;
import com.njcn.event.file.component.WavePicComponent;
import com.njcn.event.file.pojo.bo.WaveDataDetail;
@@ -57,6 +59,7 @@ import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.EleEvtFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.po.EleEvtParm;
@@ -120,13 +123,17 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
private final DicDataFeignClient dicDataFeignClient;
private final WlRmpEventDetailMapper wlRmpEventDetailMapper;
private final CsLedgerFeignClient csLedgerFeignclient;
private final DeviceMessageFeignClient deviceMessageClient;
private final AppNotificationService appNotificationService;
private final SmsNotificationService smsNotificationService;
private final EventAnalysisService eventAnalysisService;
private final EventCauseFeignClient eventCauseFeignClient;
private final MsgSendFeignClient msgSendFeignClient;
/** 波形数据抽点窗口大小每N个点为一个窗口进行MinMax抽点可通过Nacos配置wave.sample.interval调整 */
@Value("${wave.sample.interval:0}")
private int waveSampleInterval;
@Value("${msg.msg_sign:南京灿能电力}")
private String msgSign;
/** 两段数据间隔区域补null点数量可通过Nacos配置wave.gap.null.points调整 */
@Value("${wave.gap.null.points:5}")
private int waveGapNullPoints;
@Override
public List<EventDetailVO> queryEventList(CsEventUserQueryParam csEventUserQueryParam) {
@@ -393,6 +400,8 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
eventPo.setPersistTime(param.getDuration());
eventPo.setAmplitude(param.getAmplitude() * 100);
eventPo.setPhase(param.getPhase());
String dropZone = eventAnalysisService.determineDropZone(String.valueOf(param.getAmplitude() * 100),String.valueOf(param.getDuration()));
eventPo.setLandPoint(dropZone);
this.baseMapper.insert(eventPo);
//influxDB数据录入
List<String> records = new ArrayList<String>();
@@ -412,8 +421,6 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
//同步数据到 r_mp_event_detail
insertEvent(uuid, param, time);
//根据设备获取主用户、子用户
List<String> eventUser = deviceMessageClient.getEventUserByDeviceId(po.getDeviceId(),true).getData();
//获取台账信息
DevDetailDTO devDetailDto = csLedgerFeignclient.queryDevDetail(po.getDeviceId()).getData();
LocalDateTime eventTime = LocalDateTime.parse(param.getStartTime(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_MS_PATTERN));
@@ -423,7 +430,18 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
//异步处理事件用户关系和App消息推送
try {
appNotificationService.asyncSaveEventUserAndNotify(uuid, eventUser, devDetailDto, time, param.getEventType(), amplitudePercent, durationSeconds);
MsgSendParam msgSendParam = new MsgSendParam();
msgSendParam.setEventType(1);
msgSendParam.setType("2");
msgSendParam.setDevId(po.getDeviceId());
msgSendParam.setEventName(getTag(param.getEventType()));
msgSendParam.setEventTime(eventTime);
msgSendParam.setId(uuid);
msgSendParam.setNDid(devDetailDto.getNDid());
msgSendParam.setAmplitude(amplitudePercent);
msgSendParam.setPersistTime(durationSeconds);
msgSendParam.setDropZone(dropZone);
msgSendFeignClient.appMsgSend(msgSendParam);
} catch (Exception e) {
log.error("异步保存事件用户和通知失败事件ID: {}", uuid, e);
}
@@ -431,22 +449,45 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
//如果是暂降事件,异步发送短信通知
if (param.getEventType() == 1) {
try {
smsNotificationService.asyncSendSmsNotification(po.getDeviceId(), devDetailDto, eventTime, amplitudePercent, durationSeconds);
MsgSendParam msgSendParam = new MsgSendParam();
msgSendParam.setDevId(po.getDeviceId());
msgSendParam.setEventTime(eventTime);
msgSendParam.setAmplitude(amplitudePercent);
msgSendParam.setPersistTime(durationSeconds);
msgSendParam.setDropZone(dropZone);
msgSendFeignClient.smsMsgSend(msgSendParam);
} catch (Exception e) {
log.error("异步发送短信通知失败事件ID: {}", uuid, e);
}
}
} else {
if (StrUtil.isNotBlank(param.getWavePath())) {
EventAnalysisDTO var1 = new EventAnalysisDTO();
var1.setWlFilePath(param.getWavePath());
EventAnalysisDTO dto = eventCauseFeignClient.analysisCauseAndType(var1).getData();
List<DictData> list1 = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_REASON.getCode()).getData();
String id1 = list1.stream()
.filter(item -> Objects.equals(item.getAlgoDescribe(), dto.getCause()))
.map(DictData::getId)
.findFirst()
.orElse(null);
List<DictData> list2 = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()).getData();
String id2 = list2.stream()
.filter(item -> Objects.equals(item.getAlgoDescribe(), dto.getType()))
.map(DictData::getId)
.findFirst()
.orElse(null);
//更新文件信息
//先校验两份文件的名称是否一致
this.lambdaUpdate()
.eq(CsEventPO::getLineId,param.getMonitorId())
.eq(CsEventPO::getStartTime,param.getStartTime())
.set(CsEventPO::getWavePath,param.getWavePath())
.set(CsEventPO::getAdvanceReason,id1)
.set(CsEventPO::getAdvanceType,id2)
.update();
//更新文件信息
updateEvent(param);
updateEvent(param,id1,id2);
}
}
}
@@ -460,6 +501,8 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
wrapper.eq(RmpEventDetailPO::getEventId,id);
RmpEventDetailPO po2 = wlRmpEventDetailMapper.selectOne(wrapper);
po2.setWavePath(po.getWavePath());
po2.setAdvanceReason(po.getAdvanceReason());
po2.setAdvanceType(po.getAdvanceType());
po2.setFileFlag(1);
int row = wlRmpEventDetailMapper.updateById(po2);
if (row > 0) {
@@ -484,11 +527,13 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
wlRmpEventDetailMapper.insert(rmpEventDetailPO);
}
public void updateEvent(CldEventParam param) {
public void updateEvent(CldEventParam param,String advanceReason, String advanceType) {
LambdaQueryWrapper<RmpEventDetailPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(RmpEventDetailPO::getMeasurementPointId,param.getMonitorId()).eq(RmpEventDetailPO::getStartTime,param.getStartTime());
RmpEventDetailPO po = wlRmpEventDetailMapper.selectOne(wrapper);
po.setWavePath(param.getWavePath());
po.setAdvanceReason(advanceReason);
po.setAdvanceType(advanceType);
po.setFileFlag(1);
wlRmpEventDetailMapper.updateById(po);
}
@@ -602,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);
@@ -638,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);
@@ -654,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);
//单通道处理
@@ -682,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

@@ -131,4 +131,11 @@ public class CsHarmonicPlanServiceImpl extends ServiceImpl<CsHarmonicPlanMapper,
}
return plan;
}
@Override
public List<CsHarmonicPlan> getByName(String name) {
LambdaQueryWrapper<CsHarmonicPlan> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CsHarmonicPlan::getName, name);
return this.list(wrapper);
}
}

View File

@@ -52,6 +52,10 @@ public class CsHarmonicServiceImpl extends ServiceImpl<CsHarmonicMapper, CsHarmo
put("min", "最小值");
put("avg", "平均值");
put("cp95", "95%概率值");
put("MAX", "最大值");
put("MIN", "最小值");
put("AVG", "平均值");
put("CP95", "95%概率值");
}};
private final CsLedgerFeignClient csLedgerFeignClient;
@@ -275,7 +279,7 @@ public class CsHarmonicServiceImpl extends ServiceImpl<CsHarmonicMapper, CsHarmo
public List<HarmonicDetailVO.HarmDetail> AnalyzeData(String jsonString) {
List<HarmonicDetailVO.HarmDetail> result = new ArrayList<>();
List<HarmonicDetailVO.HarmDetail> result;
ObjectMapper mapper = new ObjectMapper();
List<PhaseData> phaseDataList = null;
try {

View File

@@ -599,7 +599,7 @@ public class CustomReportServiceImpl implements CustomReportService {
private void assPhase(List<EleEpdPqd> value, ReportTreeVO reportTreeItem, String key) {
List<ReportTreeVO> phaseTree = new ArrayList<>();
value.forEach(item -> {
if (Objects.nonNull(item.getPhase()) && !"M".equals(item.getPhase())) {
if (Objects.nonNull(item.getPhase()) && !"T".equals(item.getPhase())) {
List<ReportTreeVO> statTree = new ArrayList<>();
ReportTreeVO reportTreePhase = new ReportTreeVO();
reportTreePhase.setName(item.getPhase());

View File

@@ -165,7 +165,7 @@ public class LineTargetServiceImpl implements ILineTargetService {
}
String clDid = influxDbParamUtil.getClDidByLineId(item.getLineId());
//基础信息
CsRtDataVO vo = getLineRtData(item.getId(),item.getLineId(),tempTable[3],tempTable[0],Objects.equals(tempTable[1],"T")?"M":tempTable[1],tempTable[2],targetName,clDid);
CsRtDataVO vo = getLineRtData(item.getId(),item.getLineId(),tempTable[3],tempTable[0],Objects.equals(tempTable[1],"T")?"T":tempTable[1],tempTable[2],targetName,clDid);
//设备状态信息
CsEquipmentDeliveryPO po = equipmentFeignClient.getDevByLineId(item.getLineId()).getData();
vo.setDevStatus(po.getRunStatus());
@@ -214,7 +214,7 @@ public class LineTargetServiceImpl implements ILineTargetService {
.collect(Collectors.toList());
String s = tempUid.get(tempUid.size() - 1);
String[] tempTable = s.replace("$", "").split("#");
result.add(getLineRtDataNew(item.getId(),item.getLineId(),tempTable[3],tempTable[0],Objects.equals(tempTable[1],"T")?"M":tempTable[1],tempTable[2],temp,item.getUnit().get(i)));
result.add(getLineRtDataNew(item.getId(),item.getLineId(),tempTable[3],tempTable[0],Objects.equals(tempTable[1],"T")?"T":tempTable[1],tempTable[2],temp,item.getUnit().get(i)));
// result.add(getLineRtData(item.getId(),item.getLineId(),tempUid.get(3),tempUid.get(0),tempUid.get(1),tempUid.get(2).toUpperCase(),temp,"%"));
}
}

View File

@@ -7,8 +7,6 @@ import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.pojo.dto.CsEquipmentDeliveryDTO;
import com.njcn.csdevice.pojo.dto.LineParamDTO;
import com.njcn.csdevice.pojo.po.CsLedger;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.utils.ReflectUtils;
import com.njcn.csharmonic.param.CommonStatisticalQueryParam;
@@ -30,7 +28,6 @@ import com.njcn.system.api.CsStatisticalSetFeignClient;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import lombok.RequiredArgsConstructor;
import org.influxdb.dto.QueryResult;
@@ -39,11 +36,7 @@ import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.text.DecimalFormat;
import java.time.ZoneId;
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;
@@ -211,11 +204,13 @@ public class StableDataServiceImpl implements StableDataService {
CommonQueryParam commonQueryParam = new CommonQueryParam();
commonQueryParam.setLineId(temp.getLineId());
commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(data.getClassId()));
commonQueryParam.setColumnName(data.getName()+ finalFrequency1);
if (data.getName() == null || data.getName().isEmpty()) {
commonQueryParam.setColumnName(data.getName()+ finalFrequency1);
} else {
commonQueryParam.setColumnName(data.getOtherName()+ finalFrequency1);
}
commonQueryParam.setPhasic(data.getPhase());
// commonQueryParam.setStartTime();
// commonQueryParam.setEndTime();
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType());
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType().toUpperCase());
commonQueryParam.setProcess(data1.get(0).getProcess()+"");
commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
@@ -266,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));
@@ -284,11 +279,15 @@ public class StableDataServiceImpl implements StableDataService {
CommonQueryParam commonQueryParam = new CommonQueryParam();
commonQueryParam.setLineId(temp.getLineId());
commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
commonQueryParam.setColumnName(epdPqd.getName()+ finalFrequency1);
if (epdPqd.getName() == null || epdPqd.getName().isEmpty()) {
commonQueryParam.setColumnName(epdPqd.getName()+ finalFrequency1);
} else {
commonQueryParam.setColumnName(epdPqd.getOtherName()+ finalFrequency1);
}
commonQueryParam.setPhasic(epdPqd.getPhase());
commonQueryParam.setStartTime(commonStatisticalQueryParam.getStartTime() + " 00:00:00");
commonQueryParam.setEndTime(commonStatisticalQueryParam.getEndTime() + " 23:59:59");
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType());
commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType().toUpperCase());
commonQueryParam.setProcess(data1.get(0).getProcess()+"");
commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
@@ -320,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

@@ -60,11 +60,11 @@ public class StatisticsDataDataServiceImpl implements IStatisticsDataDataService
Integer process = devMap.get(item.getDeviceId()).getProcess();
//治理监测点
if (item.getClDid() == 0) {
statisticalDataDTO = commonService.getCounts(item.getLineId(),"apf_data","Apf_Freq","frequency","M","avg",item.getClDid().toString(),process.toString(),param.getStartTime(),param.getEndTime());
statisticalDataDTO = commonService.getCounts(item.getLineId(),"apf_data","Apf_Freq","frequency","T","AVG",item.getClDid().toString(),process.toString(),param.getStartTime(),param.getEndTime());
}
//电能质量监测点
else {
statisticalDataDTO = commonService.getCounts(item.getLineId(),"pqd_data","Pq_Freq","frequency","M","avg",item.getClDid().toString(),process.toString(),param.getStartTime(),param.getEndTime());
statisticalDataDTO = commonService.getCounts(item.getLineId(),"data_v","freq","frequency","T","AVG",item.getClDid().toString(),process.toString(),param.getStartTime(),param.getEndTime());
}
vo.setDevId(item.getDeviceId());
vo.setDevName(devMap.get(item.getDeviceId()).getName());
@@ -107,8 +107,8 @@ public class StatisticsDataDataServiceImpl implements IStatisticsDataDataService
List<CsLinePO> csLineList = csLineFeignClient.getLinesByDevList(devList).getData();
if (CollectionUtil.isNotEmpty(csLineList)) {
Map<String,List<CsLinePO>> devMap = csLineList.stream().collect(Collectors.groupingBy(CsLinePO::getDeviceId));
List<String> lineList = csLineList.stream().map(CsLinePO::getLineId).collect(Collectors.toList());
List<String> deviceList = csLineList.stream().map(CsLinePO::getDeviceId).collect(Collectors.toList());
List<String> lineList = csLineList.stream().map(CsLinePO::getLineId).distinct().collect(Collectors.toList());
List<String> deviceList = csLineList.stream().map(CsLinePO::getDeviceId).distinct().collect(Collectors.toList());
//获取监测点数据完整性
IcdBzParam param1 = new IcdBzParam();
param1.setLineList(lineList);

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

@@ -125,7 +125,7 @@ public class TestController {
collect.forEach((tempPhase,byNameMap)->{
//最小值
InfluxQueryWrapper influxQueryWrapperMin = new InfluxQueryWrapper(PqdData.class, clazz);
influxQueryWrapperMin.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "min")
influxQueryWrapperMin.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "MIN")
.eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
@@ -156,7 +156,7 @@ public class TestController {
//最大值
InfluxQueryWrapper influxQueryWrapperMax = new InfluxQueryWrapper(PqdData.class, clazz);
influxQueryWrapperMax.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "max")
influxQueryWrapperMax.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "MAX")
.eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
@@ -186,7 +186,7 @@ public class TestController {
//平均值
InfluxQueryWrapper influxQueryWrapperAvg = new InfluxQueryWrapper(PqdData.class, clazz);
influxQueryWrapperAvg.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "avg")
influxQueryWrapperAvg.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "AVG")
.eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
@@ -216,7 +216,7 @@ public class TestController {
//CP95
InfluxQueryWrapper influxQueryWrapperCp95 = new InfluxQueryWrapper(PqdData.class, clazz);
influxQueryWrapperCp95.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "avg")
influxQueryWrapperCp95.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "AVG")
.eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);

View File

@@ -1,348 +1,348 @@
package com.njcn.csreport.job;
import cn.hutool.extra.spring.SpringUtil;
import com.github.jeffreyning.mybatisplus.service.IMppService;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.utils.HarmonicTimesUtil;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.pojo.dto.LineParamDTO;
import com.njcn.csdevice.pojo.po.CsLedger;
import com.njcn.csreport.enums.ReportTableEnum;
import com.njcn.csreport.service.RStatDataVDService;
import com.njcn.influx.constant.InfluxDbSqlConstant;
import com.njcn.influx.imapper.CommonMapper;
import com.njcn.influx.imapper.PqdDataMapper;
import com.njcn.influx.imapper.day.GovernReportMapper;
import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
import com.njcn.influx.pojo.po.DataV;
import com.njcn.influx.pojo.po.cs.PqdData;
import com.njcn.influx.query.InfluxQueryWrapper;
import com.njcn.system.api.CsStatisticalSetFeignClient;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.vo.EleEpdPqdListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Description:
* Date: 2024/1/18 10:15【需求编号】
*
* @author clam
* @version V1.0.0
*/
@Component
@EnableScheduling
@RequiredArgsConstructor
@Slf4j
public class ReportCovertJob {
private final CsLedgerFeignClient csLedgerFeignClient;
private final DicDataFeignClient dicDataFeignClient;
private final EpdFeignClient epdFeignClient;
private final GovernReportMapper reportMapper;
private final RStatDataVDService rStatDataVDService;
private final static String SERVICE_PACKAGE_PREFIX = "com.njcn.csreport.service.";
private final static String ENTITY_PACKAGE_PREFIX = "com.njcn.csreport.pojo.po.";
private final static String SERVICE_SUFFIX = "Service";
/**
* 每天同步influxdb数据到mysql
*
* @date 2024/3/5
*/
@Scheduled(cron = "0 0 1 * * ? ")
public void executeEvent() throws ClassNotFoundException {
DateTimeFormatter formatter1 = DateTimeFormatter.ISO_DATE;
// 获取当前日期
LocalDate today = LocalDate.now();
// 计算前一天的日期
LocalDate yesterday = today.minusDays(1);
// 获取前一天的开始时间00:00:00
LocalDateTime startOfYesterday = yesterday.atStartOfDay();
// 获取前一天的结束时间23:59:59
LocalDateTime endOfYesterday = yesterday.plusDays(1).atStartOfDay().minusSeconds(1);
// 定义时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化时间为字符串
String startTime = startOfYesterday.format(formatter);
String endTime = endOfYesterday.format(formatter);
// String startTime ="2024-07-31 00:00:00";
// String endTime ="2024-09-20 23:00:00";
List<CsLedger> data = csLedgerFeignClient.queryLine(new LineParamDTO()).getData();
List<String> lineIndex = data.stream().map(CsLedger::getId).collect(Collectors.toList());
// List<String> lineIndex = Stream.of("00B78D016AB32","00B78D016AB51").collect(Collectors.toList());
//查询电能质量数据指标
DictData pqd = dicDataFeignClient.getDicDataByCode(DicDataEnum.PQD.getCode()).getData();
List<DictData> tableNameList = dicDataFeignClient.getDicDataByTypeCode("Data_Day").getData();
Map<String, String> tableMap = tableNameList.stream().collect(Collectors.toMap(DictData::getId, DictData::getCode, (code, code2) -> code));
List<EleEpdPqdListVO> eleEpdPqdListVOList = epdFeignClient.selectAll().getData();
EleEpdPqdListVO eleEpdPqdListVO = eleEpdPqdListVOList.stream().filter(temp -> Objects.equals(temp.getDataType(), pqd.getId())).collect(Collectors.toList()).get(0);
Map<String, List<EleEpdPqd>> eleEpdMap = eleEpdPqdListVO.getEleEpdPqdVOS().stream().filter(temp -> StringUtils.isNotEmpty(temp.getOtherName())
&& StringUtils.isNotEmpty(temp.getResourcesId()))
.collect(Collectors.groupingBy(EleEpdPqd::getResourcesId));//不能全表表分组查,根据映射的
for (Map.Entry<String, List<EleEpdPqd>> entry : eleEpdMap.entrySet()) {
String k = entry.getKey();
List<EleEpdPqd> v = entry.getValue();
String tableName = tableMap.get(k);
List result = new ArrayList<>();
Class clazz = Class.forName(ENTITY_PACKAGE_PREFIX + ReportTableEnum.getEntityName(tableName));
IMppService bean = (IMppService) SpringUtil.getBean(Class.forName(SERVICE_PACKAGE_PREFIX+ReportTableEnum.getEntityName(tableName)+SERVICE_SUFFIX));
//由于epd配置表ABC三项对应指标一样这里做去重处理由于功率表功率和三项总功率都对应P只是项别不一一样因此M相要和,A,B,C相分开计算
Map<String, Map<String, List<EleEpdPqd>>> collect = v.stream().collect(Collectors.groupingBy(EleEpdPqd::getPhase, Collectors.groupingBy(EleEpdPqd::getName)));
collect.forEach((tempPhase,byNameMap)->{
//最小值
InfluxQueryWrapper influxQueryWrapperMin = new InfluxQueryWrapper(PqdData.class, clazz);
influxQueryWrapperMin.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "min")
.eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
byNameMap.forEach((name, eleEpdPqdList) -> {
EleEpdPqd tempEleEpdPqd = eleEpdPqdList.get(0);
if (Objects.nonNull(tempEleEpdPqd.getHarmStart()) && Objects.nonNull(tempEleEpdPqd.getHarmEnd())) {
//0-49转成1-50
if(tempEleEpdPqd.getHarmStart()==0){
tempEleEpdPqd.setHarmStart(tempEleEpdPqd.getHarmStart()+1);
tempEleEpdPqd.setHarmEnd(tempEleEpdPqd.getHarmEnd()+1);
}
for (int i = tempEleEpdPqd.getHarmStart(); i < tempEleEpdPqd.getHarmEnd() + 1; i++) {
influxQueryWrapperMin.min(tempEleEpdPqd.getName() + "_" + i, tempEleEpdPqd.getOtherName() + "_" + i);
}
} else {
influxQueryWrapperMin.min(tempEleEpdPqd.getName(), tempEleEpdPqd.getOtherName());
}
});
influxQueryWrapperMin.groupBy(InfluxDBTableConstant.LINE_ID)
.groupBy(InfluxDBTableConstant.PHASIC_TYPE)
.groupBy(InfluxDBTableConstant.VALUE_TYPE)
.between(InfluxDBTableConstant.TIME, startTime, endTime);
List list1 = reportMapper.selectByQueryWrapper(influxQueryWrapperMin);
//最大值
InfluxQueryWrapper influxQueryWrapperMax = new InfluxQueryWrapper(PqdData.class, clazz);
influxQueryWrapperMax.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "max")
.eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
byNameMap.forEach((name, eleEpdPqdList) -> {
EleEpdPqd tempEleEpdPqd = eleEpdPqdList.get(0);
if (Objects.nonNull(tempEleEpdPqd.getHarmStart()) && Objects.nonNull(tempEleEpdPqd.getHarmEnd())) {
//0-49转成1-50
if(tempEleEpdPqd.getHarmStart()==0){
tempEleEpdPqd.setHarmStart(tempEleEpdPqd.getHarmStart()+1);
tempEleEpdPqd.setHarmEnd(tempEleEpdPqd.getHarmEnd()+1);
}
for (int i = tempEleEpdPqd.getHarmStart(); i < tempEleEpdPqd.getHarmEnd() + 1; i++) {
influxQueryWrapperMax.max(tempEleEpdPqd.getName() + "_" + i, tempEleEpdPqd.getOtherName() + "_" + i);
}
} else {
influxQueryWrapperMax.max(tempEleEpdPqd.getName(), tempEleEpdPqd.getOtherName());
}
});
influxQueryWrapperMax.groupBy(InfluxDBTableConstant.LINE_ID)
.groupBy(InfluxDBTableConstant.PHASIC_TYPE)
.groupBy(InfluxDBTableConstant.VALUE_TYPE)
.between(InfluxDBTableConstant.TIME, startTime, endTime);
List list2 = reportMapper.selectByQueryWrapper(influxQueryWrapperMax);
//平均值
InfluxQueryWrapper influxQueryWrapperAvg = new InfluxQueryWrapper(PqdData.class, clazz);
influxQueryWrapperAvg.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "avg")
.eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
byNameMap.forEach((name, eleEpdPqdList) -> {
EleEpdPqd tempEleEpdPqd = eleEpdPqdList.get(0);
if (Objects.nonNull(tempEleEpdPqd.getHarmStart()) && Objects.nonNull(tempEleEpdPqd.getHarmEnd())) {
//0-49转成1-50
if(tempEleEpdPqd.getHarmStart()==0){
tempEleEpdPqd.setHarmStart(tempEleEpdPqd.getHarmStart()+1);
tempEleEpdPqd.setHarmEnd(tempEleEpdPqd.getHarmEnd()+1);
}
for (int i = tempEleEpdPqd.getHarmStart(); i < tempEleEpdPqd.getHarmEnd() + 1; i++) {
influxQueryWrapperAvg.mean(tempEleEpdPqd.getName() + "_" + i, tempEleEpdPqd.getOtherName() + "_" + i);
}
} else {
influxQueryWrapperAvg.mean(tempEleEpdPqd.getName(), tempEleEpdPqd.getOtherName());
}
});
influxQueryWrapperAvg.groupBy(InfluxDBTableConstant.LINE_ID)
.groupBy(InfluxDBTableConstant.PHASIC_TYPE)
.groupBy(InfluxDBTableConstant.VALUE_TYPE)
.between(InfluxDBTableConstant.TIME, startTime, endTime);
List list3 = reportMapper.selectByQueryWrapper(influxQueryWrapperAvg);
//CP95
InfluxQueryWrapper influxQueryWrapperCp95 = new InfluxQueryWrapper(PqdData.class, clazz);
influxQueryWrapperCp95.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "avg")
.eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
byNameMap.forEach((name, eleEpdPqdList) -> {
EleEpdPqd tempEleEpdPqd = eleEpdPqdList.get(0);
if (Objects.nonNull(tempEleEpdPqd.getHarmStart()) && Objects.nonNull(tempEleEpdPqd.getHarmEnd())) {
//0-49转成1-50
if(tempEleEpdPqd.getHarmStart()==0){
tempEleEpdPqd.setHarmStart(tempEleEpdPqd.getHarmStart()+1);
tempEleEpdPqd.setHarmEnd(tempEleEpdPqd.getHarmEnd()+1);
}
for (int i = tempEleEpdPqd.getHarmStart(); i < tempEleEpdPqd.getHarmEnd() + 1; i++) {
influxQueryWrapperCp95.percentile(tempEleEpdPqd.getName() + "_" + i, tempEleEpdPqd.getOtherName() + "_" + i, 95);
}
} else {
influxQueryWrapperCp95.percentile(tempEleEpdPqd.getName(), tempEleEpdPqd.getOtherName(),95);
}
});
influxQueryWrapperCp95.groupBy(InfluxDBTableConstant.LINE_ID)
.groupBy(InfluxDBTableConstant.PHASIC_TYPE)
.groupBy(InfluxDBTableConstant.VALUE_TYPE)
.between(InfluxDBTableConstant.TIME, startTime, endTime);
List list4 = reportMapper.selectByQueryWrapper(influxQueryWrapperCp95);
//为ValueType转成cp95
list4.forEach(temp -> {
//获取
Field vauleField = null;
try {
vauleField = temp.getClass().getDeclaredField("valueType");
vauleField.setAccessible(true); //暴力访问id
vauleField.set(temp, "CP95");
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
result.addAll(list1);
result.addAll(list2);
result.addAll(list3);
result.addAll(list4);
} );
//1.为time赋值2.映射
result.forEach(temp -> {
//获取
Field phasicTypeeField = null;
Field timeField = null;
Field vauleTypeField = null;
Field qualityFlagField = null;
try {
timeField = temp.getClass().getDeclaredField("time");
timeField.setAccessible(true);
timeField.set(temp, yesterday);
phasicTypeeField = temp.getClass().getDeclaredField("phasicType");
phasicTypeeField.setAccessible(true);
String phase = phasicTypeeField.get(temp).toString();
phasicTypeeField.set(temp, getPhase(phase));
vauleTypeField = temp.getClass().getDeclaredField("valueType");
vauleTypeField.setAccessible(true);
String valueType = vauleTypeField.get(temp).toString();
vauleTypeField.set(temp, valueType.toUpperCase());
qualityFlagField = temp.getClass().getDeclaredField("qualityFlag");
qualityFlagField.setAccessible(true);
qualityFlagField.set(temp, 0);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
log.info("插入数据");
//由于ABA对应的都是A不能批量插入会爆主键冲突
result.forEach(temp->{
bean.saveOrUpdateByMultiId(temp);
});
}
}
public String getPhase( String phase) {
switch (phase) {
case "A":
return "A";
case "B":
return "B";
case "C":
return "C";
case "M":
return "T";
case "AB":
return "A";
case "BC":
return "B";
case "CA":
return "C";
default:
break;
}
return "";
}
}
//package com.njcn.csreport.job;
//
//import cn.hutool.extra.spring.SpringUtil;
//import com.github.jeffreyning.mybatisplus.service.IMppService;
//import com.njcn.common.pojo.enums.response.CommonResponseEnum;
//import com.njcn.common.utils.HarmonicTimesUtil;
//import com.njcn.common.utils.HttpResultUtil;
//import com.njcn.csdevice.api.CsLedgerFeignClient;
//import com.njcn.csdevice.pojo.dto.LineParamDTO;
//import com.njcn.csdevice.pojo.po.CsLedger;
//
//import com.njcn.csreport.enums.ReportTableEnum;
//import com.njcn.csreport.service.RStatDataVDService;
//import com.njcn.influx.constant.InfluxDbSqlConstant;
//import com.njcn.influx.imapper.CommonMapper;
//import com.njcn.influx.imapper.PqdDataMapper;
//import com.njcn.influx.imapper.day.GovernReportMapper;
//import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
//import com.njcn.influx.pojo.po.DataV;
//import com.njcn.influx.pojo.po.cs.PqdData;
//import com.njcn.influx.query.InfluxQueryWrapper;
//import com.njcn.system.api.CsStatisticalSetFeignClient;
//import com.njcn.system.api.DicDataFeignClient;
//
//import com.njcn.system.api.EpdFeignClient;
//import com.njcn.system.enums.DicDataEnum;
//import com.njcn.system.pojo.po.DictData;
//import com.njcn.system.pojo.po.EleEpdPqd;
//import com.njcn.system.pojo.vo.EleEpdPqdListVO;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.scheduling.annotation.EnableScheduling;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//
//import java.lang.reflect.Field;
//import java.time.LocalDate;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.Objects;
//import java.util.stream.Collectors;
//
///**
// * Description:
// * Date: 2024/1/18 10:15【需求编号】
// *
// * @author clam
// * @version V1.0.0
// */
//@Component
//@EnableScheduling
//@RequiredArgsConstructor
//@Slf4j
//public class ReportCovertJob {
//
// private final CsLedgerFeignClient csLedgerFeignClient;
// private final DicDataFeignClient dicDataFeignClient;
// private final EpdFeignClient epdFeignClient;
// private final GovernReportMapper reportMapper;
// private final RStatDataVDService rStatDataVDService;
//
// private final static String SERVICE_PACKAGE_PREFIX = "com.njcn.csreport.service.";
// private final static String ENTITY_PACKAGE_PREFIX = "com.njcn.csreport.pojo.po.";
// private final static String SERVICE_SUFFIX = "Service";
//
//
// /**
// * 每天同步influxdb数据到mysql
// *
// * @date 2024/3/5
// */
// @Scheduled(cron = "0 0 1 * * ? ")
// public void executeEvent() throws ClassNotFoundException {
// DateTimeFormatter formatter1 = DateTimeFormatter.ISO_DATE;
// // 获取当前日期
// LocalDate today = LocalDate.now();
//
//
// // 计算前一天的日期
// LocalDate yesterday = today.minusDays(1);
// // 获取前一天的开始时间00:00:00
// LocalDateTime startOfYesterday = yesterday.atStartOfDay();
// // 获取前一天的结束时间23:59:59
// LocalDateTime endOfYesterday = yesterday.plusDays(1).atStartOfDay().minusSeconds(1);
//
// // 定义时间格式
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
// // 格式化时间为字符串
// String startTime = startOfYesterday.format(formatter);
// String endTime = endOfYesterday.format(formatter);
//// String startTime ="2024-07-31 00:00:00";
//// String endTime ="2024-09-20 23:00:00";
// List<CsLedger> data = csLedgerFeignClient.queryLine(new LineParamDTO()).getData();
// List<String> lineIndex = data.stream().map(CsLedger::getId).collect(Collectors.toList());
//// List<String> lineIndex = Stream.of("00B78D016AB32","00B78D016AB51").collect(Collectors.toList());
//
// //查询电能质量数据指标
// DictData pqd = dicDataFeignClient.getDicDataByCode(DicDataEnum.PQD.getCode()).getData();
// List<DictData> tableNameList = dicDataFeignClient.getDicDataByTypeCode("Data_Day").getData();
// Map<String, String> tableMap = tableNameList.stream().collect(Collectors.toMap(DictData::getId, DictData::getCode, (code, code2) -> code));
//
//
// List<EleEpdPqdListVO> eleEpdPqdListVOList = epdFeignClient.selectAll().getData();
// EleEpdPqdListVO eleEpdPqdListVO = eleEpdPqdListVOList.stream().filter(temp -> Objects.equals(temp.getDataType(), pqd.getId())).collect(Collectors.toList()).get(0);
//
//
// Map<String, List<EleEpdPqd>> eleEpdMap = eleEpdPqdListVO.getEleEpdPqdVOS().stream().filter(temp -> StringUtils.isNotEmpty(temp.getOtherName())
// && StringUtils.isNotEmpty(temp.getResourcesId()))
// .collect(Collectors.groupingBy(EleEpdPqd::getResourcesId));//不能全表表分组查,根据映射的
//
// for (Map.Entry<String, List<EleEpdPqd>> entry : eleEpdMap.entrySet()) {
// String k = entry.getKey();
// List<EleEpdPqd> v = entry.getValue();
// String tableName = tableMap.get(k);
// List result = new ArrayList<>();
// Class clazz = Class.forName(ENTITY_PACKAGE_PREFIX + ReportTableEnum.getEntityName(tableName));
// IMppService bean = (IMppService) SpringUtil.getBean(Class.forName(SERVICE_PACKAGE_PREFIX+ReportTableEnum.getEntityName(tableName)+SERVICE_SUFFIX));
//
// //由于epd配置表ABC三项对应指标一样这里做去重处理由于功率表功率和三项总功率都对应P只是项别不一一样因此M相要和,A,B,C相分开计算
// Map<String, Map<String, List<EleEpdPqd>>> collect = v.stream().collect(Collectors.groupingBy(EleEpdPqd::getPhase, Collectors.groupingBy(EleEpdPqd::getName)));
//
// collect.forEach((tempPhase,byNameMap)->{
// //最小值
// InfluxQueryWrapper influxQueryWrapperMin = new InfluxQueryWrapper(PqdData.class, clazz);
// influxQueryWrapperMin.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "min")
// .eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
//// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
//
//
// byNameMap.forEach((name, eleEpdPqdList) -> {
// EleEpdPqd tempEleEpdPqd = eleEpdPqdList.get(0);
// if (Objects.nonNull(tempEleEpdPqd.getHarmStart()) && Objects.nonNull(tempEleEpdPqd.getHarmEnd())) {
// //0-49转成1-50
// if(tempEleEpdPqd.getHarmStart()==0){
// tempEleEpdPqd.setHarmStart(tempEleEpdPqd.getHarmStart()+1);
// tempEleEpdPqd.setHarmEnd(tempEleEpdPqd.getHarmEnd()+1);
// }
// for (int i = tempEleEpdPqd.getHarmStart(); i < tempEleEpdPqd.getHarmEnd() + 1; i++) {
// influxQueryWrapperMin.min(tempEleEpdPqd.getName() + "_" + i, tempEleEpdPqd.getOtherName() + "_" + i);
// }
// } else {
// influxQueryWrapperMin.min(tempEleEpdPqd.getName(), tempEleEpdPqd.getOtherName());
// }
//
// });
//
// influxQueryWrapperMin.groupBy(InfluxDBTableConstant.LINE_ID)
// .groupBy(InfluxDBTableConstant.PHASIC_TYPE)
// .groupBy(InfluxDBTableConstant.VALUE_TYPE)
// .between(InfluxDBTableConstant.TIME, startTime, endTime);
// List list1 = reportMapper.selectByQueryWrapper(influxQueryWrapperMin);
//
//
// //最大值
// InfluxQueryWrapper influxQueryWrapperMax = new InfluxQueryWrapper(PqdData.class, clazz);
// influxQueryWrapperMax.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "max")
// .eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
//// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
//
//
// byNameMap.forEach((name, eleEpdPqdList) -> {
// EleEpdPqd tempEleEpdPqd = eleEpdPqdList.get(0);
// if (Objects.nonNull(tempEleEpdPqd.getHarmStart()) && Objects.nonNull(tempEleEpdPqd.getHarmEnd())) {
// //0-49转成1-50
// if(tempEleEpdPqd.getHarmStart()==0){
// tempEleEpdPqd.setHarmStart(tempEleEpdPqd.getHarmStart()+1);
// tempEleEpdPqd.setHarmEnd(tempEleEpdPqd.getHarmEnd()+1);
// }
// for (int i = tempEleEpdPqd.getHarmStart(); i < tempEleEpdPqd.getHarmEnd() + 1; i++) {
// influxQueryWrapperMax.max(tempEleEpdPqd.getName() + "_" + i, tempEleEpdPqd.getOtherName() + "_" + i);
// }
// } else {
// influxQueryWrapperMax.max(tempEleEpdPqd.getName(), tempEleEpdPqd.getOtherName());
// }
//
// });
//
// influxQueryWrapperMax.groupBy(InfluxDBTableConstant.LINE_ID)
// .groupBy(InfluxDBTableConstant.PHASIC_TYPE)
// .groupBy(InfluxDBTableConstant.VALUE_TYPE)
// .between(InfluxDBTableConstant.TIME, startTime, endTime);
// List list2 = reportMapper.selectByQueryWrapper(influxQueryWrapperMax);
//
// //平均值
// InfluxQueryWrapper influxQueryWrapperAvg = new InfluxQueryWrapper(PqdData.class, clazz);
// influxQueryWrapperAvg.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "avg")
// .eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
//// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
//
// byNameMap.forEach((name, eleEpdPqdList) -> {
// EleEpdPqd tempEleEpdPqd = eleEpdPqdList.get(0);
// if (Objects.nonNull(tempEleEpdPqd.getHarmStart()) && Objects.nonNull(tempEleEpdPqd.getHarmEnd())) {
// //0-49转成1-50
// if(tempEleEpdPqd.getHarmStart()==0){
// tempEleEpdPqd.setHarmStart(tempEleEpdPqd.getHarmStart()+1);
// tempEleEpdPqd.setHarmEnd(tempEleEpdPqd.getHarmEnd()+1);
// }
// for (int i = tempEleEpdPqd.getHarmStart(); i < tempEleEpdPqd.getHarmEnd() + 1; i++) {
// influxQueryWrapperAvg.mean(tempEleEpdPqd.getName() + "_" + i, tempEleEpdPqd.getOtherName() + "_" + i);
// }
// } else {
// influxQueryWrapperAvg.mean(tempEleEpdPqd.getName(), tempEleEpdPqd.getOtherName());
// }
//
// });
//
// influxQueryWrapperAvg.groupBy(InfluxDBTableConstant.LINE_ID)
// .groupBy(InfluxDBTableConstant.PHASIC_TYPE)
// .groupBy(InfluxDBTableConstant.VALUE_TYPE)
// .between(InfluxDBTableConstant.TIME, startTime, endTime);
// List list3 = reportMapper.selectByQueryWrapper(influxQueryWrapperAvg);
//
//
// //CP95
// InfluxQueryWrapper influxQueryWrapperCp95 = new InfluxQueryWrapper(PqdData.class, clazz);
// influxQueryWrapperCp95.regular(PqdData::getLineId, lineIndex).eq(InfluxDBTableConstant.VALUE_TYPE, "avg")
// .eq(InfluxDBTableConstant.PHASIC_TYPE,tempPhase);
//// .eq(InfluxDBTableConstant.IS_ABNORMAL, 0);
//
// byNameMap.forEach((name, eleEpdPqdList) -> {
// EleEpdPqd tempEleEpdPqd = eleEpdPqdList.get(0);
// if (Objects.nonNull(tempEleEpdPqd.getHarmStart()) && Objects.nonNull(tempEleEpdPqd.getHarmEnd())) {
// //0-49转成1-50
// if(tempEleEpdPqd.getHarmStart()==0){
// tempEleEpdPqd.setHarmStart(tempEleEpdPqd.getHarmStart()+1);
// tempEleEpdPqd.setHarmEnd(tempEleEpdPqd.getHarmEnd()+1);
// }
// for (int i = tempEleEpdPqd.getHarmStart(); i < tempEleEpdPqd.getHarmEnd() + 1; i++) {
// influxQueryWrapperCp95.percentile(tempEleEpdPqd.getName() + "_" + i, tempEleEpdPqd.getOtherName() + "_" + i, 95);
// }
// } else {
// influxQueryWrapperCp95.percentile(tempEleEpdPqd.getName(), tempEleEpdPqd.getOtherName(),95);
// }
//
// });
//
// influxQueryWrapperCp95.groupBy(InfluxDBTableConstant.LINE_ID)
// .groupBy(InfluxDBTableConstant.PHASIC_TYPE)
// .groupBy(InfluxDBTableConstant.VALUE_TYPE)
// .between(InfluxDBTableConstant.TIME, startTime, endTime);
// List list4 = reportMapper.selectByQueryWrapper(influxQueryWrapperCp95);
// //为ValueType转成cp95
// list4.forEach(temp -> {
// //获取
// Field vauleField = null;
// try {
// vauleField = temp.getClass().getDeclaredField("valueType");
//
// vauleField.setAccessible(true); //暴力访问id
// vauleField.set(temp, "CP95");
//
// } catch (NoSuchFieldException e) {
// throw new RuntimeException(e);
// } catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
//
//
// });
//
//
// result.addAll(list1);
// result.addAll(list2);
// result.addAll(list3);
// result.addAll(list4);
//
//
// } );
// //1.为time赋值2.映射
// result.forEach(temp -> {
// //获取
// Field phasicTypeeField = null;
// Field timeField = null;
// Field vauleTypeField = null;
// Field qualityFlagField = null;
//
// try {
//
// timeField = temp.getClass().getDeclaredField("time");
//
// timeField.setAccessible(true);
// timeField.set(temp, yesterday);
// phasicTypeeField = temp.getClass().getDeclaredField("phasicType");
// phasicTypeeField.setAccessible(true);
// String phase = phasicTypeeField.get(temp).toString();
// phasicTypeeField.set(temp, getPhase(phase));
//
//
// vauleTypeField = temp.getClass().getDeclaredField("valueType");
// vauleTypeField.setAccessible(true);
// String valueType = vauleTypeField.get(temp).toString();
// vauleTypeField.set(temp, valueType.toUpperCase());
//
// qualityFlagField = temp.getClass().getDeclaredField("qualityFlag");
//
// qualityFlagField.setAccessible(true);
// qualityFlagField.set(temp, 0);
//
// } catch (NoSuchFieldException e) {
// throw new RuntimeException(e);
// } catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
//
//
// });
// log.info("插入数据");
// //由于ABA对应的都是A不能批量插入会爆主键冲突
// result.forEach(temp->{
// bean.saveOrUpdateByMultiId(temp);
// });
//
//
// }
//
//
// }
//
// public String getPhase( String phase) {
//
// switch (phase) {
// case "A":
// return "A";
// case "B":
// return "B";
// case "C":
// return "C";
// case "M":
// return "T";
// case "AB":
// return "A";
// case "BC":
// return "B";
// case "CA":
// return "C";
// default:
// break;
// }
// return "";
// }
//
//
//}

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,26 @@
package com.njcn.cssystem.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.cssystem.api.fallback.MsgSendFeignClientFallbackFactory;
import com.njcn.cssystem.pojo.param.MsgSendParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.CS_SYSTEM_BOOT, path = "/send", fallbackFactory = MsgSendFeignClientFallbackFactory.class,contextId = "send")
public interface MsgSendFeignClient {
@PostMapping("/appMsgSend")
@ApiOperation("app消息推送")
HttpResult<Boolean> appMsgSend(@RequestBody MsgSendParam param);
@PostMapping("/smsMsgSend")
@ApiOperation("短信消息推送")
HttpResult<Boolean> smsMsgSend(@RequestBody MsgSendParam param);
}

View File

@@ -1,9 +1,10 @@
package com.njcn.csdevice.api.fallback;
package com.njcn.cssystem.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 com.njcn.cssystem.api.MsgSendFeignClient;
import com.njcn.cssystem.pojo.param.MsgSendParam;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@@ -13,20 +14,26 @@ import org.springframework.stereotype.Component;
*/
@Slf4j
@Component
public class SmsSendClientFallbackFactory implements FallbackFactory<SmsSendFeignClient> {
public class MsgSendFeignClientFallbackFactory implements FallbackFactory<MsgSendFeignClient> {
@Override
public SmsSendFeignClient create(Throwable cause) {
public MsgSendFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new SmsSendFeignClient() {
return new MsgSendFeignClient() {
@Override
public HttpResult<String> sendSmsSimple(String receiver, String content, String messageType) {
log.error("{}异常,降级处理,异常为:{}","发送短信(简化参数)数据异常",cause.toString());
public HttpResult<Boolean> appMsgSend(MsgSendParam param) {
log.error("{}异常,降级处理,异常为:{}","app消息推送异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<Boolean> smsMsgSend(MsgSendParam param) {
log.error("{}异常,降级处理,异常为:{}","短信消息推送异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};

View File

@@ -0,0 +1,34 @@
package com.njcn.cssystem.pojo.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* @author xy
*/
@Data
public class CsAlarmSetParam implements Serializable {
@ApiModelProperty("主键ID")
private String id;
@ApiModelProperty("方案名称")
@NotBlank(message = "方案名称不能为空")
private String name;
@ApiModelProperty("在线率阈值")
@NotNull(message = "在线率阈值不能为空")
private Integer onlineRateLimit;
@ApiModelProperty("完整性阈值")
@NotNull(message = "完整性阈值不能为空")
private Integer integrityLimit;
@ApiModelProperty("是否启用 (0:未启用 1:启用)")
private Integer active;
}

View File

@@ -0,0 +1,45 @@
package com.njcn.cssystem.pojo.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author xy
*/
@Data
public class MsgSendParam implements Serializable {
@ApiModelProperty("事件类型")
private Integer eventType;
@ApiModelProperty("类型")
private String type;
@ApiModelProperty("设备id")
private String devId;
@ApiModelProperty("事件名称")
private String eventName;
@ApiModelProperty("事件时间")
private LocalDateTime eventTime;
@ApiModelProperty("事件id")
private String id;
@ApiModelProperty("nDid")
private String nDid;
@ApiModelProperty("暂态幅值")
private Double amplitude;
@ApiModelProperty("持续时间")
private Double persistTime;
@ApiModelProperty("落点位置")
private String dropZone;
}

View File

@@ -0,0 +1,49 @@
package com.njcn.cssystem.pojo.po;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.bo.BaseEntity;
import java.io.Serializable;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
/**
* <p>
*
* </p>
*
* @author xy
* @since 2026-05-08
*/
@Getter
@Setter
@TableName("cs_alarm_set")
public class CsAlarmSet extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* id
*/
private String id;
/**
* 方案名称
*/
private String name;
/**
* 在线率阈值
*/
private Integer onlineRateLimit;
/**
* 完整性阈值
*/
private Integer integrityLimit;
/**
* 是否启用 (0:未启用 1:启用)
*/
private Integer active;
}

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

@@ -1,4 +1,4 @@
package com.njcn.csharmonic.config;
package com.njcn.cssystem.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

View File

@@ -0,0 +1,124 @@
package com.njcn.cssystem.controller.baseinfo;
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.cssystem.pojo.param.CsAlarmSetParam;
import com.njcn.cssystem.pojo.po.CsAlarmSet;
import com.njcn.cssystem.service.ICsAlarmSetService;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author xy
* @since 2026-05-08
*/
@RestController
@Slf4j
@RequestMapping("/csAlarmSet")
@Api(tags = "告警配置管理")
@AllArgsConstructor
public class CsAlarmSetController extends BaseController {
private final ICsAlarmSetService csAlarmSetService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/add")
@ApiOperation("新增告警配置")
@ApiImplicitParam(name = "param", value = "告警配置参数", required = true)
public HttpResult<String> add(@RequestBody @Validated CsAlarmSetParam param) {
String methodDescribe = getMethodDescribe("add");
boolean result = csAlarmSetService.add(param);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, "新增成功", methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, "新增失败", methodDescribe);
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/update")
@ApiOperation("修改告警配置")
@ApiImplicitParam(name = "param", value = "告警配置参数", required = true)
public HttpResult<String> update(@RequestBody @Validated CsAlarmSetParam param) {
String methodDescribe = getMethodDescribe("update");
boolean result = csAlarmSetService.update(param);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, "修改成功", methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, "修改失败", methodDescribe);
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/delete")
@ApiOperation("删除告警配置")
@ApiImplicitParam(name = "id", value = "配置ID", required = true)
public HttpResult<String> delete(@RequestParam("id") String id) {
String methodDescribe = getMethodDescribe("delete");
boolean result = csAlarmSetService.delete(id);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, "删除成功", methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, "删除失败", methodDescribe);
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getById")
@ApiOperation("根据ID查询告警配置")
@ApiImplicitParam(name = "id", value = "配置ID", required = true)
public HttpResult<CsAlarmSet> getById(@RequestParam("id") String id) {
String methodDescribe = getMethodDescribe("getById");
CsAlarmSet vo = csAlarmSetService.getById(id);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, vo, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/listAll")
@ApiOperation("查询所有告警配置")
public HttpResult<List<CsAlarmSet>> listAll() {
String methodDescribe = getMethodDescribe("listAll");
List<CsAlarmSet> list = csAlarmSetService.listAll();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/toggleActive")
@ApiOperation("切换告警配置启用状态")
@ApiImplicitParam(name = "id", value = "配置ID", required = true)
public HttpResult<String> toggleActive(@RequestParam("id") String id) {
String methodDescribe = getMethodDescribe("toggleActive");
boolean result = csAlarmSetService.toggleActive(id);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, "切换成功", methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, "切换失败", methodDescribe);
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getEnabledConfig")
@ApiOperation("获取当前启用的告警配置")
public HttpResult<CsAlarmSet> getEnabledConfig() {
String methodDescribe = getMethodDescribe("getEnabledConfig");
CsAlarmSet vo = csAlarmSetService.getEnabledConfig();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, vo, methodDescribe);
}
}

View File

@@ -0,0 +1,50 @@
package com.njcn.cssystem.controller.sendmsg;
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.cssystem.pojo.param.MsgSendParam;
import com.njcn.cssystem.service.IMsgSendService;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author xy
*/
@Slf4j
@RestController
@RequestMapping("/send")
@Api(tags = "消息推送")
@AllArgsConstructor
public class MsgSendController extends BaseController {
private final IMsgSendService msgSendService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/appMsgSend")
@ApiOperation("app消息推送")
public HttpResult<Boolean> appMsgSend(@RequestBody MsgSendParam param){
String methodDescribe = getMethodDescribe("appMsgSend");
msgSendService.sendAppNotification(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/smsMsgSend")
@ApiOperation("短信消息推送")
public HttpResult<Boolean> smsMsgSend(@RequestBody MsgSendParam param){
String methodDescribe = getMethodDescribe("smsMsgSend");
msgSendService.sendSmsForDipEvent(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
}

View File

@@ -46,6 +46,15 @@ public class DataTaskController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/runDataAlarm")
@ApiOperation("运行告警(完整性、在线率)")
public HttpResult<Boolean> channelRunDataAlarm(@RequestParam("time") String time){
String methodDescribe = getMethodDescribe("channelRunDataAlarm");
dataTaskService.channelRunDataAlarm(time);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/pushAppMsg")
@ApiOperation("app消息推送")

View File

@@ -0,0 +1,16 @@
package com.njcn.cssystem.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.cssystem.pojo.po.CsAlarmSet;
/**
* <p>
* Mapper 接口
* </p>
*
* @author xy
* @since 2026-05-08
*/
public interface CsAlarmSetMapper extends BaseMapper<CsAlarmSet> {
}

View File

@@ -0,0 +1,16 @@
package com.njcn.cssystem.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
/**
* <p>
* 暂态事件表 Mapper 接口
* </p>
*
* @author xuyang
* @since 2023-08-23
*/
public interface CsEventUserMapper extends BaseMapper<CsEventUserPO> {
}

View File

@@ -0,0 +1,33 @@
package com.njcn.cssystem.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.cssystem.pojo.param.CsAlarmSetParam;
import com.njcn.cssystem.pojo.po.CsAlarmSet;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author xy
* @since 2026-05-08
*/
public interface ICsAlarmSetService extends IService<CsAlarmSet> {
boolean add(CsAlarmSetParam param);
boolean update(CsAlarmSetParam param);
boolean delete(String id);
CsAlarmSet getById(String id);
List<CsAlarmSet> listAll();
boolean toggleActive(String id);
CsAlarmSet getEnabledConfig();
}

View File

@@ -0,0 +1,16 @@
package com.njcn.cssystem.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
/**
* <p>
* 暂态事件表 服务类
* </p>
*
* @author xuyang
* @since 2023-08-23
*/
public interface ICsEventUserService extends IService<CsEventUserPO> {
}

View File

@@ -23,6 +23,18 @@ public interface IDataTaskService {
*/
void channelRunAlarm(String time);
/**
运行告警算法
1、每天生成一条记录查询所有的设备获取设备告警数据、设备的在线率和完整性在线率根据设备来判断完整性根据监测点来判断(多个监测点取最小值)
告警判断逻辑:(这个数据是根据一个表配置的,先查询阈值配置表)
a.完整性 < 90(可变动)
b.完整性 > 90(可变动) && 在线率 < 60(可变动)
2、根据设备获取哪些用户有这个设备的权限然后将用户id收集起来。(主用户、子用户、管理员id集合)
3、将cs_alarm生成的记录存储到cs_event_user表中标记为未读
* @param time
*/
void channelRunDataAlarm(String time);
/**
* 推送App消息
* 只推送稳态事件、运行告警数据

View File

@@ -0,0 +1,15 @@
package com.njcn.cssystem.service;
import com.njcn.cssystem.pojo.param.MsgSendParam;
/**
* @author xy
*/
public interface IMsgSendService {
void sendAppNotification(MsgSendParam param);
void sendSmsForDipEvent(MsgSendParam param);
}

View File

@@ -0,0 +1,101 @@
package com.njcn.cssystem.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.cssystem.mapper.CsAlarmSetMapper;
import com.njcn.cssystem.pojo.param.CsAlarmSetParam;
import com.njcn.cssystem.pojo.po.CsAlarmSet;
import com.njcn.cssystem.service.ICsAlarmSetService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
/**
* <p>
* 服务实现类
* </p>
*
* @author xy
* @since 2026-05-08
*/
@Service
public class CsAlarmSetServiceImpl extends ServiceImpl<CsAlarmSetMapper, CsAlarmSet> implements ICsAlarmSetService {
@Override
@Transactional(rollbackFor = Exception.class)
public boolean add(CsAlarmSetParam param) {
CsAlarmSet csAlarmSet = new CsAlarmSet();
BeanUtils.copyProperties(param, csAlarmSet);
if (Objects.isNull(csAlarmSet.getActive())) {
csAlarmSet.setActive(0);
}
return this.save(csAlarmSet);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean update(CsAlarmSetParam param) {
CsAlarmSet csAlarmSet = new CsAlarmSet();
BeanUtils.copyProperties(param, csAlarmSet);
return this.updateById(csAlarmSet);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delete(String id) {
CsAlarmSet csAlarmSet = this.baseMapper.selectById(id);
if (Objects.nonNull(csAlarmSet) && Objects.equals(csAlarmSet.getActive(), 1)) {
throw new BusinessException("不能删除已启用的配置");
}
return this.removeById(id);
}
@Override
public CsAlarmSet getById(String id) {
return this.baseMapper.selectById(id);
}
@Override
public List<CsAlarmSet> listAll() {
LambdaQueryWrapper<CsAlarmSet> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.orderByDesc(CsAlarmSet::getCreateTime);
return this.list(queryWrapper);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean toggleActive(String id) {
CsAlarmSet csAlarmSet = this.baseMapper.selectById(id);
if (Objects.isNull(csAlarmSet)) {
throw new BusinessException("配置不存在");
}
if (Objects.equals(csAlarmSet.getActive(), 1)) {
long enabledCount = this.count(new LambdaQueryWrapper<CsAlarmSet>().eq(CsAlarmSet::getActive, 1));
if (enabledCount <= 1) {
throw new BusinessException("至少需要保留一条启用的配置");
}
csAlarmSet.setActive(0);
} else {
LambdaUpdateWrapper<CsAlarmSet> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.set(CsAlarmSet::getActive, 0);
this.update(updateWrapper);
csAlarmSet.setActive(1);
}
return this.updateById(csAlarmSet);
}
@Override
public CsAlarmSet getEnabledConfig() {
LambdaQueryWrapper<CsAlarmSet> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(CsAlarmSet::getActive, 1);
queryWrapper.last("limit 1");
return this.getOne(queryWrapper);
}
}

View File

@@ -0,0 +1,20 @@
package com.njcn.cssystem.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.cssystem.mapper.CsEventUserMapper;
import com.njcn.cssystem.service.ICsEventUserService;
import org.springframework.stereotype.Service;
/**
* <p>
* 暂态事件表 服务实现类
* </p>
*
* @author xuyang
* @since 2023-08-23
*/
@Service
public class CsEventUserServiceImpl extends ServiceImpl<CsEventUserMapper, CsEventUserPO> implements ICsEventUserService {
}

View File

@@ -10,17 +10,21 @@ import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.njcn.access.pojo.dto.NoticeUserDto;
import com.njcn.access.utils.SendMessageUtil;
import com.njcn.csdevice.api.CsCommTerminalFeignClient;
import com.njcn.csdevice.api.CsDeviceUserFeignClient;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.*;
import com.njcn.csdevice.param.IcdBzParam;
import com.njcn.csdevice.pojo.dto.CsLineDTO;
import com.njcn.csdevice.pojo.param.UserDevParam;
import com.njcn.csdevice.pojo.po.CsDeviceUserPO;
import com.njcn.csdevice.pojo.po.RStatIntegrityD;
import com.njcn.csdevice.pojo.po.RStatOnlineRateD;
import com.njcn.csharmonic.api.*;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.param.RStatLimitQueryParam;
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;
@@ -77,6 +81,9 @@ public class DataTaskServiceImpl implements IDataTaskService {
private final CsCommTerminalFeignClient csCommTerminalFeignClient;
private final CsHarmonicPlanFeignClient csHarmonicPlanFeignClient;
private final CsHarmonicPlanLineFeignClient csHarmonicPlanLineFeignClient;
private final ICsAlarmSetService csAlarmSetService;
private final OnlineRateFeignClient onlineRateFeignClient;
private final IntegrityFeignClient integrityClient;
@Override
@Transactional(rollbackFor = Exception.class)
@@ -126,6 +133,13 @@ public class DataTaskServiceImpl implements IDataTaskService {
RStatLimitQueryParam rStatLimitQueryParam = RStatLimitQueryParam.builder().ids(lineList).date(date).endDate(date).build();
List<RStatLimitRateDPO> limitRates = rStatLimitRateDClient.monitorIdsGetLimitRateInfo(rStatLimitQueryParam).getData();
//获取监测点信息
Map<String, CsLineDTO> lineMap;
if (CollUtil.isNotEmpty(allLine)) {
lineMap = allLine.stream().collect(Collectors.toMap(CsLineDTO::getLineId, item -> item));
} else {
lineMap = Collections.emptyMap();
}
if (CollUtil.isNotEmpty(limitRates)) {
limitRates.forEach(item->{
//新增cs_harmonic数据
@@ -134,9 +148,14 @@ public class DataTaskServiceImpl implements IDataTaskService {
csharmonic.setId(id);
csharmonic.setLineId(item.getLineId());
csharmonic.setTime(LocalDate.parse(date));
String tag = buildOverlimitTag(item);
//统计间隔
Integer lineInterval = 1;
if (!Objects.isNull(lineMap.get(item.getLineId())) && lineMap.get(item.getLineId()).getLineInterval() != 0) {
lineInterval = lineMap.get(item.getLineId()).getLineInterval();
}
String tag = buildOverLimitTag(item,lineInterval);
if (StringUtils.isNotBlank(tag)) {
csharmonic.setTag(buildOverlimitTag(item));
csharmonic.setTag(buildOverLimitTag(item,lineInterval));
list1.add(csharmonic);
//根据监测点id获取设备
@@ -302,6 +321,135 @@ public class DataTaskServiceImpl implements IDataTaskService {
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void channelRunDataAlarm(String time) {
CsAlarm alarm = new CsAlarm();
List<CsEventUserPO> list2 = new ArrayList<>();
//获取所有监测点
List<CsLineDTO> allLine = csLineFeignClient.getAllLineDetail().getData();
if (CollUtil.isNotEmpty(allLine)) {
//过滤物联、在线监测的点
DictTreeVO portable = dictTreeFeignClient.queryByCode(DicDataEnum.PORTABLE.getCode()).getData();
if (ObjectUtil.isNotNull(portable)) {
allLine = allLine.stream().filter(item -> !item.getDeviceType().equals(portable.getId())).collect(Collectors.toList());
}
//设备id集合
List<String> devList = allLine.stream().map(CsLineDTO::getDeviceId).distinct().collect(Collectors.toList());
//获取设备和用户关系
UserDevParam param = new UserDevParam();
param.setList(devList);
List<CsDeviceUserPO> userList = csDeviceUserFeignClient.getList(param).getData();
//根据设备id分组 组是subUserId的集合
Map<String, List<String>> userDevMap = userList.stream().collect(Collectors.groupingBy(
CsDeviceUserPO::getDeviceId,
Collectors.mapping(
CsDeviceUserPO::getSubUserId,
Collectors.toList()
)
));
//获取管理员信息
List<User> adminList = appUserFeignClient.getAdminInfo().getData();
//获取用户id集合
List<String> userIdList = adminList.stream().map(User::getId).collect(Collectors.toList());
//获取时间
String date;
if (StringUtils.isNotBlank(time)) {
date = time;
} else {
date = DateUtil.yesterday().toString(NORM_DATE_PATTERN);
}
//获取在线率、完整性阈值
CsAlarmSet csAlarmSet = csAlarmSetService.getEnabledConfig();
//获取当日的在线率数据
IcdBzParam param1 = new IcdBzParam();
param1.setStartTime(date);
param1.setEndTime(date);
param1.setLineList(devList);
List<RStatOnlineRateD> onlineRateList = onlineRateFeignClient.list(param1).getData();
//获取当日的完整性数据
List<String> lineList = allLine.stream().map(CsLineDTO::getLineId).distinct().collect(Collectors.toList());
param1.setLineList(lineList);
List<RStatIntegrityD> integrityList = integrityClient.list(param1).getData();
// 构建告警数据
List<CsAlarmData> alarmDataList = buildAlarmData(devList, onlineRateList, integrityList, allLine, csAlarmSet);
Map<String,CsAlarmData> alarmDataMap = alarmDataList.stream().collect(Collectors.toMap(CsAlarmData::getDeviceId, item -> item));
//获取告警数据
CsEventUserQueryParam queryParam = new CsEventUserQueryParam();
queryParam.setTarget(devList);
queryParam.setStartTime(date + " 00:00:00");
queryParam.setEndTime(date + " 23:59:59");
List<CsEventPO> alarmList = eventFeignClient.getDevAlarmList(queryParam).getData();
Map<String, List<CsEventPO>> alarmMap = alarmList.stream().collect(Collectors.groupingBy(CsEventPO::getDeviceId));
List<String> l0 = new ArrayList<>();
List<CsAlarmData> l1 = new ArrayList<>();
List<List<String>> l2 = new ArrayList<>();
//step1:构造告警数据
String id = IdUtil.fastSimpleUUID();
alarm.setId(id);
alarm.setTime(LocalDate.parse(date));
devList.forEach(item->{
//写入中断数据
CsAlarmData data1 = alarmDataMap.get(item);
//写入告警数据
List<CsEventPO> data2 = alarmMap.get(item);
List<String> alarmIds = null;
if (CollUtil.isNotEmpty(data2)) {
alarmIds = data2.stream().map(CsEventPO::getId).collect(Collectors.toList());
}
//只要有一个不为空,就需要统计
if (Objects.nonNull(data1) || CollUtil.isNotEmpty(alarmIds)) {
// 对中断时间数据进行过滤,只保留间隔超过 6 小时的时间段
l0.add(item);
l1.add(data1);
l2.add(alarmIds);
}
});
alarm.setDevList(String.join(",", l0));
alarm.setInterruptEvent(new Gson().toJson(l1));
alarm.setAlarmEvent(new Gson().toJson(l2));
//step2:用户告警通知
if (CollUtil.isNotEmpty(l0)) {
Set<String> userIds = new HashSet<>();
l0.forEach(item->{
List<String> ids = userDevMap.get(item);
if (CollUtil.isNotEmpty(ids)) {
userIds.addAll(ids);
}
});
//添加管理员用户
List<String> result = Stream.concat(userIdList.stream(), userIds.stream())
.distinct()
.collect(Collectors.toList());
result.forEach(userId->{
//新增cs_event_user数据
CsEventUserPO po = new CsEventUserPO();
po.setUserId(userId);
po.setEventId(id);
po.setStatus(0);
list2.add(po);
});
}
}
if (ObjectUtil.isNotNull(alarm)) {
//先删除 再录入
List<CsAlarm> oldList = csAlarmFeignClient.queryListByTime(time).getData();
if (CollUtil.isNotEmpty(oldList)) {
List<String> ids = oldList.stream().map(CsAlarm::getId).collect(Collectors.toList());
csAlarmFeignClient.deleteListByTime(time);
eventUserFeignClient.deleteByIds(ids);
}
csAlarmFeignClient.addList(Collections.singletonList(alarm));
eventUserFeignClient.addUserEventList(list2);
}
}
@Override
public void pushAppMsg(String time) {
//查询所有用户-设备关系
@@ -457,6 +605,108 @@ public class DataTaskServiceImpl implements IDataTaskService {
}
}
/**
* 构建告警数据
*/
private List<CsAlarmData> buildAlarmData(List<String> devList,
List<RStatOnlineRateD> onlineRateList,
List<RStatIntegrityD> integrityList,
List<CsLineDTO> allLine,
CsAlarmSet csAlarmSet) {
List<CsAlarmData> result = new ArrayList<>();
if (CollUtil.isEmpty(devList)) {
return result;
}
// 获取在线率阈值和完整性阈值
double onlineRateThreshold = csAlarmSet.getOnlineRateLimit() != null ? csAlarmSet.getOnlineRateLimit().doubleValue() : 60.0;
double integrityThreshold = csAlarmSet.getIntegrityLimit() != null ? csAlarmSet.getIntegrityLimit().doubleValue() : 90.0;
// 构建设备ID到监测点列表的映射
Map<String, List<CsLineDTO>> deviceToLinesMap = allLine.stream()
.collect(Collectors.groupingBy(CsLineDTO::getDeviceId));
// 构建监测点ID到监测点信息的映射
Map<String, CsLineDTO> lineInfoMap = allLine.stream()
.collect(Collectors.toMap(CsLineDTO::getLineId, line -> line, (k1, k2) -> k1));
// 将列表转换为Map便于查找处理null情况
Map<String, RStatOnlineRateD> onlineRateMap = CollUtil.isNotEmpty(onlineRateList)
? onlineRateList.stream().collect(Collectors.toMap(RStatOnlineRateD::getDevIndex, item -> item, (k1, k2) -> k1))
: new HashMap<>();
Map<String, RStatIntegrityD> integrityDataMap = CollUtil.isNotEmpty(integrityList)
? integrityList.stream().collect(Collectors.toMap(RStatIntegrityD::getLineIndex, item -> item, (k1, k2) -> k1))
: new HashMap<>();
// 遍历每个设备
for (String deviceId : devList) {
// 处理在线率数据
RStatOnlineRateD onlineRateData = onlineRateMap.get(deviceId);
// 如果为空默认值为0
int onlineMin = onlineRateData != null ? onlineRateData.getOnlineMin() : 0;
double onlineRateValue = Math.round(onlineMin * 100.0 / 1440 * 100.0) / 100.0;
CsAlarmData.OnlineRateAlarm onlineRateAlarm = new CsAlarmData.OnlineRateAlarm();
onlineRateAlarm.setValue(onlineRateValue);
onlineRateAlarm.setThreshold(onlineRateThreshold);
// value < threshold 时为 true低于阈值为异常
onlineRateAlarm.setIsAbnormal(onlineRateValue < onlineRateThreshold);
// 处理完整性数据 - 按设备分组
List<CsLineDTO> deviceLines = deviceToLinesMap.get(deviceId);
boolean hasIntegrityAbnormal = false;
// 构建完整性数据结构
CsAlarmData.IntegrityAlarm integrityAlarm = new CsAlarmData.IntegrityAlarm();
integrityAlarm.setThreshold(integrityThreshold);
List<CsAlarmData.IntegrityAlarm.MonitorPointIntegrity> monitorPoints = new ArrayList<>();
if (CollUtil.isNotEmpty(deviceLines)) {
// 为该设备下的每个监测点创建完整性数据
for (CsLineDTO line : deviceLines) {
String lineId = line.getLineId();
RStatIntegrityD integrityData = integrityDataMap.get(lineId);
// 如果为空默认值为0
int dueTime = integrityData != null && integrityData.getDueTime() != null ? integrityData.getDueTime() : 0;
int realTime = integrityData != null && integrityData.getRealTime() != null ? integrityData.getRealTime() : 0;
double integrityValue = dueTime > 0 ? Math.round(realTime * 100.0 / dueTime * 100.0) / 100.0 : 0.0;
CsAlarmData.IntegrityAlarm.MonitorPointIntegrity monitorPoint = new CsAlarmData.IntegrityAlarm.MonitorPointIntegrity();
monitorPoint.setMonitorPointId(lineId);
monitorPoint.setMonitorName(line.getName());
monitorPoint.setValue(integrityValue);
// value < threshold 时为 true低于阈值为异常
Boolean isAbnormal = integrityValue < integrityThreshold;
monitorPoint.setIsAbnormal(isAbnormal);
if (isAbnormal) {
hasIntegrityAbnormal = true;
}
monitorPoints.add(monitorPoint);
}
}
integrityAlarm.setMonitorPoints(monitorPoints);
// 只要在线率异常 或 完整性有任意一个监测点异常,就记录该设备的完整数据
if (onlineRateAlarm.getIsAbnormal() || hasIntegrityAbnormal) {
CsAlarmData alarmData = new CsAlarmData();
alarmData.setDeviceId(deviceId);
alarmData.setOnlineRate(onlineRateAlarm);
alarmData.setIntegrity(integrityAlarm);
result.add(alarmData);
}
}
return result;
}
/**
* 过滤时间间隔,只保留超过指定小时数的时间段
@@ -548,64 +798,6 @@ public class DataTaskServiceImpl implements IDataTaskService {
// 按设备 ID 分组
Map<String, List<PqsCommunicate>> deviceCommMap = pqsCommunicates.stream()
.collect(Collectors.groupingBy(PqsCommunicate::getDevId));
// deviceCommMap.forEach((devId, commList) -> {
// // 按时间排序
// commList.sort(Comparator.comparing(PqsCommunicate::getTime));
//
// List<String> offlinePeriods = new ArrayList<>();
// String offlineStartTime = null;
// String offlineEndTime = null;
//
// if (commList.size() == 1) {
// // 只有一条数据的情况
// PqsCommunicate singleRecord = commList.get(0);
// if (singleRecord.getType() == 0) {
// // 掉线:从掉线时间到 24 点
// offlineStartTime = DATE_TIME_FORMATTER.format(singleRecord.getTime());
// offlineEndTime = DATE_TIME_FORMATTER.format(singleRecord.getTime()).substring(0, 10) + " 23:59:59";
// } else {
// // 上线:从 0 点到上线时间
// offlineStartTime = DATE_TIME_FORMATTER.format(singleRecord.getTime()).substring(0, 10) + " 00:00:00";
// offlineEndTime = DATE_TIME_FORMATTER.format(singleRecord.getTime());
// }
// offlinePeriods.add(offlineStartTime + " ~ " + offlineEndTime);
// } else {
// // 多条数据的情况
// for (int i = 0; i < commList.size(); i++) {
// PqsCommunicate current = commList.get(i);
//
// if (current.getType() == 0) {
// // 掉线记录
// if (offlineStartTime == null) {
// offlineStartTime = DATE_TIME_FORMATTER.format(current.getTime());
// }
// // 如果是最后一条记录,结束时间为 24 点
// if (i == commList.size() - 1) {
// offlineEndTime = DATE_TIME_FORMATTER.format(current.getTime()).substring(0, 10) + " 23:59:59";
// offlinePeriods.add(offlineStartTime + " ~ " + offlineEndTime);
// }
// } else {
// // 上线记录
// if (offlineStartTime != null) {
// // 有对应的掉线记录,形成完整时间段
// offlineEndTime = DATE_TIME_FORMATTER.format(current.getTime());
// offlinePeriods.add(offlineStartTime + " ~ " + offlineEndTime);
// offlineStartTime = null;
// offlineEndTime = null;
// } else {
// // 没有对应的掉线记录,说明是从 0 点开始掉线
// offlineStartTime = DATE_TIME_FORMATTER.format(current.getTime()).substring(0, 10) + " 00:00:00";
// offlineEndTime = DATE_TIME_FORMATTER.format(current.getTime());;
// offlinePeriods.add(offlineStartTime + " ~ " + offlineEndTime);
// }
// }
// }
// }
// if (CollUtil.isNotEmpty(offlinePeriods)) {
// result.put(devId, offlinePeriods);
// }
// });
deviceCommMap.forEach((devId, commList) -> {
// 按时间排序
commList.sort(Comparator.comparing(PqsCommunicate::getTime));
@@ -688,7 +880,7 @@ public class DataTaskServiceImpl implements IDataTaskService {
* @param item 越限统计数据
* @return 越限标签
*/
private String buildOverlimitTag(RStatLimitRateDPO item) {
private String buildOverLimitTag(RStatLimitRateDPO item, Integer lineInterval) {
StringBuilder tagBuilder = new StringBuilder();
String planId = csHarmonicPlanLineFeignClient.getPlanIdByLineId(item.getLineId()).getData();
@@ -707,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(freqDevOvertime).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(voltageDevOvertime).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(ubalanceOvertime).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(flickerOvertime).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(uaberranceOvertime).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(iNegOvertime).append("");
tagBuilder.append("负序电流越限").append(TimeUtil.convertMinutes(Math.min(iNegOvertime * lineInterval,1440))).append("");
}
for (int i = 2; i <= 25; i++) {
@@ -741,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(value).append("");
tagBuilder.append(i).append("次谐波电压含有率越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
}
@@ -752,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(value).append("");
tagBuilder.append(i).append("次谐波电流有效值越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
}
@@ -764,52 +956,52 @@ public class DataTaskServiceImpl implements IDataTaskService {
double harmonicOrder = i * 1.0 - 0.5;
String targetName = harmonicOrder + "次间谐波电压含有率";
if (targetSet.contains(targetName)) {
tagBuilder.append(harmonicOrder).append("次间谐波电压含有率越限").append(value).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(freqDevOvertime).append("");
tagBuilder.append("频率偏差越限").append(TimeUtil.convertMinutes(Math.min(freqDevOvertime * lineInterval,1440))).append("");
}
Integer voltageDevOvertime = item.getVoltageDevOvertime();
if (voltageDevOvertime != null && voltageDevOvertime > 0) {
tagBuilder.append("电压偏差越限").append(voltageDevOvertime).append("");
tagBuilder.append("电压偏差越限").append(TimeUtil.convertMinutes(Math.min(voltageDevOvertime * lineInterval,1440))).append("");
}
Integer ubalanceOvertime = item.getUbalanceOvertime();
if (ubalanceOvertime != null && ubalanceOvertime > 0) {
tagBuilder.append("三相电压不平衡度越限").append(ubalanceOvertime).append("");
tagBuilder.append("三相电压不平衡度越限").append(TimeUtil.convertMinutes(Math.min(ubalanceOvertime * lineInterval,1440))).append("");
}
Integer flickerOvertime = item.getFlickerOvertime();
if (flickerOvertime != null && flickerOvertime > 0) {
tagBuilder.append("闪变越限").append(flickerOvertime).append("");
tagBuilder.append("闪变越限").append(TimeUtil.convertMinutes(Math.min(flickerOvertime * 120,1440))).append("分钟");
}
Integer uaberranceOvertime = item.getUaberranceOvertime();
if (uaberranceOvertime != null && uaberranceOvertime > 0) {
tagBuilder.append("电压总谐波畸变率越限").append(uaberranceOvertime).append("");
tagBuilder.append("电压总谐波畸变率越限").append(TimeUtil.convertMinutes(Math.min(uaberranceOvertime * lineInterval,1440))).append("");
}
Integer iNegOvertime = item.getINegOvertime();
if (iNegOvertime != null && iNegOvertime > 0) {
tagBuilder.append("负序电流越限").append(iNegOvertime).append("");
tagBuilder.append("负序电流越限").append(TimeUtil.convertMinutes(Math.min(iNegOvertime * lineInterval,1440))).append("");
}
String harmonicVoltageTag = buildHarmonicVoltageTags(item, "");
String harmonicVoltageTag = buildHarmonicVoltageTags(item, "", lineInterval);
if (StrUtil.isNotBlank(harmonicVoltageTag)) {
tagBuilder.append(harmonicVoltageTag);
}
String harmonicCurrentTag = buildHarmonicCurrentTags(item, "");
String harmonicCurrentTag = buildHarmonicCurrentTags(item, "", lineInterval);
if (StrUtil.isNotBlank(harmonicCurrentTag)) {
tagBuilder.append(harmonicCurrentTag);
}
String interharmonicTag = buildInterharmonicVoltageTags(item, "");
String interharmonicTag = buildInterharmonicVoltageTags(item, "", lineInterval);
if (StrUtil.isNotBlank(interharmonicTag)) {
tagBuilder.append(interharmonicTag);
}
@@ -818,124 +1010,6 @@ public class DataTaskServiceImpl implements IDataTaskService {
return trimTrailingComma(tagBuilder.toString());
}
// private String buildOverlimitTag(RStatLimitRateDPO item) {
// String tag = "";
//
// //获取监测点配置的稳态指标,如果没有配置则查询所有指标
// String planId = csHarmonicPlanLineFeignClient.getPlanIdByLineId(item.getLineId()).getData();
// if (planId != null) {
// CsHarmonicPlan csHarmonicPlan = csHarmonicPlanFeignClient.getById(planId).getData();
// String harmonicTarget = csHarmonicPlan.getHarmonicTarget();
// List<String> targetList = Arrays.asList(harmonicTarget.split(","));
//
// Integer freqDevOvertime = item.getFreqDevOvertime();
// if (freqDevOvertime > 0 && targetList.contains("频率偏差")) {
// tag = tag + "频率偏差越限" + freqDevOvertime + "次,";
// }
//
// Integer voltageDevOvertime = item.getVoltageDevOvertime();
// if (voltageDevOvertime > 0 && targetList.contains("电压偏差")) {
// tag = tag + "电压偏差越限" + voltageDevOvertime + "次,";
// }
//
// Integer ubalanceOvertime = item.getUbalanceOvertime();
// if (ubalanceOvertime > 0 && targetList.contains("三相电压不平衡度")) {
// tag = tag + "三相电压不平衡度越限" + ubalanceOvertime + "次,";
// }
//
// Integer flickerOvertime = item.getFlickerOvertime();
// if (flickerOvertime > 0 && targetList.contains("闪变")) {
// tag = tag + "闪变越限" + flickerOvertime + "次,";
// }
//
// Integer uaberranceOvertime = item.getUaberranceOvertime();
// if (uaberranceOvertime > 0 && targetList.contains("电压总谐波畸变率")) {
// tag = tag + "电压总谐波畸变率越限" + uaberranceOvertime + "次,";
// }
//
// Integer iNegOvertime = item.getINegOvertime();
// if (iNegOvertime > 0 && targetList.contains("负序电流")) {
// tag = tag + "负序电流越限" + iNegOvertime + "次,";
// }
//
// for (int i = 2; i <= 25; i++) {
// String fieldName = "uharm" + i + "Overtime";
// Integer value = (Integer) ReflectUtil.getFieldValue(item, fieldName);
// if (value != null && value > 0) {
// String targetName = i + "次谐波电压含有率";
// if (targetList.contains(targetName)) {
// tag = tag + i + "次谐波电压含有率越限" + value + "次,";
// }
// }
// }
//
// for (int i = 2; i <= 25; i++) {
// String fieldName = "iharm" + i + "Overtime";
// Integer value = (Integer) ReflectUtil.getFieldValue(item, fieldName);
// if (value != null && value > 0) {
// String targetName = i + "次谐波电流有效值";
// if (targetList.contains(targetName)) {
// tag = tag + i + "次谐波电流有效值越限" + value + "次,";
// }
// }
// }
//
// 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;
// String targetName = harmonicOrder + "次间谐波电压含有率";
// if (targetList.contains(targetName)) {
// tag = tag + harmonicOrder + "次间谐波电压含有率越限" + value + "次,";
// }
// }
// }
// } else {
// // 基础越限项
// Integer freqDevOvertime = item.getFreqDevOvertime();
// if (freqDevOvertime > 0) {
// tag = tag + "频率偏差越限" + freqDevOvertime + "次,";
// }
//
// Integer voltageDevOvertime = item.getVoltageDevOvertime();
// if (voltageDevOvertime > 0) {
// tag = tag + "电压偏差越限" + voltageDevOvertime + "次,";
// }
//
// Integer ubalanceOvertime = item.getUbalanceOvertime();
// if (ubalanceOvertime > 0) {
// tag = tag + "三相电压不平衡度越限" + ubalanceOvertime + "次,";
// }
//
// Integer flickerOvertime = item.getFlickerOvertime();
// if (flickerOvertime > 0) {
// tag = tag + "闪变越限" + flickerOvertime + "次,";
// }
//
// Integer uaberranceOvertime = item.getUaberranceOvertime();
// if (uaberranceOvertime > 0) {
// tag = tag + "电压总谐波畸变率越限" + uaberranceOvertime + "次,";
// }
//
// Integer iNegOvertime = item.getINegOvertime();
// if (iNegOvertime > 0) {
// tag = tag + "负序电流越限" + iNegOvertime + "次,";
// }
//
// // 谐波电压含有率2-25 次)
// tag = buildHarmonicVoltageTags(item, tag);
//
// // 谐波电流有效值2-25 次)
// tag = buildHarmonicCurrentTags(item, tag);
//
// // 间谐波电压含有率0.5-15.5 次)
// tag = buildInterharmonicVoltageTags(item, tag);
// }
// // 去除末尾逗号
// return trimTrailingComma(tag);
// }
/**
* 批量构建谐波电压含有率 tag2-25 次)
*
@@ -943,16 +1017,16 @@ public class DataTaskServiceImpl implements IDataTaskService {
* @param originalTag 原始 tag
* @return 组装后的 tag
*/
public static String buildHarmonicVoltageTags(Object item, String originalTag) {
String tag = originalTag;
public static String buildHarmonicVoltageTags(Object item, String originalTag, Integer lineInterval) {
StringBuilder tag = new StringBuilder(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.append(i).append("次谐波电压含有率越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
return tag;
return tag.toString();
}
/**
@@ -962,16 +1036,16 @@ public class DataTaskServiceImpl implements IDataTaskService {
* @param originalTag 原始 tag
* @return 组装后的 tag
*/
public static String buildHarmonicCurrentTags(Object item, String originalTag) {
String tag = originalTag;
public static String buildHarmonicCurrentTags(Object item, String originalTag, Integer lineInterval) {
StringBuilder tag = new StringBuilder(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.append(i).append("次谐波电流有效值越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
return tag;
return tag.toString();
}
/**
@@ -981,17 +1055,17 @@ public class DataTaskServiceImpl implements IDataTaskService {
* @param originalTag 原始 tag
* @return 组装后的 tag
*/
public static String buildInterharmonicVoltageTags(Object item, String originalTag) {
String tag = originalTag;
public static String buildInterharmonicVoltageTags(Object item, String originalTag, Integer lineInterval) {
StringBuilder tag = new StringBuilder(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.append(harmonicOrder).append("次间谐波电压含有率越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
return tag;
return tag.toString();
}
/**

Some files were not shown because too many files have changed in this diff Show More