81 Commits

Author SHA1 Message Date
xy
709262c2b4 fix(auth): 解决非手机号注册用户查询异常及自动登录接口配置问题
- 在AppInfoSetController中添加空值检查,抛出业务异常提示非手机号注册用户需联系管理员
- 修改AuthController中自动登录接口为POST方法并更新相关参数配置
- 更新用户权限类型参数验证范围从0-2扩展到0-3以支持更多权限类型
2026-06-26 15:22:56 +08:00
e2e7669d47 1.限值负序电流调整 2026-06-26 11:52:29 +08:00
83907cd3ee 1.bug调整 2026-06-25 18:27:44 +08:00
xy
5a0e990f90 refactor(service): 移除线路治理状态设置逻辑
- 注释掉线路治理状态的条件判断代码
- 删除未治理和已治理状态的设置逻辑
- 保留其他线路信息设置功能
2026-06-25 15:52:50 +08:00
f00af22b33 1.台账增加默认排序
2.增加场站/用户监测规模接口
2026-06-23 21:30:27 +08:00
xy
7f13d3576d feat(user): 添加手机号重复注册检查并调整默认消息设置
- 添加手机号唯一性验证逻辑,防止重复注册
- 新增 REGISTER_PHONE_REPEAT 业务异常枚举
- 调整新用户默认消息配置:harmonicInfo从1改为0
- 调整新用户默认消息配置:runInfo从1改为0
- 调整新用户默认消息配置:alarmInfo从1改为0
2026-06-22 19:58:41 +08:00
xy
c4f5d1b543 refactor(dict): 重构字典类型查询方法参数类型
- 将 queryDictType 方法的 lineId 参数从 String 类型改为 Integer 类型
- 更新接口定义中的参数类型声明
- 修改控制器层方法签名以匹配新的参数类型
- 调整业务逻辑中对参数的处理方式,从字符串末尾字符判断改为整数比较
- 移除不再需要的 SysDicTreePOMapper 导入
- 更新 API 文档注解中的参数描述信息
2026-06-22 13:45:54 +08:00
xy
6451cfeb88 refactor(gateway): 移除CS系统应用版本获取接口配置
- 移除 /cs-system-boot/appVersion/getLastData 接口路径配置
- 清理相关的历史数据分析接口配置项
- 优化网关路由规则避免不必要的路径暴露
2026-06-18 15:44:52 +08:00
xy
6eedee7783 fix(user): 修复用户注册逻辑并更新Redis键格式
- 修改设备模板和监测点位置的Redis键格式,统一添加冒号后缀
- 移除未使用的ResponseEntity导入
- 简化用户注册流程,移除重复的手机号验证逻辑
- 在网关配置中添加新的白名单接口路径
2026-06-18 15:29:05 +08:00
hzj
21fe98db49 修改生成报告画图采样率 2026-06-18 10:21:07 +08:00
hzj
bf9779c06e 暂态原因计算问题 2026-06-17 16:06:29 +08:00
cdf
368103cad5 Merge remote-tracking branch 'origin/main' 2026-06-17 14:21:17 +08:00
cdf
507a7f7a09 辽宁CAS统一认证兼容 2026-06-17 14:19:52 +08:00
wr
c1dfcb9236 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	pqs-device/pq-device/pq-device-boot/src/main/java/com/njcn/device/pq/service/impl/RStatIntegrityDServiceImpl.java
2026-06-17 14:14:16 +08:00
wr
f5eb2c7af6 1.解决数据质量监测点数据完整性查询过慢问题 2026-06-17 14:11:24 +08:00
hzj
d36c30973d 添加日志查询慢接口 2026-06-17 13:54:44 +08:00
hzj
148e834f9c 代码优化 2026-06-16 16:25:50 +08:00
hzj
9a9a8151d9 代码优化 2026-06-16 15:55:22 +08:00
hzj
ca8bd9fea2 优化前置切换装置进程重置代码 2026-06-16 14:52:03 +08:00
wr
770b707b84 1.前置交互日志扩展模糊查询
2.解决暂态时间12小时制的问题
3.优化文件工具类
2026-06-16 09:58:24 +08:00
0196277eb2 1.台账增加默认排序
2.增加场站/用户监测规模接口
2026-06-15 10:21:14 +08:00
hzj
6e4a294b00 Merge remote-tracking branch 'origin/main' 2026-06-12 10:25:07 +08:00
xy
1e5acdd214 feat(mq): 添加日志消息处理功能
- 在BusinessTopic中新增ZL_LOG_TOPIC常量
- 添加LogTag接口用于日志标签定义
- 创建LogMessage类定义日志消息结构
- 实现LogMessageTemplate用于发送日志消息
- 集成RocketMQ增强模板支持日志消息发送
- 定义日志消息的数据类型和操作字段
2026-06-11 19:55:24 +08:00
hzj
2754969dfc 暂态高级算法异步 2026-06-11 16:59:16 +08:00
hzj
4c083c84e5 oss兼容 2026-06-10 17:51:24 +08:00
hzj
6e26c81ff9 oss兼容 2026-06-10 16:14:56 +08:00
hzj
ba7ae8da9e oss兼容 2026-06-10 16:08:37 +08:00
hzj
ef6c464897 oss兼容 2026-06-10 15:55:20 +08:00
hzj
743cbfbdcb 暂降报告修改 2026-06-09 15:46:34 +08:00
hzj
48cddd92b0 暂降报告修改 2026-06-09 11:09:19 +08:00
cdf
ee5526b0f7 区域报告修改,添加间谐波电压含有率 2026-06-08 16:38:15 +08:00
cdf
11306f1d00 区域报告修改,添加间谐波电压含有率 2026-06-08 16:33:53 +08:00
hzj
85ab4de719 区域报表修改 2026-06-08 11:30:36 +08:00
xy
552573df00 暂态报告新增是否只统计暂降条件 2026-06-08 10:13:47 +08:00
cdf
50181459bf 区域报告修改,添加间谐波电压含有率 2026-06-07 15:55:50 +08:00
cdf
748fd62afb Merge remote-tracking branch 'origin/main' 2026-06-05 18:42:14 +08:00
hzj
749c1d954c 区域报表修改 2026-06-05 16:32:55 +08:00
xy
6089be6b4a feat(report): 电压暂降事件报告导出功能优化 2026-06-05 11:16:15 +08:00
xy
eb89472670 微调 2026-06-04 18:28:51 +08:00
xy
56cd9a05c3 feat(echarts): 添加波形图绘制功能支持
- 新增drawWavePic方法用于绘制波形图
- 实现null数据段压缩算法,确保图表性能优化
- 添加markLine和markArea功能显示null段边界标记
- 集成到WavePicComponent组件中支持瞬时和RMS波形图生成
- 修复RestTemplate对Hutool JSON对象的支持问题
- 优化WaveUtil工具类处理空值数据逻辑
2026-06-04 18:27:47 +08:00
xy
aafd32c7fc refactor(sms): 重构短信发送功能并优化数据库配置
- 移除旧的短信发送实现和相关依赖
- 引入新的短信发送服务接口和实现
- 添加短信发送记录实体和数据访问层
- 创建短信发送控制器提供REST API
- 实现带重试机制的短信发送功能
- 添加系统凭证管理和缓存机制
- 更新数据库连接配置信息
- 修改统计查询接口参数类型
- 清理过时的代码和服务方法
2026-06-03 10:20:25 +08:00
cdf
46969f7e02 Merge remote-tracking branch 'origin/main' 2026-06-01 10:02:47 +08:00
xy
79cec4e21b feat(event): 新增压降落点区域判定功能
- 在EventAnalysisService中添加determineDropZone方法用于判定压降落点区域
- 实现压降落点区域判定逻辑,支持A/B/C/D四个区域的分类判断
- 添加精确的数值范围匹配算法,使用BigDecimal确保计算精度
- 集成日志记录功能,便于问题排查和监控
- 在RedisUtil中新增scanKeysByPattern方法支持模糊查询key功能
- 优化代码结构,移除冗余的导入包和空行
- 更新类级别的注解配置,添加@Slf4j注解支持日志功能
2026-05-27 18:10:15 +08:00
hzj
615fe78d61 辽宁稳态指标超标明细等页面丰富查询条件; 2026-05-22 14:05:53 +08:00
hzj
5fff0890e8 数据清洗移动包修改 2026-05-21 15:15:24 +08:00
hzj
f5e134b194 数据清洗移动包修改 2026-05-21 15:00:13 +08:00
hzj
291a20649e 添加控制task是否执行配置business:task-enabled: false为true是执行,false不执行,缺省默认为true只行,只有没有前置微服务版本配置false; 2026-05-21 11:11:38 +08:00
cdf
fdd6ff574f Merge remote-tracking branch 'origin/main' 2026-05-20 17:00:58 +08:00
hzj
7eef16599f 台账模版导入功能修复 2026-05-20 15:58:48 +08:00
xy
11750a4f3a fix(service): 修正电力参数默认相位设置
- 将新增记录时的默认相位从"M"改为"T"
- 将更新记录时的默认相位从"M"改为"T"
- 确保相位字段在空值情况下统一使用"T"作为默认值
2026-05-20 14:18:03 +08:00
cdf
e5ffa2ec29 修改自定义报表处理没有模板情况,使用默认模板 2026-05-18 16:13:28 +08:00
hzj
e6332f1c51 装置文件系统访问 2026-05-15 13:36:51 +08:00
cdf
23d87aecc8 修改自定义报表适配分钟/统计数据查询 2026-05-14 17:05:43 +08:00
xy
eff784e94e feat(mq): 添加治理心跳过期处理消息功能 2026-05-14 09:20:42 +08:00
hzj
eed647d3d1 高级算法异常抛出 2026-04-30 12:25:25 +08:00
hzj
4a5fde6a47 设备退运bug修复 2026-04-27 16:23:53 +08:00
hzj
82ab1de5b9 Merge remote-tracking branch 'origin/main' 2026-04-27 16:21:16 +08:00
hzj
ecc56dd2f6 暂态原因算法bug修复 2026-04-27 16:19:43 +08:00
xy
39ae7412a8 微调 2026-04-27 15:33:08 +08:00
xy
52677f84dc fix(utils): 修复JNA调用动态库的路径和错误处理问题
- 移除硬编码的文件后缀名,根据操作系统自动识别.dll或.so文件
- 修正Linux系统下的库文件命名规则,移除多余的"_dll"后缀
- 添加对文件扩展名的条件判断,在Windows下确保.dll后缀
- 添加动态库加载成功后的路径打印功能
2026-04-27 15:32:39 +08:00
cdf
abdb855919 注释prepareboot模块无用代码 2026-04-23 15:11:07 +08:00
cdf
64bcbfff91 注释prepareboot模块无用代码 2026-04-23 14:56:12 +08:00
wr
499eee6784 redis工具类优化 2026-04-23 14:37:24 +08:00
caozehui
c58bd87a78 微调 2026-04-23 09:11:02 +08:00
caozehui
0902f92838 Merge remote-tracking branch 'origin/main' 2026-04-23 08:53:24 +08:00
xy
87818db6f3 微调 2026-04-21 16:00:46 +08:00
caozehui
850b3174a2 云前置文件文件目录功能 2026-04-20 13:43:26 +08:00
aad5943d64 fix(waveform): 修复录波文件处理中的RMS段逻辑错误
- 在RateDTO初始化时设置bRMSFlag默认值为false,确保16~31点/周波段按普通抽点处理
- 修复RMS段与普通抽点的控制流程分离,避免共享取模条件导致的逻辑混乱
- 优化RMS段处理逻辑,添加周波索引推进机制防止重复处理
- 修复2点/周波时半周波位置的采样点切换逻辑
- 添加段末尾对齐机制,确保外层循环能稳定跳转到下一段起点
- 更新测试文件路径配置,使用新的测试数据文件
2026-04-17 15:44:18 +08:00
cdf
9c467310d5 用能添加mqtt支持 2026-04-16 14:19:33 +08:00
cdf
ca3b125424 用能添加mqtt支持 2026-04-16 14:08:05 +08:00
hzj
0c5c9bf067 删除MQTT相关代码 2026-04-16 13:47:30 +08:00
hzj
c692282ea4 bug修复 2026-04-15 10:43:46 +08:00
232e84aad3 波形解析的电流一次值转二次值调整 2026-04-15 10:20:48 +08:00
xy
59f2588488 生成文件自定义文件名称 2026-04-14 19:07:11 +08:00
hzj
46f521c7a7 谐波频谱查询Influxdb分钟数据修改成查询mysql统计数据 2026-04-10 13:32:36 +08:00
hzj
6d69027e16 数据完整性页面添加字段objname 监测对象 2026-04-09 15:41:14 +08:00
hzj
1afed2c9a4 数据完整性页面添加字段objname 监测对象 2026-04-09 15:40:38 +08:00
hzj
9bb250bdb9 优化查询 2026-04-09 09:05:56 +08:00
hzj
d33b3637a5 暂态事件推送由MQTT切换成Websocket 2026-04-09 09:05:02 +08:00
hzj
f50f11b159 优化前置下线装置状态翻转 2026-04-09 08:57:12 +08:00
xy
30984aa908 暂态事件波形解析代码调整 2026-04-08 19:27:57 +08:00
160 changed files with 10247 additions and 6826 deletions

View File

@@ -26,8 +26,6 @@ import java.util.*;
public class AnalyWave { public class AnalyWave {
/***************************************** /*****************************************
* 解析comtrate文件工具类 * 解析comtrate文件工具类
* author yexb根据Ww算法装换 * author yexb根据Ww算法装换
@@ -297,8 +295,6 @@ public class AnalyWave {
strBinType = iterable.next().toUpperCase(); strBinType = iterable.next().toUpperCase();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
logger.error("读取文件内容出错" + e.getMessage()); logger.error("读取文件内容出错" + e.getMessage());
@@ -306,7 +302,6 @@ public class AnalyWave {
} finally { } finally {
} }
return true; return true;
} }
@@ -319,15 +314,8 @@ public class AnalyWave {
private List<List<Float>> AnalyseComtradeDat(byte[] array, int iFlag) { private List<List<Float>> AnalyseComtradeDat(byte[] array, int iFlag) {
float xValueAll = 0;//初始化xValue的值 float xValueAll = 0;//初始化xValue的值
boolean blxValue = false;//判断是否首次登陆 boolean blxValue = false;//判断是否首次登陆
List<List<Float>> listWaveData = new ArrayList<>();//返回数据 List<List<Float>> listWaveData = new ArrayList<>();//返回数据
try { try {
// 计算每个单独的数据块的大小 4字节的序号 4字节的时间 2字节的值 // 计算每个单独的数据块的大小 4字节的序号 4字节的时间 2字节的值
// 示例中的排布是 4字节的序号 4字节的时间 UA(2字节) UB(2字节) UC(2字节) IA(2字节) IB(2字节) // 示例中的排布是 4字节的序号 4字节的时间 UA(2字节) UB(2字节) UC(2字节) IA(2字节) IB(2字节)
// IC(2字节) // IC(2字节)
@@ -470,7 +458,7 @@ public class AnalyWave {
{ {
if (ComtradeCfg.OneChannleCfg.get(j).fPrimary != 0.0f)//根据cfg内的变比将一次值转换成二次值 if (ComtradeCfg.OneChannleCfg.get(j).fPrimary != 0.0f)//根据cfg内的变比将一次值转换成二次值
{ {
fValue = ComtradeCfg.OneChannleCfg.get(j).fSecondary / ComtradeCfg.OneChannleCfg.get(j).fPrimary; fValue = fValue * ComtradeCfg.OneChannleCfg.get(j).fSecondary / ComtradeCfg.OneChannleCfg.get(j).fPrimary;
} else { } else {
fValue = fValue; fValue = fValue;
} }

View File

@@ -129,10 +129,10 @@ public class EventRelevantAnalysisController extends BaseController {
@PostMapping("/updateEventToAss") @PostMapping("/updateEventToAss")
@ApiOperation("把暂降事件添加到指定事件中去") @ApiOperation("把暂降事件添加到指定事件中去")
public HttpResult<Page<AdvanceEventDetailVO>> updateEventToAss(@RequestBody Map<String,Object> map){ public HttpResult<Page<AdvanceEventDetailVO>> updateEventToAss(@RequestBody Map<String,Object> map){
String methodDescribe = getMethodDescribe("updateEventToAss");
if(!map.containsKey("eventId") || !map.containsKey("assId")){ if(!map.containsKey("eventId") || !map.containsKey("assId")){
throw new BusinessException("参数异常"); throw new BusinessException("参数异常");
} }
String methodDescribe = getMethodDescribe("updateEventToAss");
List<String> eventIds = (List<String>) map.get("eventId"); List<String> eventIds = (List<String>) map.get("eventId");
if(CollectionUtil.isEmpty(eventIds)){ if(CollectionUtil.isEmpty(eventIds)){
throw new BusinessException("暂降事件不可为空"); throw new BusinessException("暂降事件不可为空");

View File

@@ -7,7 +7,6 @@ import com.njcn.advance.event.cause.model.DataFeature;
import com.njcn.advance.event.type.jna.*; import com.njcn.advance.event.type.jna.*;
import com.njcn.advance.pojo.dto.EventAnalysisDTO; import com.njcn.advance.pojo.dto.EventAnalysisDTO;
import com.njcn.advance.event.service.IEventAdvanceService; import com.njcn.advance.event.service.IEventAdvanceService;
import com.njcn.advance.pojo.dto.waveAnalysis.Rect;
import com.njcn.advance.utils.Utils; import com.njcn.advance.utils.Utils;
import com.njcn.common.config.GeneralInfo; import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
@@ -26,6 +25,8 @@ import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/** /**
* @author hongawen * @author hongawen
@@ -43,9 +44,13 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
private final FileStorageUtil fileStorageUtil; private final FileStorageUtil fileStorageUtil;
private final Lock lock = new ReentrantLock();
@Override @Override
public EventAnalysisDTO analysisCauseAndType(EventAnalysisDTO eventAnalysis) { public EventAnalysisDTO analysisCauseAndType(EventAnalysisDTO eventAnalysis) {
//由于计算原因是异步操作这里需要加锁不然JNI调用ddl文件会存在内存Invalid memory access
lock.lock();
try {
WaveDataDTO waveDataDTO; WaveDataDTO waveDataDTO;
String waveName = eventAnalysis.getWaveName(); String waveName = eventAnalysis.getWaveName();
String wlFilePath = eventAnalysis.getWlFilePath(); String wlFilePath = eventAnalysis.getWlFilePath();
@@ -75,7 +80,7 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) { if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND); throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
} }
waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 0); waveDataDTO = waveFileComponent.getComtradeNoAddPoints(cfgStream, datStream, 0);
} catch (Exception e) { } catch (Exception e) {
try { try {
InputStream cfgStream = fileStorageUtil.getFileStream(cfgPath2); InputStream cfgStream = fileStorageUtil.getFileStream(cfgPath2);
@@ -112,7 +117,6 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
try { try {
QvvrDLL.INSTANCE.qvvr_fun(typeDataStruct); QvvrDLL.INSTANCE.qvvr_fun(typeDataStruct);
System.out.println("调用qvvrdll成功-----------"); System.out.println("调用qvvrdll成功-----------");
if (typeDataStruct.evt_num > 0) { if (typeDataStruct.evt_num > 0) {
// 全局比较找出最小三相电压特征值 // 全局比较找出最小三相电压特征值
float globalMinVoltage = Float.MAX_VALUE; float globalMinVoltage = Float.MAX_VALUE;
@@ -127,25 +131,14 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
} }
} }
} }
String str = WriteData2File(typeDataStruct);
if (Objects.isNull(wlFilePath)) {
String hdrPath = OssPath.WAVE_DIR + ip+StrUtil.SLASH;
String hdrName = waveName + GeneralConstant.HDR_LOWER;
fileStorageUtil.uploadStreamSpecifyName(new ByteArrayInputStream(str.getBytes()),hdrPath,hdrName);
} else {
// comtrade/00:B7:8D:00:A8:7A/PQMonitor_PQM1_00100_20260204_162453_071_WAV.hdr
String fullPath = wlFilePath + GeneralConstant.HDR_LOWER;
int lastSlashIndex = fullPath.lastIndexOf('/');
String hdrPath = fullPath.substring(0, lastSlashIndex + 1);
String hdrName = fullPath.substring(lastSlashIndex + 1);
fileStorageUtil.uploadStreamSpecifyName(new ByteArrayInputStream(str.getBytes()),hdrPath,hdrName);
}
//上传HR //上传HR
eventAnalysis.setType(globalFaultType); eventAnalysis.setType(globalFaultType);
} else { } else {
eventAnalysis.setType(DataFeature.TYPE10); eventAnalysis.setType(DataFeature.TYPE10);
} }
System.out.println("结束qvvrdll方法调用-----------"); System.out.println("结束qvvrdll方法调用-----------");
} catch (Exception e) { } catch (Exception e) {
eventAnalysis.setType(DataFeature.TYPE10); eventAnalysis.setType(DataFeature.TYPE10);
@@ -174,12 +167,33 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
eventAnalysis.setCause(DataFeature.CAUSE_TYPE0); eventAnalysis.setCause(DataFeature.CAUSE_TYPE0);
eventAnalysis.setCauseFlag(0); eventAnalysis.setCauseFlag(0);
} }
String str = null;
try {
str = WriteData2File(typeDataStruct,causeDataStruct);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (Objects.isNull(wlFilePath)) {
String hdrPath = OssPath.WAVE_DIR + ip+StrUtil.SLASH;
String hdrName = waveName + GeneralConstant.HDR_LOWER;
fileStorageUtil.uploadStreamSpecifyName(new ByteArrayInputStream(str.getBytes()),hdrPath,hdrName);
} else {
// comtrade/00:B7:8D:00:A8:7A/PQMonitor_PQM1_00100_20260204_162453_071_WAV.hdr
String fullPath = wlFilePath + GeneralConstant.HDR_LOWER;
int lastSlashIndex = fullPath.lastIndexOf('/');
String hdrPath = fullPath.substring(0, lastSlashIndex + 1);
String hdrName = fullPath.substring(lastSlashIndex + 1);
fileStorageUtil.uploadStreamSpecifyName(new ByteArrayInputStream(str.getBytes()),hdrPath,hdrName);
}
System.out.println("暂降原因分析完毕==============="); System.out.println("暂降原因分析完毕===============");
System.out.println("cause:" + eventAnalysis); System.out.println("cause:" + eventAnalysis);
} finally {
lock.unlock(); // 释放锁
}
return eventAnalysis; return eventAnalysis;
} }
public String WriteData2File(QvvrDLL.QvvrDataStruct rect) throws Exception { public String WriteData2File(QvvrDLL.QvvrDataStruct rect, QvvrCauseDLL.QvvrDataStruct causeDataStruct) throws Exception {
StringBuilder stringBuilder = new StringBuilder("{" + EnumEvt.NEWLINE.getProperty()); StringBuilder stringBuilder = new StringBuilder("{" + EnumEvt.NEWLINE.getProperty());
/** /**
@@ -414,7 +428,7 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
*/ */
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) { for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.QVVR_CATA_CAUSE.getProperty(), null, setEigenVlaue(k, stringBuilder, EnumEvt.QVVR_CATA_CAUSE.getProperty(), null,
rect.evt_buf[i].qvvr_cata_cause[k]); causeDataStruct.cause);
if (rect.evt_buf[i].u_min_num - 1 == k) { if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1); stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
@@ -458,6 +472,10 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(2), 2)); stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(2), 2));
} }
} }
if(rect.evt_num==0){
stringBuilder.append("]");
}
stringBuilder.append("}"); stringBuilder.append("}");
return stringBuilder.toString(); return stringBuilder.toString();

View File

@@ -177,12 +177,6 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
} }
disposeNonStandardData(handleEvent, baseList, listEventAssObj, listSagEvent, date); disposeNonStandardData(handleEvent, baseList, listEventAssObj, listSagEvent, date);
@@ -223,231 +217,12 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
relevantLogMapper.insert(entityPqsRelevance); relevantLogMapper.insert(entityPqsRelevance);
log.info("事件关联分析用时:" + timeInterval.interval() / 1000 + ""); log.info("事件关联分析用时:" + timeInterval.interval() / 1000 + "");
} }
// @Override
// @Transactional(rollbackFor = Exception.class)
// public void processEvents(LocalDateTime startTime, LocalDateTime endTime) {
//
// TimeInterval timeInterval = new TimeInterval();
//
//
// Map<String, Map<String, Integer>> nodeSort = new HashMap<>();
// Map<String, EntityMtrans> entityMtransMap = getNodeInfo();
//
//
//
//
//
// for (Map.Entry<String, Map<String, Integer>> m : nodeSort) {
// List<EntityGroupEvtData> list = new ArrayList<EntityGroupEvtData>();
// Set<Map.Entry<String, Integer>> mapValue = m.getValue().entrySet();
// FinalData.NODE_NUM = m.getValue().size();
//
// for (Map.Entry<String, Integer> mm : mapValue) {
// for (int i = 0; i < entityGroupEvtDatas.length; i++) {
// if (entityGroupEvtDatas[i].getNodePhysics() == mm.getKey().intValue() && "短路故障".equals(entityGroupEvtDatas[i].getSagReason())) {
// entityGroupEvtDatas[i].setNode(mm.getValue());
// list.add(entityGroupEvtDatas[i]);
// }
// }
//
// // 筛选不在矩阵中的事件id
// Iterator<EntityGroupEvtData> iterator = list3.iterator();
// while (iterator.hasNext()) {
// EntityGroupEvtData entityGroupEvtData = iterator.next();
//
// if (entityGroupEvtData.getNodePhysics() == mm.getKey().intValue() && "短路故障".equals(entityGroupEvtData.getSagReason())) {
// iterator.remove();
// }
// }
// }
//
// EntityGroupEvtData[] entityGroupEvtData = new EntityGroupEvtData[list.size()];
// Collections.sort(list);
// list.toArray(entityGroupEvtData);
//
// for (Map.Entry<String, JSONObject> mEntry : setMtrans) {
// if (mEntry.getKey().equals(m.getKey())) {
// *//**//********************************************************************
// * 算法最多处理1000条数据超过限制需分批处理 先将数据根据某种方式进行升序/降序排序,然后分段处理 加入循环处理
// *********************************************************************//**//*
// int circulation = entityGroupEvtData.length % FinalData.MAX_EVT_NUM == 0
// ? entityGroupEvtData.length / FinalData.MAX_EVT_NUM
// : entityGroupEvtData.length / FinalData.MAX_EVT_NUM + 1;
//
// for (int i = 0; i < circulation; i++) {
// int to = 0;
//
// if (i == circulation - 1) {
// to = entityGroupEvtData.length % FinalData.MAX_EVT_NUM > 0
// ? entityGroupEvtData.length
// : (i + 1) * FinalData.MAX_EVT_NUM - 1;
// } else {
// to = (i + 1) * FinalData.MAX_EVT_NUM - 1;
// }
//
// EntityGroupEvtData[] arrayObj = Arrays.copyOfRange(entityGroupEvtData,
// i * FinalData.MAX_EVT_NUM, to);
// JSONObject entityMtrans = mEntry.getValue();
// EntityGroupData entityGroupData = handleEvent.translate(arrayObj, (EntityMtrans) JSONObject.toBean(entityMtrans, EntityMtrans.class));
// // 处理分析结果
// handleEvent.show_group_info(entityGroupData, listSagEvent, listEventAssObj, date);
// }
// }
// }
// }
//
//
// DictData dictData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.EVENT_REASON.getName(), DicDataEnum.SHORT_TROUBLE.getName()).getData();
// if (Objects.isNull(dictData)) {
// throw new BusinessException(SystemResponseEnum.ADVANCE_REASON);
// }
//
//
// LocalDateTime date = LocalDateTime.now();
// HandleEvent handleEvent = new HandleEvent();
// // 分析的事件进行处理
// List<EntityGroupEvtData> baseList = handleEvent.getData(startTime, endTime);
// if (CollectionUtil.isEmpty(baseList)) {
// throw new BusinessException("当前时间段暂无可分析事件");
// }
//
// // 传入的处理事件根据物理隔绝进行分组
//
// List<EntityLogic> strategyList = relevantLogMapper.getLogic();
//
// if (CollectionUtil.isNotEmpty(strategyList)) {
// List<SagEvent> listSagEvent = new ArrayList<>();
// List<EventAssObj> listEventAssObj = new ArrayList<>();
//
// Map<String, List<String>> strategyToBusBarMap = new HashMap<>(32);
//
// Map<String, EntityMtrans> mapRedis = new HashMap<>(32);
//
// Map<String, List<EntityLogic>> strategyMap = strategyList.stream().collect(Collectors.groupingBy(EntityLogic::getTPIndex));
// strategyMap.forEach((key, list) -> {
// List<String> before = list.stream().map(EntityLogic::getNodeBefore).distinct().collect(Collectors.toList());
// List<String> after = list.stream().map(EntityLogic::getNodeNext).distinct().collect(Collectors.toList());
// before.addAll(after);
// before = before.stream().distinct().collect(Collectors.toList());
// strategyToBusBarMap.put(key, before);
//
// FinalData.NODE_NUM = before.size();
// EntityMtrans entityMtrans = new EntityMtrans();
// handleEvent.create_matrixcata(list, entityMtrans);
//
// mapRedis.put(key, entityMtrans);
// });
//
// strategyToBusBarMap.forEach((lastKey, lastVal) -> {
// int index = 1;
// List<EntityGroupEvtData> list = new ArrayList<>();
// for (EntityGroupEvtData entityGroupEvtData : baseList) {
// if (lastVal.contains(entityGroupEvtData.getNodePhysics()) && dictData.getId().equals(entityGroupEvtData.getSagReason())) {
// entityGroupEvtData.setNode(index++);
// list.add(entityGroupEvtData);
// }
// }
//
// baseList.removeIf(entityGroupEvtData -> lastVal.contains(entityGroupEvtData.getNodePhysics()) && dictData.getId().equals(entityGroupEvtData.getSagReason()));
//
//
// EntityGroupEvtData[] entityGroupEvtData = new EntityGroupEvtData[list.size()];
// Collections.sort(list);
// list.toArray(entityGroupEvtData);
//
// mapRedis.forEach((mKey, mVal) -> {
// if (mKey.equals(lastKey)) {
// //算法最多处理1000条数据超过限制需分批处理 先将数据根据某种方式进行升序/降序排序,然后分段处理 加入循环处理
// int circulation = entityGroupEvtData.length % FinalData.MAX_EVT_NUM == 0
// ? entityGroupEvtData.length / FinalData.MAX_EVT_NUM
// : entityGroupEvtData.length / FinalData.MAX_EVT_NUM + 1;
//
// for (int i = 0; i < circulation; i++) {
// int to;
// if (i == circulation - 1) {
// to = entityGroupEvtData.length % FinalData.MAX_EVT_NUM > 0
// ? entityGroupEvtData.length
// : (i + 1) * FinalData.MAX_EVT_NUM - 1;
// } else {
// to = (i + 1) * FinalData.MAX_EVT_NUM - 1;
// }
//
// EntityGroupEvtData[] arrayObj = Arrays.copyOfRange(entityGroupEvtData,
// i * FinalData.MAX_EVT_NUM, to);
// EntityGroupData entityGroupData = handleEvent.translate(arrayObj, mVal);
// // 处理分析结果
// handleEvent.show_group_info(entityGroupData, listSagEvent, listEventAssObj, date);
// }
// }
// });
//
// });
//
//
//
// //事件ID不在矩阵中结果集为基础以时标为标准进行归集处理 注意:三相与(单相/两相)互斥
//
// disposeNonStandardData(handleEvent, baseList, listEventAssObj, listSagEvent, date);
//
//
// int listSize = listEventAssObj.size();
// int toIndex = 1000;
// for (int i = 0; i < listSize; i += 1000) {
// //作用为toIndex最后没有toIndex条数据则剩余几条newList中就装几条
// if (i + 1000 > listSize) {
// toIndex = listSize - i;
// }
// //分割lst
// List<EventAssObj> newList = listEventAssObj.subList(i, i + toIndex);
// //写入添加方法,需要写你的新增方法把newList分切后的数据新增进入数据库。
// rmpEventDetailAssMapper.insertEventAssData(newList);
// }
//
// List<RmpEventDetailPO> eventUpdateList = new ArrayList<>();
// for (int i = 0; i < listSagEvent.size(); i++) {
// RmpEventDetailPO rmp = new RmpEventDetailPO();
// rmp.setEventId(listSagEvent.get(i).getIndexEventDetail());
// rmp.setEventassIndex(listSagEvent.get(i).getIndexEventAss());
// rmp.setDealTime(listSagEvent.get(i).getDealTime());
// eventUpdateList.add(rmp);
// if ((i + 1) % 1000 == 0) {
// this.updateBatchById(eventUpdateList);
// eventUpdateList.clear();
// } else if (i == listSagEvent.size() - 1) {
// this.updateBatchById(eventUpdateList);
// }
// }
//
// // 增加策略记录
// String describe = "用户" + RequestUtil.getUserNickname() + "进行了关联分析";
// PqsRelevanceLog entityPqsRelevance = new PqsRelevanceLog();
// entityPqsRelevance.setContentDes(describe);
// entityPqsRelevance.setState(DataStateEnum.ENABLE.getCode());
// entityPqsRelevance.setTimeId(date);
// relevantLogMapper.insert(entityPqsRelevance);
//
// } else {
// throw new BusinessException("当前无变压器策略,请先配置策略");
// }
//
// log.info("事件关联分析用时:" + timeInterval.interval() / 1000 + "秒");
// }
@Override @Override
public Page<AdvanceEventDetailVO> querySagEventsPage(BaseParam baseParam) { public Page<AdvanceEventDetailVO> querySagEventsPage(BaseParam baseParam) {
List<String> lineIds = generalDeviceInfoClient.deptGetRunLineEvent(RequestUtil.getDeptIndex()).getData(); List<String> lineIds = generalDeviceInfoClient.deptGetRunLineEvent(RequestUtil.getDeptIndex()).getData();
@@ -493,6 +268,7 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
} }
/** /**
* 四舍五入保留两位小数 * 四舍五入保留两位小数
*/ */
@@ -504,6 +280,7 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
//保留2位小数 //保留2位小数
return com.njcn.harmonic.utils.PubUtils.dataLimits(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); return com.njcn.harmonic.utils.PubUtils.dataLimits(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
} }
@Override @Override
public Page<RmpEventDetailAssPO> queryEventsAssPage(BaseParam baseParam) { public Page<RmpEventDetailAssPO> queryEventsAssPage(BaseParam baseParam) {
List<LocalDateTime> timeV = PubUtils.checkLocalDate(baseParam.getSearchBeginTime(), baseParam.getSearchEndTime()); List<LocalDateTime> timeV = PubUtils.checkLocalDate(baseParam.getSearchBeginTime(), baseParam.getSearchEndTime());
@@ -620,6 +397,7 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
.in(RmpEventDetailPO::getEventId, eventId); .in(RmpEventDetailPO::getEventId, eventId);
RmpEventDetailPO rmpEventDetailPO = new RmpEventDetailPO(); RmpEventDetailPO rmpEventDetailPO = new RmpEventDetailPO();
rmpEventDetailPO.setEventassIndex(assId); rmpEventDetailPO.setEventassIndex(assId);
rmpEventDetailPO.setDealTime(LocalDateTime.now());
eventAdvanceMapper.update(rmpEventDetailPO, lambdaUpdateWrapper); eventAdvanceMapper.update(rmpEventDetailPO, lambdaUpdateWrapper);
return true; return true;
} }

View File

@@ -81,6 +81,8 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
//获取所有暂态原因 //获取所有暂态原因
List<DictData> dicDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()).getData(); List<DictData> dicDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()).getData();
Map<Integer, DictData> eventTypeMap = dicDataList.stream().collect(Collectors.toMap(DictData::getAlgoDescribe, Function.identity())); Map<Integer, DictData> eventTypeMap = dicDataList.stream().collect(Collectors.toMap(DictData::getAlgoDescribe, Function.identity()));
List<DictData> reasonList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_REASON.getCode()).getData();
Map<Integer, DictData> eventReasonMap = reasonList.stream().collect(Collectors.toMap(DictData::getAlgoDescribe, Function.identity()));
InputStream inputStreamCfg; InputStream inputStreamCfg;
InputStream inputStreamDat; InputStream inputStreamDat;
try { try {
@@ -176,11 +178,11 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
causeStruct.smp_len = pitchList.size(); causeStruct.smp_len = pitchList.size();
causeStruct.smp_rate = (int) wavePitchData.getnOneWaveNum(); causeStruct.smp_rate = (int) wavePitchData.getnOneWaveNum();
String hdrStr = waveUtils.getFile(OssPath.WAVE_DIR + lineDetailDataVO.getIp() + StrUtil.SLASH + rmpEventDetailPO.getWavePath() + GeneralConstant.HDR); String hdrStr = waveUtils.getFile(OssPath.WAVE_DIR + lineDetailDataVO.getIp() + StrUtil.SLASH + rmpEventDetailPO.getWavePath() + GeneralConstant.HDR_LOWER);
JSONObject jsonObject = JSONObject.fromObject(hdrStr); JSONObject jsonObject = JSONObject.fromObject(hdrStr);
translateData(jsonObject, rmpEventDetailPO.getStartTime(), entityAdvancedData); translateData(jsonObject, rmpEventDetailPO.getStartTime(), entityAdvancedData);
if (rmpEventDetailPO.getDealFlag() != 1) { if (!Objects.equals(rmpEventDetailPO.getDealFlag(),1) ) {
//如果存在三个文件但是没有调用dll/so计算 //如果存在三个文件但是没有调用dll/so计算
getDataFromDLL(rmpEventDetailPO, waveOriginalData, rect, entityAdvancedData, causeStruct); getDataFromDLL(rmpEventDetailPO, waveOriginalData, rect, entityAdvancedData, causeStruct);
} }
@@ -192,7 +194,7 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
if (entityAdvancedData.backNumber > 0) { if (entityAdvancedData.backNumber > 0) {
for (int i = 0; i < entityAdvancedData.backNumber; i++) { for (int i = 0; i < entityAdvancedData.backNumber; i++) {
entityAdvancedData.sagType[i] = eventTypeMap.get(entityAdvancedData.evt_buf[i].qvvr_cata_type[0]).getName(); entityAdvancedData.sagType[i] = eventTypeMap.get(entityAdvancedData.evt_buf[i].qvvr_cata_type[0]).getName();
entityAdvancedData.sagReason[i]= eventReasonMap.get(entityAdvancedData.evt_buf[i].qvvr_cata_cause[0]).getName();
switch (entityAdvancedData.evt_buf[i].qvvr_phasetype[0]) { switch (entityAdvancedData.evt_buf[i].qvvr_phasetype[0]) {
case 1: case 1:
entityAdvancedData.sagPhaseType[i] = "单相"; entityAdvancedData.sagPhaseType[i] = "单相";
@@ -223,6 +225,10 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
RmpEventDetailPO rmpEventDetailPO = rmpEventAdvanceMapper.selectById(eventIndex); RmpEventDetailPO rmpEventDetailPO = rmpEventAdvanceMapper.selectById(eventIndex);
EntityAdvancedData entityAdvancedData; EntityAdvancedData entityAdvancedData;
if (Objects.isNull(rmpEventDetailPO.getFileFlag())) {
throw new BusinessException("系统检测到波形文件未从装置招到本地,请联系管理员");
}
if (rmpEventDetailPO.getFileFlag() == 1) { if (rmpEventDetailPO.getFileFlag() == 1) {
//获取所有暂态原因 //获取所有暂态原因
List<DictData> dicDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()).getData(); List<DictData> dicDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()).getData();
@@ -624,7 +630,7 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
entityAdvancedData.backNumber = len; entityAdvancedData.backNumber = len;
//初始化EntityAdvancedData的BackData数据 //初始化EntityAdvancedData的BackData数据
len = (len == 0 ? 1 : len); // len = (len == 0 ? 1 : len);
entityAdvancedData.evt_buf = new BackData[len]; entityAdvancedData.evt_buf = new BackData[len];
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
entityAdvancedData.evt_buf[i] = new BackData(); entityAdvancedData.evt_buf[i] = new BackData();

View File

@@ -1,11 +1,11 @@
package com.njcn.advance.utils; package com.njcn.advance.utils;
import cn.hutool.core.io.resource.ClassPathResource;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import java.io.*; import java.io.File;
import java.net.URLDecoder; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
/** /**
* pqs * pqs
@@ -20,21 +20,20 @@ public class JnaCallDllOrSo {
public JnaCallDllOrSo(String name) { public JnaCallDllOrSo(String name) {
super(); super();
String suffix = ".dll";
try { try {
String os = System.getProperty("os.name"); String os = System.getProperty("os.name");
// windows操作系统为1 否则为0
int beginIndex = os != null && os.startsWith("Windows") ? 1 : 0; int beginIndex = os != null && os.startsWith("Windows") ? 1 : 0;
String nameDll; String nameDll;
if (beginIndex == 0) { if (beginIndex == 0) {
//linux操作系统 nameDll = "lib" + name + ".so";
nameDll = "lib" + name + "_dll";
suffix = ".so";
} else { } else {
nameDll = name; nameDll = name;
if (!name.endsWith(".dll")) {
nameDll = name + ".dll";
}
} }
String tem = "/usr/local/dllFile/"+ nameDll.concat(suffix); String tem = "/usr/local/dllFile/"+ nameDll;
File dockerFile = new File(tem); File dockerFile = new File(tem);
if(!dockerFile.exists()){ if(!dockerFile.exists()){
boolean f = dockerFile.getParentFile().mkdirs(); boolean f = dockerFile.getParentFile().mkdirs();
@@ -42,7 +41,11 @@ public class JnaCallDllOrSo {
System.out.println("文件夹创建:"+f); System.out.println("文件夹创建:"+f);
System.out.println("文件创建:"+d); System.out.println("文件创建:"+d);
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(nameDll.concat(suffix))) { try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(nameDll)) {
if (inputStream == null) {
log.error("找不到资源文件: {}", nameDll);
throw new FileNotFoundException("找不到资源文件: " + nameDll);
}
try (FileOutputStream outputStream = new FileOutputStream(dockerFile)) { try (FileOutputStream outputStream = new FileOutputStream(dockerFile)) {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int bytesRead; int bytesRead;
@@ -53,9 +56,11 @@ public class JnaCallDllOrSo {
} }
} }
this.path = dockerFile.getAbsolutePath(); this.path = dockerFile.getAbsolutePath();
System.out.println("动态库路径: " + this.path);
} catch (Exception e) { } catch (Exception e) {
log.error("调用高级算法文件异常,异常信息如下:"); log.error("调用高级算法文件异常,异常信息如下:");
log.error(e.getMessage()); log.error(e.getMessage(), e);
throw new RuntimeException("加载动态库失败: " + e.getMessage(), e);
} }

View File

@@ -1,3 +1,3 @@
spring: spring:
profiles: profiles:
active: sjzx active: @spring.profiles.active@

View File

@@ -66,6 +66,13 @@
<artifactId>common-oss</artifactId> <artifactId>common-oss</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<!--辽宁调度现场单点登录-->
<dependency>
<groupId>com.sgcc.epri.auth</groupId>
<artifactId>sso-client-base</artifactId>
<version>2.1.1 </version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@@ -0,0 +1,26 @@
package com.njcn.auth.config;
/**
* pqs
*
* @author cdf
* @date 2026/6/8
*/
import com.sgcc.epri.auth.config.EnableSSOClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
/**
* 仅控制 SSO 客户端开关,不影响任何其他功能
*/
@Configuration
@ConditionalOnProperty(
prefix = "cas.client", // 配置前缀
name = "enabled", // 配置项名称
havingValue = "true", // 值为true才生效
matchIfMissing = false // 不配置默认关闭
)
@EnableSSOClient
public class LnSsoClientConfig {
}

View File

@@ -37,7 +37,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .authorizeRequests()
.antMatchers("/oauth/getPublicKey","/oauth/logout","/auth/getImgCode","/judgeToken/guangZhou","/judgeToken/heBei","/oauth/autoLogin").permitAll() .antMatchers("/oauth/getPublicKey","/oauth/logout","/auth/getImgCode","/judgeToken/guangZhou","/judgeToken/heBei","/oauth/autoLogin","/oauth/lnLogin","/oauth/lnCheck","/oauth/lnRefreshToken").permitAll()
// @link https://gitee.com/xiaoym/knife4j/issues/I1Q5X6 (接口文档knife4j需要放行的规则) // @link https://gitee.com/xiaoym/knife4j/issues/I1Q5X6 (接口文档knife4j需要放行的规则)
.antMatchers("/webjars/**","/doc.html","/swagger-resources/**","/v2/api-docs").permitAll() .antMatchers("/webjars/**","/doc.html","/swagger-resources/**","/v2/api-docs").permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()

View File

@@ -25,13 +25,17 @@ import com.njcn.user.pojo.po.UserStrategy;
import com.njcn.web.controller.BaseController; import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.RequestUtil; import com.njcn.web.utils.RequestUtil;
import com.njcn.web.utils.RestTemplateUtil; import com.njcn.web.utils.RestTemplateUtil;
import com.sgcc.epri.auth.session.HttpSessionManager;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint; import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException;
@@ -39,6 +43,10 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.security.KeyPair; import java.security.KeyPair;
import java.security.Principal; import java.security.Principal;
@@ -55,7 +63,7 @@ import java.util.stream.Collectors;
@Slf4j @Slf4j
@RestController @RestController
@RequestMapping("/oauth") @RequestMapping("/oauth")
@AllArgsConstructor @RequiredArgsConstructor
public class AuthController extends BaseController { public class AuthController extends BaseController {
@@ -71,6 +79,11 @@ public class AuthController extends BaseController {
private final UserTokenService userTokenService; private final UserTokenService userTokenService;
@Value("${cas.redirect-url:http://10.21.30.11:8088/#/login?flag=1}")
private String redirectUrl;
private String UsernamePrefix = "CAS_";
@ApiIgnore @ApiIgnore
@OperateInfo(info = LogEnum.SYSTEM_SERIOUS, operateType = OperateType.AUTHENTICATE) @OperateInfo(info = LogEnum.SYSTEM_SERIOUS, operateType = OperateType.AUTHENTICATE)
@@ -91,7 +104,6 @@ public class AuthController extends BaseController {
String methodDescribe = getMethodDescribe("postAccessToken"); String methodDescribe = getMethodDescribe("postAccessToken");
String username = parameters.get(SecurityConstants.USERNAME); String username = parameters.get(SecurityConstants.USERNAME);
String grantType = parameters.get(SecurityConstants.GRANT_TYPE); String grantType = parameters.get(SecurityConstants.GRANT_TYPE);
if (grantType.equalsIgnoreCase(SecurityConstants.GRANT_CAPTCHA) || grantType.equalsIgnoreCase(SecurityConstants.REFRESH_TOKEN_KEY)) { if (grantType.equalsIgnoreCase(SecurityConstants.GRANT_CAPTCHA) || grantType.equalsIgnoreCase(SecurityConstants.REFRESH_TOKEN_KEY)) {
username = DesUtils.aesDecrypt(username); username = DesUtils.aesDecrypt(username);
@@ -143,7 +155,7 @@ public class AuthController extends BaseController {
@OperateInfo(info = LogEnum.SYSTEM_SERIOUS, operateType = OperateType.LOGOUT) @OperateInfo(info = LogEnum.SYSTEM_SERIOUS, operateType = OperateType.LOGOUT)
@ApiOperation("用户登出系统") @ApiOperation("用户登出系统")
@DeleteMapping("/logout") @DeleteMapping("/logout")
public HttpResult<Object> logout() { public HttpResult<Object> logout(HttpServletRequest request, HttpServletResponse response) {
String methodDescribe = getMethodDescribe("logout"); String methodDescribe = getMethodDescribe("logout");
String userIndex = RequestUtil.getUserIndex(); String userIndex = RequestUtil.getUserIndex();
String username = RequestUtil.getUsername(); String username = RequestUtil.getUsername();
@@ -165,6 +177,24 @@ public class AuthController extends BaseController {
long lifeTime = Math.abs(refreshTokenExpire.plusMinutes(5L).toEpochSecond(ZoneOffset.of("+8")) - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))); long lifeTime = Math.abs(refreshTokenExpire.plusMinutes(5L).toEpochSecond(ZoneOffset.of("+8")) - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
redisUtil.saveByKeyWithExpire(blackUserKey, blackUsers, lifeTime); redisUtil.saveByKeyWithExpire(blackUserKey, blackUsers, lifeTime);
} }
// 以下代码是辽宁登出代码,关键:使 Session 失效
request.getSession().invalidate();
// 清除 JSESSIONID
Cookie jsessionidCookie = new Cookie("JSESSIONID", null);
jsessionidCookie.setMaxAge(0);
jsessionidCookie.setPath("/");
response.addCookie(jsessionidCookie);
// 清除 loginUser Cookie关键
Cookie loginUserCookie = new Cookie("loginUser", null);
loginUserCookie.setMaxAge(0);
loginUserCookie.setPath("/");
response.addCookie(loginUserCookie);
log.info("登出成功。。。。。。。。。。。。。。。。");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
} }
@@ -191,7 +221,7 @@ public class AuthController extends BaseController {
@ApiIgnore @ApiIgnore
public HttpResult<Object> autoLogin(@RequestParam String phone) { public HttpResult<Object> autoLogin(@RequestParam String phone) {
String methodDescribe = getMethodDescribe("autoLogin"); String methodDescribe = getMethodDescribe("autoLogin");
String userUrl = "http://127.0.0.1:10214/oauth/token"; String userUrl = "http://127.0.0.1:20214/oauth/token";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(userUrl) UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(userUrl)
.queryParam("grant_type", "sms_code") .queryParam("grant_type", "sms_code")
.queryParam("client_id", "njcnapp") .queryParam("client_id", "njcnapp")
@@ -202,4 +232,134 @@ public class AuthController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, Objects.requireNonNull(RestTemplateUtil.post(uri, HttpResult.class).getBody()).getData(), methodDescribe); return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, Objects.requireNonNull(RestTemplateUtil.post(uri, HttpResult.class).getBody()).getData(), methodDescribe);
} }
/**
* 【电科院CAS调控云单点登录适配】
* 这个只用来匹配
*/
@ApiIgnore
@GetMapping("/lnLogin")
@ApiOperation("获取ln系统用户token")
public HttpResult<Object> lnLogin(@RequestParam String clientId, @RequestParam String clientSecret, HttpServletRequest request, HttpServletResponse response) throws HttpRequestMethodNotSupportedException {
log.info("进入lnLogin++++++++++++++++++");
String methodDescribe = getMethodDescribe("lnLogin");
// 读取CAS信息
String userName = String.valueOf(HttpSessionManager.getAttribute(request, HttpSessionManager.AUTH_USER_KEY));
String userId = String.valueOf(HttpSessionManager.getAttribute(request, HttpSessionManager.USER_ID_KEY));
String owner = String.valueOf(HttpSessionManager.getAttribute(request, HttpSessionManager.USER_OWNER));
String name = String.valueOf(HttpSessionManager.getAttribute(request, HttpSessionManager.USER_NAME_CHN));
String employeeId = String.valueOf(HttpSessionManager.getAttribute(request, HttpSessionManager.USER_EMPLOYEE_ID));
log.info("userName:{}", userName);
log.info("userId:{}", userId);
log.info("owner:{}", owner);
log.info("name:{}", name);
log.info("employeeId:{}", employeeId);
if ("null".equals(userName)) {
throw new BusinessException(UserResponseEnum.LN_AUTH_ERROR);
}
// 2. 【关键】用户名前面加上"CAS_"前缀让UserDetailsService识别
String casUsername = userName;
// 2. 直接构造 OAuth2 必要参数(跳过所有密码/加密校验)
Map<String, String> parameters = new HashMap<>();
parameters.put("grant_type", "password"); // 固定密码模式
parameters.put("client_id", clientId); // 你的客户端ID
parameters.put("client_secret", clientSecret); // 你的客户端秘钥
parameters.put("username", userName); // 统一认证传过来的用户名
parameters.put("password", "@#001njcnpqs");
// 3. 直接调用 OAuth2 生成 Token跳过所有登录校验
Authentication authentication = new UsernamePasswordAuthenticationToken(
clientId, clientSecret, Collections.emptyList()
);
OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(authentication, parameters).getBody();
// 获取过期时间(秒数)
int expiresIn = oAuth2AccessToken.getExpiresIn();
log.info("token过期时间: {} 秒", expiresIn);
log.info("token过期时间: {} 分钟", expiresIn / 60);
log.info("token过期时间: {} 小时", expiresIn / 3600);
log.info("====== 免密登录成功返回token给前端 ======");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, oAuth2AccessToken, methodDescribe);
}
/**
* 重点:
* 这个接口 不加 白名单
* 访问它 → 自动跳CAS → 登录成功 → 重定向到登录页
*/
@GetMapping("/lnCheck")
@ApiOperation("检查CAS是否登录")
public void lnToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.info("进入lnCheck。。。。");
response.sendRedirect(redirectUrl);
}
/**
*/
@GetMapping("/lnRefreshToken")
@ApiOperation("刷新token")
public HttpResult<Object> lnRefreshToken(
@RequestParam String refreshToken,
@RequestParam String clientId,
@RequestParam String clientSecret,
HttpServletRequest request,
HttpServletResponse response) throws HttpRequestMethodNotSupportedException {
log.info("进入lnRefreshToken开始刷新token");
String methodDescribe = getMethodDescribe("lnRefreshToken");
// ========== 【前置优先校验CAS会话是否过期】 ==========
String userName = String.valueOf(HttpSessionManager.getAttribute(request, HttpSessionManager.AUTH_USER_KEY));
if ("null".equals(userName)) {
log.error("CAS会话已过期跳转登录页");
throw new BusinessException(UserResponseEnum.LN_AUTH_ERROR);
}
// 1. 先尝试用refresh_token正常刷新
Map<String, String> parameters = new HashMap<>();
parameters.put("grant_type", "refresh_token");
parameters.put("refresh_token", refreshToken);
parameters.put("client_id", clientId);
parameters.put("client_secret", clientSecret);
Authentication authentication = new UsernamePasswordAuthenticationToken(
clientId, clientSecret, Collections.emptyList()
);
try {
OAuth2AccessToken newAccessToken = tokenEndpoint.postAccessToken(authentication, parameters).getBody();
log.info("refresh_token刷新成功");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, newAccessToken, methodDescribe);
} catch (Exception e) {
log.warn("refresh_token刷新失败尝试回退到CAS会话重新签发token", e);
}
// 3. CAS会话有效重新签发token等同于重新登录
log.info("CAS会话有效为用户[{}]重新签发token", userName);
String casUsername = userName;
Map<String, String> reLoginParams = new HashMap<>();
reLoginParams.put("grant_type", "password");
reLoginParams.put("client_id", clientId);
reLoginParams.put("client_secret", clientSecret);
reLoginParams.put("username", userName);
reLoginParams.put("password", "@#001njcnpqs");
Authentication reAuth = new UsernamePasswordAuthenticationToken(
clientId, clientSecret, Collections.emptyList()
);
OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(reAuth, reLoginParams).getBody();
log.info("CAS回退重签token成功userName:{}", userName);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, oAuth2AccessToken, methodDescribe);
}
} }

View File

@@ -55,3 +55,22 @@ mybatis-plus:
mqtt: mqtt:
client-id: @artifactId@${random.value} client-id: @artifactId@${random.value}
cas:
client:
# true 开启 false 关闭
enabled: false
redirect-url: http://PQMonitoring.dcloud.ln.dc.sgcc.com.cn/#/login?flag=1
server-url-prefix: http://privilege-epri.dcloud.ln.dc.sgcc.com.cn/cas
server-login-url: http://privilege-epri.dcloud.ln.dc.sgcc.com.cn/cas/login
client-host-url: http://PQMonitoring.dcloud.ln.dc.sgcc.com.cn:80
validation-type: CAS
#白名单设置
# /oauth/lnLogin$|/pqs-auth/oauth/lnLogin|/oauth/lnRefreshToken$|/pqs-auth/oauth/lnRefreshToken
sso:
whiteList: .*/oauth/lnLogin.*|.*/pqs-auth/oauth/lnLogin.*|.*/oauth/lnRefreshToken.*|.*/pqs-auth/oauth/lnRefreshToken.*

View File

@@ -21,7 +21,7 @@ public class GenerateCode {
private static final String TARGET_DIR = "D://code"; private static final String TARGET_DIR = "D://code";
private static final String DB_URL = "jdbc:mysql://192.168.1.24:13306/pqsinfo_ln"; private static final String DB_URL = "jdbc:mysql://192.168.1.103:13306/pqsinfo_zl";
// private static final String DB_URL = "jdbc:oracle:thin:@192.168.1.170:1521:pqsbase"; // private static final String DB_URL = "jdbc:oracle:thin:@192.168.1.170:1521:pqsbase";
private static final String USERNAME = "root"; private static final String USERNAME = "root";
@@ -30,8 +30,8 @@ public class GenerateCode {
public static void main(String[] args) { public static void main(String[] args) {
List<Module> modules = Stream.of( List<Module> modules = Stream.of(
new Module("cdf", "com.njcn.device", "", Stream.of( new Module("xy", "com.njcn.csdevice", "", Stream.of(
"pq_icd_path" "cs_alarm_set"
).collect(Collectors.toList()), "") ).collect(Collectors.toList()), "")
).collect(Collectors.toList()); ).collect(Collectors.toList());
generateJavaFile(modules); generateJavaFile(modules);

View File

@@ -97,11 +97,11 @@
<groupId>com.fasterxml.jackson.datatype</groupId> <groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId> <artifactId>jackson-datatype-jsr310</artifactId>
</dependency> </dependency>
<!--mqtt相关依赖--> <!-- &lt;!&ndash;mqtt相关依赖&ndash;&gt;-->
<dependency> <!-- <dependency>-->
<groupId>com.github.tocrhz</groupId> <!-- <groupId>com.github.tocrhz</groupId>-->
<artifactId>mqtt-spring-boot-starter</artifactId> <!-- <artifactId>mqtt-spring-boot-starter</artifactId>-->
</dependency> <!-- </dependency>-->
<!-- <dependency>--> <!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>--> <!-- <groupId>org.springframework.boot</groupId>-->

View File

@@ -15,6 +15,7 @@ import com.njcn.common.pojo.exception.BusinessException;
import lombok.Data; import lombok.Data;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.math.BigDecimal; import java.math.BigDecimal;
@@ -32,6 +33,7 @@ import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.lang.Integer.parseInt; import static java.lang.Integer.parseInt;
@@ -281,6 +283,30 @@ public class PubUtils {
} }
} }
/**
* 用于获取对象中前缀一样后缀为2~50的属性值
*
* @param methodPrefix 方法前缀
* @param number 方法后缀
* @return 对象属性值
*/
public static Double getValueByMethodDouble(List data ,Class clazz, String methodPrefix, Integer number) {
try {
Method method = clazz.getMethod(methodPrefix + number);
OptionalDouble average = data.stream().mapToDouble(temp -> {
try {
return (Double) method.invoke(temp);
} catch (Exception e) {
throw new BusinessException(CommonResponseEnum.REFLECT_METHOD_EXCEPTION);
}
}).average();
return average.orElse(0.0);
} catch (Exception e) {
throw new BusinessException(CommonResponseEnum.REFLECT_METHOD_EXCEPTION);
}
}
public static List<String> getStartTimeEndTime(String beginDate, String endDate) throws Exception { public static List<String> getStartTimeEndTime(String beginDate, String endDate) throws Exception {

View File

@@ -1,11 +1,7 @@
package com.njcn.echarts.json; package com.njcn.echarts.json;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import cn.hutool.json.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.njcn.echarts.pojo.bo.TolerateData; import com.njcn.echarts.pojo.bo.TolerateData;
import com.njcn.echarts.pojo.constant.PicCommonData; import com.njcn.echarts.pojo.constant.PicCommonData;
import org.icepear.echarts.Option; import org.icepear.echarts.Option;
@@ -29,7 +25,6 @@ import org.icepear.echarts.render.Engine;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -43,6 +38,17 @@ import java.util.stream.Collectors;
public class LineGenerator { public class LineGenerator {
private final static Engine ENGINE = new Engine(); private final static Engine ENGINE = new Engine();
// null段在图表上的固定视觉宽度数据点数量
private static final int NULL_PLACEHOLDER_COUNT = 90;
// 压缩结果
private static class CompressedResult {
// 压缩后的数据
List<List<Float>> data;
// 每个null段的[起始索引, 结束索引](占位点范围)
List<int[]> nullRegionIndices;
// null段边界处的真实x值entry, exit交替
List<Float> nullBoundaryRealXValues;
}
/*** /***
@@ -529,6 +535,478 @@ public class LineGenerator {
return ENGINE.renderJsonOption(instantOption); return ENGINE.renderJsonOption(instantOption);
} }
public static String generateWaveOption(String title, List<List<Float>> aValue, List<List<Float>> bValue, List<List<Float>> cValue, String unit, Float max, Float min, String a, String b, String c, List<String> colors, Boolean isOpen, Double lastTime, List<Float> sharedNullBoundaryXValues, Integer nPush) {
DecimalFormat df1 = new DecimalFormat("#.00");
// 压缩null数据如果有共享边界则用共享边界否则独立压缩
CompressedResult aCompressed;
CompressedResult bCompressed;
CompressedResult cCompressed;
if (sharedNullBoundaryXValues != null && !sharedNullBoundaryXValues.isEmpty()) {
aCompressed = compressNullDataWithSharedBoundaries(aValue, sharedNullBoundaryXValues);
bCompressed = compressNullDataWithSharedBoundaries(bValue, sharedNullBoundaryXValues);
cCompressed = compressNullDataWithSharedBoundaries(cValue, sharedNullBoundaryXValues);
} else {
aCompressed = compressNullData(aValue);
bCompressed = compressNullData(bValue);
cCompressed = compressNullData(cValue);
}
Option instantOption = new Option();
//取消渲染动画
instantOption.setAnimation(false);
//背景色
instantOption.setBackgroundColor(PicCommonData.PIC_BACK_COLOR);
//标题
instantOption.setTitle(new Title()
.setText(title)
.setLeft(PicCommonData.CENTER)
.setTextStyle(new Label().setFontSize(14))
);
//配置颜色
instantOption.setColor(colors.toArray(new String[colors.size()]));
//配置图例
if (isOpen) {
instantOption.setLegend(new Legend().setData(new String[]{a, b}).setLeft("10px"));
} else {
instantOption.setLegend(new Legend().setData(new String[]{a, b, c}).setLeft("10px"));
}
//上下左右的图内间距
instantOption.setGrid(new Grid().setTop("60px").setLeft("70px").setRight("40px").setBottom("10%"));
//横坐标(使用压缩后的数据)
instantOption.setXAxis(new ValueAxis().setName("ms")
.setSplitLine(new SplitLine().setShow(false))
.setAxisLine(new AxisLine().setOnZero(false))
.setType("category")
.setMinInterval(1)
);
//纵坐标
instantOption.setYAxis(new ValueAxis()
.setName(unit)
.setMax(df1.format(max * 1.1))
.setMin(df1.format(min * 1.1))
.setPosition(PicCommonData.LEFT)
.setAxisLine(new AxisLine().setShow(false).setOnZero(false))
);
//数据信息(使用压缩后的数据)
LineSeries aSeries = new LineSeries()
.setName(a)
.setSmooth(true)
.setSymbol("none")
.setConnectNulls(false)
.setData(aCompressed.data);
LineSeries bSeries = new LineSeries()
.setName(b)
.setSmooth(true)
.setSymbol("none")
.setConnectNulls(false)
.setData(bCompressed.data);
LineSeries cSeries = new LineSeries()
.setName(c)
.setSmooth(true)
.setSymbol("none")
.setConnectNulls(false)
.setData(cCompressed.data);
instantOption.setSeries(new LineSeries[]{aSeries, bSeries, cSeries});
// 渲染基础JSON
String jsonStr = ENGINE.renderJsonOption(instantOption);
cn.hutool.json.JSONObject optionJson = JSONUtil.parseObj(jsonStr);
cn.hutool.json.JSONArray seriesArray = optionJson.getJSONArray("series");
// 隐藏x轴默认标签设置boundaryGap=false只通过markLine显示关键节点
Object xAxisRaw = optionJson.get("xAxis");
cn.hutool.json.JSONObject xAxisJson;
if (xAxisRaw instanceof cn.hutool.json.JSONArray) {
xAxisJson = ((cn.hutool.json.JSONArray) xAxisRaw).getJSONObject(0);
} else {
xAxisJson = (cn.hutool.json.JSONObject) xAxisRaw;
}
cn.hutool.json.JSONObject axisLabelJson = new cn.hutool.json.JSONObject();
axisLabelJson.set("show", false);
xAxisJson.set("axisLabel", axisLabelJson);
xAxisJson.set("boundaryGap", false);
// 添加null markLine/markArea基于压缩后的数据
addNullMarkLinesForCategoryAxis(seriesArray.getJSONObject(0), aCompressed, lastTime);
addNullMarkLinesForCategoryAxis(seriesArray.getJSONObject(1), bCompressed, lastTime);
addNullMarkLinesForCategoryAxis(seriesArray.getJSONObject(2), cCompressed, lastTime);
// 在第一个series追加自定义横坐标标签markLine
addAxisLabelMarkLines(seriesArray.getJSONObject(0), aCompressed, lastTime, nPush);
return optionJson.toString();
}
/** 提取null边界的真实x值供其他数据集共享使用 */
public static List<Float> extractNullBoundaryXValues(List<List<Float>> data) {
List<Integer> boundaries = findNullSegmentBoundaryIndices(data);
List<Float> xValues = new ArrayList<>();
for (int idx : boundaries) {
xValues.add(data.get(idx).get(0));
}
return xValues;
}
/** 使用共享的null边界x值来压缩数据确保不同数据集压缩结果结构一致 */
private static CompressedResult compressNullDataWithSharedBoundaries(List<List<Float>> originalData, List<Float> sharedBoundaryXValues) {
if (sharedBoundaryXValues == null || sharedBoundaryXValues.isEmpty()) {
return compressNullData(originalData);
}
// 用共享的x值找到本数据集中对应的索引
List<Integer> boundaries = new ArrayList<>();
for (Float x : sharedBoundaryXValues) {
boundaries.add(findClosestValidIndex(originalData, x));
}
CompressedResult result = new CompressedResult();
result.data = new ArrayList<>();
result.nullRegionIndices = new ArrayList<>();
result.nullBoundaryRealXValues = new ArrayList<>(sharedBoundaryXValues);
int srcIdx = 0;
for (int b = 0; b < boundaries.size(); b += 2) {
int entryBoundary = boundaries.get(b);
int exitBoundary = boundaries.get(b + 1);
while (srcIdx <= entryBoundary) {
result.data.add(originalData.get(srcIdx));
srcIdx++;
}
int nullStartIdx = result.data.size();
float entryX = sharedBoundaryXValues.get(b);
float exitX = sharedBoundaryXValues.get(b + 1);
for (int p = 0; p < NULL_PLACEHOLDER_COUNT; p++) {
List<Float> point = new ArrayList<>();
point.add(entryX + (exitX - entryX) * p / NULL_PLACEHOLDER_COUNT);
point.add(null);
result.data.add(point);
}
int nullEndIdx = result.data.size() - 1;
result.nullRegionIndices.add(new int[]{nullStartIdx, nullEndIdx});
srcIdx = exitBoundary;
}
while (srcIdx < originalData.size()) {
result.data.add(originalData.get(srcIdx));
srcIdx++;
}
return result;
}
/**
* 压缩null数据删除所有null数据点替换为固定NULL_PLACEHOLDER_COUNT个占位点
* 这样null段在图表上永远只占固定视觉宽度前后有效数据正常展开
*/
private static CompressedResult compressNullData(List<List<Float>> originalData) {
List<Integer> boundaries = findNullSegmentBoundaryIndices(originalData);
CompressedResult result = new CompressedResult();
result.data = new ArrayList<>();
result.nullRegionIndices = new ArrayList<>();
result.nullBoundaryRealXValues = new ArrayList<>();
if (boundaries.isEmpty()) {
result.data.addAll(originalData);
return result;
}
int srcIdx = 0;
for (int b = 0; b < boundaries.size(); b += 2) {
// 最后一个有效点的索引null段入口边界
int entryBoundary = boundaries.get(b);
// 第一个恢复有效点的索引null段出口边界
int exitBoundary = boundaries.get(b + 1);
// 复制有效数据从srcIdx到entryBoundary
while (srcIdx <= entryBoundary) {
result.data.add(originalData.get(srcIdx));
srcIdx++;
}
// 记录边界真实x值
result.nullBoundaryRealXValues.add(originalData.get(entryBoundary).get(0));
result.nullBoundaryRealXValues.add(originalData.get(exitBoundary).get(0));
// 插入固定数量的null占位点
int nullStartIdx = result.data.size();
float entryX = originalData.get(entryBoundary).get(0);
float exitX = originalData.get(exitBoundary).get(0);
for (int p = 0; p < NULL_PLACEHOLDER_COUNT; p++) {
List<Float> point = new ArrayList<>();
point.add(entryX + (exitX - entryX) * p / NULL_PLACEHOLDER_COUNT);
point.add(null);
result.data.add(point);
}
int nullEndIdx = result.data.size() - 1;
result.nullRegionIndices.add(new int[]{nullStartIdx, nullEndIdx});
// 跳过原始null数据点srcIdx跳到exitBoundary
srcIdx = exitBoundary;
}
// 复制最后一个null段之后的剩余有效数据
while (srcIdx < originalData.size()) {
result.data.add(originalData.get(srcIdx));
srcIdx++;
}
return result;
}
/**
* 在压缩数据中查找最接近目标x值的有效数据点索引跳过null点
*/
private static int findClosestValidIndex(List<List<Float>> data, float targetX) {
int closestIdx = -1;
float minDiff = Float.MAX_VALUE;
for (int i = 0; i < data.size(); i++) {
Float y = data.get(i).get(1);
if (y == null) continue;
float diff = Math.abs(data.get(i).get(0) - targetX);
if (diff < minDiff) {
minDiff = diff;
closestIdx = i;
}
}
return closestIdx;
}
private static void addAxisLabelMarkLines(cn.hutool.json.JSONObject seriesObj, CompressedResult compressed, Double lastTime, Integer nPush) {
boolean hasNull = !compressed.nullRegionIndices.isEmpty();
// 收集需要标注的横坐标位置:[数据索引, 显示的时间值]
List<int[]> labelPositions = new ArrayList<>();
// 开头ms始终显示
labelPositions.add(new int[]{findClosestValidIndex(compressed.data, -nPush), -nPush});
// 0ms始终显示
labelPositions.add(new int[]{findClosestValidIndex(compressed.data, 0f), 0});
// npush ms仅在有null时显示
if (hasNull) {
labelPositions.add(new int[]{findClosestValidIndex(compressed.data, nPush), nPush});
}
// null段边界真实时间值仅在有null时显示
if (hasNull) {
for (Float realX : compressed.nullBoundaryRealXValues) {
int idx = findClosestValidIndex(compressed.data, realX);
if (idx >= 0) {
labelPositions.add(new int[]{idx, (int) Math.round(realX)});
}
}
}
// lastTime始终显示
if (lastTime != null) {
labelPositions.add(new int[]{findClosestValidIndex(compressed.data, lastTime.floatValue()), lastTime.intValue()});
}
// 最后一组数据(始终显示,数据结束位置横坐标)
if (lastTime != null) {
float lastTime20 = lastTime.floatValue() + nPush;
int lastTime20Idx = findClosestValidIndex(compressed.data, lastTime20);
if (lastTime20Idx >= 0) {
labelPositions.add(new int[]{(lastTime20Idx-2), (int) Math.round(lastTime20)});
}
}
// 获取或创建markLine
cn.hutool.json.JSONObject existingMarkLine = seriesObj.getJSONObject("markLine");
cn.hutool.json.JSONArray markLineData;
if (existingMarkLine == null) {
// 无null的情况自己创建markLine包含虚线和横坐标标签
markLineData = new cn.hutool.json.JSONArray();
// x=0 虚线
int zeroIdx = findClosestValidIndex(compressed.data, 0f);
if (zeroIdx >= 0) {
cn.hutool.json.JSONObject zeroLine = new cn.hutool.json.JSONObject();
zeroLine.set("xAxis", zeroIdx);
cn.hutool.json.JSONObject zeroLabel = new cn.hutool.json.JSONObject();
zeroLabel.set("show", false);
zeroLine.set("label", zeroLabel);
markLineData.add(zeroLine);
}
// lastTime 虚线
if (lastTime != null) {
int lastTimeIdx = findClosestValidIndex(compressed.data, lastTime.floatValue());
if (lastTimeIdx >= 0) {
cn.hutool.json.JSONObject lastTimeLine = new cn.hutool.json.JSONObject();
lastTimeLine.set("xAxis", lastTimeIdx);
cn.hutool.json.JSONObject lastTimeLabelObj = new cn.hutool.json.JSONObject();
lastTimeLabelObj.set("show", false);
lastTimeLine.set("label", lastTimeLabelObj);
markLineData.add(lastTimeLine);
}
}
// 先收集所有标签到markLineData
for (int[] pos : labelPositions) {
cn.hutool.json.JSONObject line = new cn.hutool.json.JSONObject();
line.set("xAxis", pos[0]);
cn.hutool.json.JSONObject lineLineStyle = new cn.hutool.json.JSONObject();
lineLineStyle.set("width", 0);
line.set("lineStyle", lineLineStyle);
cn.hutool.json.JSONObject lineLabel = new cn.hutool.json.JSONObject();
lineLabel.set("show", true);
lineLabel.set("formatter", String.valueOf(pos[1]));
lineLabel.set("position", "start");
lineLabel.set("color", "#333");
lineLabel.set("fontSize", 10);
line.set("label", lineLabel);
markLineData.add(line);
}
// 最后一次性设置到markLine和series
existingMarkLine = new cn.hutool.json.JSONObject();
existingMarkLine.set("symbol", new String[]{"none", "none"});
cn.hutool.json.JSONObject lineStyle = new cn.hutool.json.JSONObject();
lineStyle.set("type", "dashed");
lineStyle.set("color", "#999");
lineStyle.set("width", 1);
existingMarkLine.set("lineStyle", lineStyle);
cn.hutool.json.JSONObject globalLabel = new cn.hutool.json.JSONObject();
globalLabel.set("show", false);
existingMarkLine.set("label", globalLabel);
existingMarkLine.set("data", markLineData);
seriesObj.set("markLine", existingMarkLine);
} else {
// 有null的情况追加标签到已有的markLine
markLineData = existingMarkLine.getJSONArray("data");
for (int[] pos : labelPositions) {
cn.hutool.json.JSONObject line = new cn.hutool.json.JSONObject();
line.set("xAxis", pos[0]);
cn.hutool.json.JSONObject lineLineStyle = new cn.hutool.json.JSONObject();
lineLineStyle.set("width", 0);
line.set("lineStyle", lineLineStyle);
cn.hutool.json.JSONObject lineLabel = new cn.hutool.json.JSONObject();
lineLabel.set("show", true);
lineLabel.set("formatter", String.valueOf(pos[1]));
lineLabel.set("position", "start");
lineLabel.set("color", "#333");
lineLabel.set("fontSize", 10);
line.set("label", lineLabel);
markLineData.add(line);
}
}
}
private static List<Integer> findNullSegmentBoundaryIndices(List<List<Float>> data) {
List<Integer> indices = new ArrayList<>();
boolean inNullSegment = false;
for (int i = 0; i < data.size(); i++) {
Float y = data.get(i).get(1);
if (y == null) {
if (!inNullSegment) {
indices.add(i > 0 ? i - 1 : i);
inNullSegment = true;
}
} else {
if (inNullSegment) {
indices.add(i);
inNullSegment = false;
}
}
}
if (inNullSegment) {
indices.add(data.size() - 1);
}
return indices;
}
private static void addNullMarkLinesForCategoryAxis(cn.hutool.json.JSONObject seriesObj, CompressedResult compressed, Double lastTime) {
if (compressed.nullRegionIndices.isEmpty()) {
return;
}
cn.hutool.json.JSONArray markLineData = new cn.hutool.json.JSONArray();
// x=0 虚线
int zeroIdx = findClosestValidIndex(compressed.data, 0f);
if (zeroIdx >= 0) {
cn.hutool.json.JSONObject zeroLine = new cn.hutool.json.JSONObject();
zeroLine.set("xAxis", zeroIdx);
cn.hutool.json.JSONObject zeroLabel = new cn.hutool.json.JSONObject();
zeroLabel.set("show", false);
zeroLine.set("label", zeroLabel);
markLineData.add(zeroLine);
}
// null段边界的垂直虚线
for (int r = 0; r < compressed.nullRegionIndices.size(); r++) {
int[] region = compressed.nullRegionIndices.get(r);
int nullStartIdx = region[0]; // 第一个占位点索引
int nullEndIdx = region[1]; // 最后一个占位点索引
// 入口虚线nullStartIdx - 1null前最后一个有效数据点
cn.hutool.json.JSONObject entryLine = new cn.hutool.json.JSONObject();
entryLine.set("xAxis", nullStartIdx - 1);
cn.hutool.json.JSONObject entryLabel = new cn.hutool.json.JSONObject();
entryLabel.set("show", false);
entryLine.set("label", entryLabel);
markLineData.add(entryLine);
// 出口虚线nullEndIdxnull后第一个有效数据点
cn.hutool.json.JSONObject exitLine = new cn.hutool.json.JSONObject();
exitLine.set("xAxis", nullEndIdx);
cn.hutool.json.JSONObject exitLabel = new cn.hutool.json.JSONObject();
exitLabel.set("show", false);
exitLine.set("label", exitLabel);
markLineData.add(exitLine);
}
// 时间持续时间结束的数据点
if (lastTime != null) {
int lastTimeIdx = findClosestValidIndex(compressed.data, lastTime.floatValue());
if (lastTimeIdx >= 0) {
cn.hutool.json.JSONObject lastTimeLine = new cn.hutool.json.JSONObject();
lastTimeLine.set("xAxis", lastTimeIdx);
cn.hutool.json.JSONObject lastTimeLabel = new cn.hutool.json.JSONObject();
lastTimeLabel.set("show", false);
lastTimeLine.set("label", lastTimeLabel);
markLineData.add(lastTimeLine);
}
}
cn.hutool.json.JSONObject markLine = new cn.hutool.json.JSONObject();
markLine.set("symbol", new String[]{"none", "none"});
cn.hutool.json.JSONObject lineStyle = new cn.hutool.json.JSONObject();
lineStyle.set("type", "dashed");
lineStyle.set("color", "#999");
lineStyle.set("width", 1);
markLine.set("lineStyle", lineStyle);
cn.hutool.json.JSONObject globalLabel = new cn.hutool.json.JSONObject();
globalLabel.set("show", false);
markLine.set("label", globalLabel);
markLine.set("data", markLineData);
seriesObj.set("markLine", markLine);
// markArea - 灰色背景覆盖null区域从入口边界到出口边界
cn.hutool.json.JSONArray markAreaData = new cn.hutool.json.JSONArray();
for (int r = 0; r < compressed.nullRegionIndices.size(); r++) {
int[] region = compressed.nullRegionIndices.get(r);
int nullStartIdx = region[0];
int nullEndIdx = region[1];
cn.hutool.json.JSONArray areaPair = new cn.hutool.json.JSONArray();
cn.hutool.json.JSONObject start = new cn.hutool.json.JSONObject();
start.set("xAxis", nullStartIdx - 1); // 从入口边界有效数据点
cn.hutool.json.JSONObject end = new cn.hutool.json.JSONObject();
end.set("xAxis", nullEndIdx); // 到出口边界有效数据点
areaPair.add(start);
areaPair.add(end);
markAreaData.add(areaPair);
}
cn.hutool.json.JSONObject markArea = new cn.hutool.json.JSONObject();
cn.hutool.json.JSONObject itemStyle = new cn.hutool.json.JSONObject();
itemStyle.set("color", "rgba(180, 180, 180, 0.2)");
itemStyle.set("borderWidth", 0);
markArea.set("itemStyle", itemStyle);
markArea.set("data", markAreaData);
seriesObj.set("markArea", markArea);
}
/** /**
* @param title 标题 * @param title 标题
* @param values 数据值 * @param values 数据值

View File

@@ -10,9 +10,10 @@ import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.*; import java.util.List;
import java.util.Map;
import java.util.Objects;
/** /**
* @author hongawen * @author hongawen
@@ -55,10 +56,9 @@ public class DrawPicUtil {
return Objects.requireNonNull(picResult.getBody()).indexOf("image/png") > 0 ? picResult.getBody() : ""; return Objects.requireNonNull(picResult.getBody()).indexOf("image/png") > 0 ? picResult.getBody() : "";
} }
/*** /***
* 绘制波形图
* @author hongawen * @author hongawen
* 绘制波形图
* @date 2023/6/21 11:01 * @date 2023/6/21 11:01
* @return String base64数据 * @return String base64数据
*/ */
@@ -77,6 +77,11 @@ public class DrawPicUtil {
return drawPic(instantJson, width, height); return drawPic(instantJson, width, height);
} }
public String drawWavePic(String title, List<List<Float>> aValue, List<List<Float>> bValue, List<List<Float>> cValue, String unit, Float max, Float min, String a, String b, String c, List<String> colors, Boolean isOpen, Double lastTime, List<Float> sharedNullBoundaryXValues,Integer nPush) {
String instantJson = LineGenerator.generateWaveOption(title, aValue, bValue, cValue, unit, max, min, a, b, c, colors, isOpen, lastTime, sharedNullBoundaryXValues,nPush);
return drawPic(instantJson, 0, 0);
}
/*** /***
* 绘制itic曲线图 * 绘制itic曲线图

View File

@@ -3,11 +3,9 @@ package com.njcn.event.file.component;
import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.wave.BitConverter; import com.njcn.common.utils.wave.BitConverter;
import com.njcn.event.file.pojo.dto.*; import com.njcn.event.file.pojo.dto.*;
@@ -16,11 +14,13 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.awt.*;
import java.io.*; import java.io.*;
import java.nio.file.Files; import java.nio.file.Files;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.List;
/** /**
* @author hongawen * @author hongawen
@@ -81,6 +81,46 @@ public class WaveFileComponent {
return waveDataDTO; return waveDataDTO;
} }
public WaveDataDTO getComtradeNoAddPoints(InputStream cfgStream, InputStream datStream, int iType) {
WaveDataDTO waveDataDTO = new WaveDataDTO();
// 首先判断文件路径是否为空
// 读取cfg文件
ComtradeCfgDTO comtradeCfgDTO = getComtradeCfgNoAddPoints(cfgStream);
// 为空或者未找到结束符号
if (comtradeCfgDTO == null || !"BINARY".equalsIgnoreCase(comtradeCfgDTO.getStrBinType())) {
throw new BusinessException(WaveFileResponseEnum.CFG_DATA_ERROR);
}
/*****根据通道号计算相别** add by yexb -----Start****
* 1、判断是否是3的倍数是3的倍数则是3相
* 2、假如不是3的倍数 是1的倍数则是单相
********************************************************/
if (comtradeCfgDTO.getNAnalogNum() % 3 == 0) {
comtradeCfgDTO.setNPhasic(3);
} else {
comtradeCfgDTO.setNPhasic(1);
}
// 给相别数量赋值
waveDataDTO.setIPhasic(comtradeCfgDTO.getNPhasic());
// 组装解析抬头
getWaveTitle(waveDataDTO, comtradeCfgDTO);
// 解析.dat文件
List<List<Float>> listWaveData = getComtradeDatNoAddPoints(comtradeCfgDTO, datStream, iType);
waveDataDTO.setComtradeCfgDTO(comtradeCfgDTO);
waveDataDTO.setListWaveData(listWaveData);
//add by hongawen,将暂态触发起始时间记录下来
waveDataDTO.setTime(DateUtil.format(comtradeCfgDTO.getTimeTrige(), DatePattern.NORM_DATETIME_MS_PATTERN));
/*****根据通道号计算相别** add by yexb -----end****/
return waveDataDTO;
}
/********************************* /*********************************
* 根据波形数据算出rms值数据 * 根据波形数据算出rms值数据
* param waveDataDTO 瞬时波形包含了CFG配置文件 * param waveDataDTO 瞬时波形包含了CFG配置文件
@@ -472,6 +512,127 @@ public class WaveFileComponent {
return comtradeCfgDTO; return comtradeCfgDTO;
} }
private ComtradeCfgDTO getComtradeCfgNoAddPoints(InputStream cfgStream) {
ComtradeCfgDTO comtradeCfgDTO = new ComtradeCfgDTO();
try (InputStreamReader read = new InputStreamReader(cfgStream, CharsetUtil.CHARSET_GBK); BufferedReader bufferedReader = new BufferedReader(read);) {
// 第一行不关心仅仅是一些描述类的信息
String strFileLine = bufferedReader.readLine();
// 第二行需要关心第二个(模拟量的个数)和第三个参数(开关量的个数)
strFileLine = bufferedReader.readLine();
// 按“,”进行分割
String[] strTempArray = strFileLine.split(StrUtil.COMMA);
// 总个数
comtradeCfgDTO.setNChannelNum(Integer.parseInt(strTempArray[0]));
// 模拟量的个数
comtradeCfgDTO.setNAnalogNum(Integer.parseInt(strTempArray[1].substring(0, strTempArray[1].length() - 1)));
// 开关量的个数
comtradeCfgDTO.setNDigitalNum(Integer.parseInt(strTempArray[2].substring(0, strTempArray[2].length() - 1)));
// 从第三行开始的ComtradeCfg.nChannelNum行是模拟量通道和数字量通道
List<AnalogDTO> lstAnalogDTO = new ArrayList<>();
comtradeCfgDTO.setLstAnalogDTO(lstAnalogDTO);
for (int i = 0; i < comtradeCfgDTO.getNChannelNum(); i++) {
AnalogDTO analogDTO = new AnalogDTO();
lstAnalogDTO.add(analogDTO);
strFileLine = bufferedReader.readLine();
strTempArray = strFileLine.split(StrUtil.COMMA);
//通道序号
analogDTO.setNIndex(Integer.parseInt(strTempArray[0]));
// 通道名称
analogDTO.setSzChannleName(strTempArray[1]);
// 相位名称
analogDTO.setSzPhasicName(strTempArray[2]);
// 监视的通道名称
analogDTO.setSzMonitoredChannleName(strTempArray[3]);
// 通道的单位
analogDTO.setSzUnitName(strTempArray[4]);
// 通道的系数
analogDTO.setFCoefficent(Float.parseFloat(strTempArray[5]));
// 通道的偏移量
analogDTO.setFOffset(Float.parseFloat(strTempArray[6]));
// 起始采样时间的偏移量
analogDTO.setFTimeOffset(Float.parseFloat(strTempArray[7]));
// 采样值的最小值
analogDTO.setNMin(Integer.parseInt(strTempArray[8]));
// 采样值的最大值
analogDTO.setNMax(Integer.parseInt(strTempArray[9]));
// 一次变比
analogDTO.setFPrimary(Float.parseFloat(strTempArray[10]));
// 二次变比
analogDTO.setFSecondary(Float.parseFloat(strTempArray[11]));
// 一次值还是二次值标志
analogDTO.setSzValueType(strTempArray[12]);
}
//WW 2019-11-14 // 采样频率
String freqLine = bufferedReader.readLine();
int nFreq;
try {
// 先尝试解析为double再四舍五入为整数以兼容"50.00"这样的格式
nFreq = (int) Math.round(Double.parseDouble(freqLine));
} catch (NumberFormatException e) {
// 如果失败则使用原来的整数解析方式
nFreq = Integer.parseInt(freqLine);
}
// 获取采样段数
strFileLine = bufferedReader.readLine();
int nRates = Integer.parseInt(strFileLine);
comtradeCfgDTO.setNRates(nRates);
// 获得每段的采样率 //采样率
List<RateDTO> lstRate = new ArrayList<>();
int nOffset = 0;
for (int i = 0; i < nRates; i++) {
strFileLine = bufferedReader.readLine();
strTempArray = strFileLine.split(StrUtil.COMMA);
RateDTO rateDTO = new RateDTO();
// 单周波采样点数 //WW 2019-11-14
double doubleValue = Double.parseDouble(strTempArray[0]); // 解析为 double
int result = (int) (doubleValue / nFreq); // 强制转换为 int
rateDTO.setNOneSample(result);
// 总点数 //这里的strTemp是一个偏移量
rateDTO.setNSampleNum((Integer.parseInt(strTempArray[1]) - nOffset));
nOffset = rateDTO.getNSampleNum();
lstRate.add(rateDTO);
}
comtradeCfgDTO.setLstRate(lstRate);
// 增加读取波形起始时间个结束时间
String timeFormat = "dd/MM/yyyy,HH:mm:ss.SSS";
// 波形起始时间
strFileLine = bufferedReader.readLine();
strFileLine = strFileLine.substring(0, strFileLine.length() - 3);
comtradeCfgDTO.setTimeStart(DateUtil.parse(strFileLine, timeFormat));
// 暂态触发时间
strFileLine = bufferedReader.readLine();
strFileLine = strFileLine.substring(0, strFileLine.length() - 3);
comtradeCfgDTO.setTimeTrige(DateUtil.parse(strFileLine, timeFormat));
// 获取触发时间的时间 + 毫秒
Calendar calendar = DateUtil.calendar(comtradeCfgDTO.getTimeTrige());
comtradeCfgDTO.setFirstMs(calendar.get(Calendar.MILLISECOND));
comtradeCfgDTO.setFirstTime(calendar.getTime());
long a = comtradeCfgDTO.getTimeStart().getTime();
long b = comtradeCfgDTO.getTimeTrige().getTime();
int c = (int) (b - a);
if (c >= 90 && c <= 110) {
comtradeCfgDTO.setNPush(100);
} else if (c >= 190 && c <= 210) {
comtradeCfgDTO.setNPush(200);
}
// 赋值编码格式(二进制)
comtradeCfgDTO.setStrBinType(bufferedReader.readLine().toUpperCase());
} catch (Exception e) {
// 解析.cfg文件出错
comtradeCfgDTO = null;
}
return comtradeCfgDTO;
}
/********************************* /*********************************
* 读取dat方法 * 读取dat方法
* param strFilePath .dat访问路径 * param strFilePath .dat访问路径
@@ -511,13 +672,14 @@ public class WaveFileComponent {
//抽点后新的的采样率 //抽点后新的的采样率
List<RateDTO> newLstRate = new ArrayList<>(); List<RateDTO> newLstRate = new ArrayList<>();
for (int iRate = 0; iRate < comtradeCfgDTO.getNRates(); iRate++) { for (int iRate = 0; iRate < comtradeCfgDTO.getNRates(); iRate++) {
// if (comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() >= 32) {
// 计算本段录波总共有多少波形 // 计算本段录波总共有多少波形
nWaveNum = comtradeCfgDTO.getLstRate().get(iRate).getNSampleNum() / comtradeCfgDTO.getLstRate().get(iRate).getNOneSample(); nWaveNum = comtradeCfgDTO.getLstRate().get(iRate).getNSampleNum() / comtradeCfgDTO.getLstRate().get(iRate).getNOneSample();
//设置总波形大小 //设置总波形大小
comtradeCfgDTO.setNAllWaveNum(comtradeCfgDTO.getNAllWaveNum() + nWaveNum); comtradeCfgDTO.setNAllWaveNum(comtradeCfgDTO.getNAllWaveNum() + nWaveNum);
// 将最低采样率替换到本段录波内 // 将最低采样率替换到本段录波内
RateDTO tmpRateDTO = new RateDTO(); RateDTO tmpRateDTO = new RateDTO();
// C# 原实现中 bool 默认是 false16~31 点/周波段也应按普通抽点处理
tmpRateDTO.bRMSFlag = false;
// 有效值标志,如果是有效值,那么就需要反向补点,而不是抽点 // 有效值标志,如果是有效值,那么就需要反向补点,而不是抽点
if (comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() >= 32) { if (comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() >= 32) {
//YXB 2025-08-27 //YXB 2025-08-27
@@ -547,12 +709,7 @@ public class WaveFileComponent {
newLstRate.get(nnInd).setNSampleNum(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() * nWaveNum); newLstRate.get(nnInd).setNSampleNum(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() * nWaveNum);
} }
// 正常的配置中采样率
/* comtradeCfgDTO.getLstRate().get(nnInd).setNOneSample(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample());
comtradeCfgDTO.getLstRate().get(nnInd).setNSampleNum(comtradeCfgDTO.getLstRate().get(iRate).getNSampleNum());*/
nnInd++; nnInd++;
// }
} }
// 偏移量,采样间隔 // 偏移量,采样间隔
long nOffSet = 0, nWaveSpan; long nOffSet = 0, nWaveSpan;
@@ -560,7 +717,6 @@ public class WaveFileComponent {
float fValue, dfValue; float fValue, dfValue;
// 计算不同块的采样率 // 计算不同块的采样率
int nIndex = 0; int nIndex = 0;
// 将最低采样率替换到本段录波内
// .CFG中采样率 // .CFG中采样率
RateDTO tmpRateDTO; RateDTO tmpRateDTO;
// nBlockNum 总循环次数 // nBlockNum 总循环次数
@@ -575,46 +731,29 @@ public class WaveFileComponent {
} }
} }
tmpRateDTO = comtradeCfgDTO.getLstRate().get(nIndex); tmpRateDTO = comtradeCfgDTO.getLstRate().get(nIndex);
//YXB 2025-08-27 如果是有效值,那么需要去补点,而不是抽点 dfValue = (float) 20 / tmpRateDTO.getNOneSample();
if (newLstRate.get(nIndex).bRMSFlag == true) { // C# 原实现中 RMS 段与普通抽点是两条独立控制流,不能挂在同一个取模条件下
if (Boolean.TRUE.equals(newLstRate.get(nIndex).bRMSFlag)) {
//计算本段补点采样间隔 //计算本段补点采样间隔
nWaveSpan = newLstRate.get(nIndex).getNOneSample() / tmpRateDTO.getNOneSample(); nWaveSpan = newLstRate.get(nIndex).getNOneSample() / tmpRateDTO.getNOneSample();
} else {
// 计算本段抽点采样间隔
nWaveSpan = tmpRateDTO.getNOneSample() / newLstRate.get(nIndex).getNOneSample();
}
dfValue = (float) 20 / tmpRateDTO.getNOneSample();
// 判断是否到了需要抽的采样点
if (i % nWaveSpan == 0) {
// 计算每个通道的值
//存储局部数据集合包含了时间ABC三相
List<Float> tmpWaveData = new ArrayList<>();
//YXB 2025-08-27 如果是有效值,那么需要去补点,而不是抽点
if (newLstRate.get(nIndex).bRMSFlag == true) {
// 计算有多少个周波 // 计算有多少个周波
long allWaveTemp = newLstRate.get(nIndex).getNSampleNum() / newLstRate.get(nIndex).getNOneSample(); long allWaveTemp = newLstRate.get(nIndex).getNSampleNum() / newLstRate.get(nIndex).getNOneSample();
// 本段需要补多少点 // 本段需要补多少点
long allempSample = newLstRate.get(nIndex).getNOneSample(); long allempSample = newLstRate.get(nIndex).getNOneSample();
//int iStartWaveTemp = i ;// 开始补点的起点 int segmentEndIndex = (int) (nOffSet + tmpRateDTO.getNSampleNum() - 1);
for (int iWaveTemp = 0; iWaveTemp < allWaveTemp; iWaveTemp++) { for (int iWaveTemp = 0; iWaveTemp < allWaveTemp; iWaveTemp++) {
for (int mTempSample = 0; mTempSample < allempSample; mTempSample++) { for (int mTempSample = 0; mTempSample < allempSample; mTempSample++) {
//最多只有半波有效值也就是每周波是1个或者2个点然后去补最少16个 // 2 点/周波时,半周波位置需要切换到该周波的第二个原始采样
if (mTempSample / nWaveSpan == 1 && mTempSample % nWaveSpan == 0) { if (mTempSample / nWaveSpan == 1 && mTempSample % nWaveSpan == 0) {
i++; i++;
} }
//存储局部数据集合包含了时间ABC三相 //存储局部数据集合包含了时间ABC三相
tmpWaveData = new ArrayList<>(); List<Float> tmpWaveData = new ArrayList<>();
for (int j = 0; j < comtradeCfgDTO.getNAnalogNum(); j++) { for (int j = 0; j < comtradeCfgDTO.getNAnalogNum(); j++) {
//数据只有电压ABC三相数据不展示U0、I0等数据 YXB2020-10-09 去除相别为N相的数据
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzPhasicName().equalsIgnoreCase("N")) { if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzPhasicName().equalsIgnoreCase("N")) {
break; break;
} }
float fCoef = comtradeCfgDTO.getLstAnalogDTO().get(j).getFCoefficent(); float fCoef = comtradeCfgDTO.getLstAnalogDTO().get(j).getFCoefficent();
if((i * nBlockSize + 2 * 4 + j * 2) == 2437568){
System.out.println(55);
}
fValue = BitConverter.byte2ToUnsignedShort(datArray, i * nBlockSize + 2 * 4 + j * 2) * fCoef; fValue = BitConverter.byte2ToUnsignedShort(datArray, i * nBlockSize + 2 * 4 + j * 2) * fCoef;
//WW 2019-11-14 //WW 2019-11-14
/************************* /*************************
@@ -659,7 +798,7 @@ public class WaveFileComponent {
{ {
//根据cfg内的变比将一次值转换成二次值 //根据cfg内的变比将一次值转换成二次值
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary() != 0.0f) { if (comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary() != 0.0f) {
fValue = comtradeCfgDTO.getLstAnalogDTO().get(j).getFSecondary() / comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary(); fValue = fValue * comtradeCfgDTO.getLstAnalogDTO().get(j).getFSecondary() / comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary();
} else { } else {
fValue = fValue; fValue = fValue;
} }
@@ -684,12 +823,25 @@ public class WaveFileComponent {
//把每个单独的值赋予到整体里面去 //把每个单独的值赋予到整体里面去
listWaveData.add(tmpWaveData); listWaveData.add(tmpWaveData);
} }
// 把每个单独的值赋予到整体里面去 // 本周波处理完成后,推进到下一周波的原始采样点
if (iWaveTemp < (allWaveTemp - 1)) { if (iWaveTemp < (allWaveTemp - 1)) {
i++; i++;
} }
} }
} else { // 某些文件的段点数并不是原始每周波点数的整倍数。
// RMS 段处理完成后,强制把原始游标对齐到当前段末尾,
// 这样外层 for 的下一次自增才能稳定落到下一段起点,避免重复进入同一 RMS 段。
i = segmentEndIndex;
continue;
}
// 计算本段抽点采样间隔
nWaveSpan = tmpRateDTO.getNOneSample() / newLstRate.get(nIndex).getNOneSample();
// 判断是否到了需要抽的采样点
if (i % nWaveSpan == 0) {
// 计算每个通道的值
//存储局部数据集合包含了时间ABC三相
List<Float> tmpWaveData = new ArrayList<>();
for (int j = 0; j < comtradeCfgDTO.getNAnalogNum(); j++) { for (int j = 0; j < comtradeCfgDTO.getNAnalogNum(); j++) {
//数据只有电压ABC三相数据不展示U0、I0等数据 YXB2020-10-09 去除相别为N相的数据 //数据只有电压ABC三相数据不展示U0、I0等数据 YXB2020-10-09 去除相别为N相的数据
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzPhasicName().equalsIgnoreCase("N")) { if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzPhasicName().equalsIgnoreCase("N")) {
@@ -742,7 +894,7 @@ public class WaveFileComponent {
{ {
//根据cfg内的变比将一次值转换成二次值 //根据cfg内的变比将一次值转换成二次值
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary() != 0.0f) { if (comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary() != 0.0f) {
fValue = comtradeCfgDTO.getLstAnalogDTO().get(j).getFSecondary() / comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary(); fValue = fValue * comtradeCfgDTO.getLstAnalogDTO().get(j).getFSecondary() / comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary();
} else { } else {
fValue = fValue; fValue = fValue;
} }
@@ -768,6 +920,204 @@ public class WaveFileComponent {
} }
} }
} }
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(WaveFileResponseEnum.DAT_DATA_ERROR);
}
return listWaveData;
}
private List<List<Float>> getComtradeDatNoAddPoints(ComtradeCfgDTO comtradeCfgDTO, InputStream datStream, int iType) {
//返回数据如果仅仅做展示后期考虑换String类型降低内存开销
List<List<Float>> listWaveData = new ArrayList<>();
//初始化xValue的值
float xValueAll = 0;
//判断是否首次登陆
boolean blxValue = false;
byte[] datArray;
try {
datArray = IoUtil.readBytes(datStream);
if (ArrayUtil.isEmpty(datArray)) {
throw new BusinessException(WaveFileResponseEnum.DAT_DATA_ERROR);
}
// 计算每个单独的数据块的大小 4个字节的序号 4个字节的时间 2个字节的值
// 示例中的排布是 4个字节的序号 4个字节的时间 UA(2字节) UB(2字节) UC(2字节) IA(2字节) IB(2字节) IC(2字节)
int nDigSize = (comtradeCfgDTO.getNDigitalNum() % 16) > 0 ? (comtradeCfgDTO.getNDigitalNum() / 16 + 1) * 2 : comtradeCfgDTO.getNDigitalNum() / 16 * 2;
int nBlockSize = 2 * Integer.SIZE / 8 + comtradeCfgDTO.getNAnalogNum() * 2 + nDigSize;
// 总长度除以每个块的大小
int nBlockNum = (int)Math.floor(datArray.length / nBlockSize);
// 获取采样率
int finalSampleRate = getFinalWaveSample(comtradeCfgDTO.getLstRate(), iType);
if (finalSampleRate != -1) {
//设置最终采样率
comtradeCfgDTO.setFinalSampleRate(finalSampleRate);
// 计算转换后的采样率
int nnInd = 0;
// 抽点后总共多少点数据
int nWaveNum;
//抽点后新的的采样率
List<RateDTO> newLstRate = new ArrayList<>();
for (int iRate = 0; iRate < comtradeCfgDTO.getNRates(); iRate++) {
if (comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() >= 32) {
// 计算本段录波总共有多少波形
nWaveNum = comtradeCfgDTO.getLstRate().get(iRate).getNSampleNum() / comtradeCfgDTO.getLstRate().get(iRate).getNOneSample();
//设置总波形大小
comtradeCfgDTO.setNAllWaveNum(comtradeCfgDTO.getNAllWaveNum() + nWaveNum);
// 将最低采样率替换到本段录波内
RateDTO tmpRateDTO = new RateDTO();
// 有效值标志,如果是有效值,那么就需要反向补点,而不是抽点
// if (comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() >= 32) {
// //YXB 2025-08-27
// tmpRateDTO.bRMSFlag = false;
// }
// //如果采样是全波有效值或者半波有效值,需要去补足周波点数 YXB 2025-08-27
// else if (comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() <= 2) {
// //YXB 2025-08-27
// tmpRateDTO.bRMSFlag = true;
// }
newLstRate.add(tmpRateDTO);
//iFlag =3 一定不进行抽点算法
if (iType != 3) {
//true 抽点算法(当前采样率跟统一采样率不一样则是抽点,否则是未抽点)
if (!Objects.equals(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample(), comtradeCfgDTO.getFinalSampleRate())) {
newLstRate.get(nnInd).setNOneSample(comtradeCfgDTO.getFinalSampleRate());
// 计算本段录波按照最低采样点应该有多少录波
newLstRate.get(nnInd).setNSampleNum(comtradeCfgDTO.getFinalSampleRate() * nWaveNum);
} else {
newLstRate.get(nnInd).setNOneSample(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample());
// 计算本段录波按照最低采样点应该有多少录波
newLstRate.get(nnInd).setNSampleNum(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() * nWaveNum);
}
} else {
newLstRate.get(nnInd).setNOneSample(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample());
// 计算本段录波按照最低采样点应该有多少录波
newLstRate.get(nnInd).setNSampleNum(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample() * nWaveNum);
}
// 正常的配置中采样率
comtradeCfgDTO.getLstRate().get(nnInd).setNOneSample(comtradeCfgDTO.getLstRate().get(iRate).getNOneSample());
comtradeCfgDTO.getLstRate().get(nnInd).setNSampleNum(comtradeCfgDTO.getLstRate().get(iRate).getNSampleNum());
nnInd++;
}
}
// 偏移量,采样间隔
long nOffSet = 0, nWaveSpan;
//两个点之间的时间差
float fValue, dfValue;
// 计算不同块的采样率
int nIndex = 0;
// 将最低采样率替换到本段录波内
// .CFG中采样率
RateDTO tmpRateDTO;
// nBlockNum 总循环次数
for (int i = 0; i < nBlockNum; i++) {
tmpRateDTO = comtradeCfgDTO.getLstRate().get(nIndex);
// 判断是否进入下一段
if (i == tmpRateDTO.getNSampleNum() + nOffSet) {
nOffSet += tmpRateDTO.getNSampleNum();
nIndex++;
if (nIndex == nnInd) {
break;
}
}
nWaveSpan = tmpRateDTO.getNOneSample() / newLstRate.get(nIndex).getNOneSample();
// tmpRateDTO = comtradeCfgDTO.getLstRate().get(nIndex);
// //YXB 2025-08-27 如果是有效值,那么需要去补点,而不是抽点
// if (newLstRate.get(nIndex).bRMSFlag == true) {
// //计算本段补点采样间隔
// nWaveSpan = newLstRate.get(nIndex).getNOneSample() / tmpRateDTO.getNOneSample();
// } else {
// // 计算本段抽点采样间隔
// nWaveSpan = tmpRateDTO.getNOneSample() / newLstRate.get(nIndex).getNOneSample();
// }
dfValue = (float) 20 / tmpRateDTO.getNOneSample();
// 判断是否到了需要抽的采样点
if (i % nWaveSpan == 0) {
// 计算每个通道的值
//存储局部数据集合包含了时间ABC三相
List<Float> tmpWaveData = new ArrayList<>();
for (int j = 0; j < comtradeCfgDTO.getNAnalogNum(); j++) {
//数据只有电压ABC三相数据不展示U0、I0等数据 YXB2020-10-09 去除相别为N相的数据
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzPhasicName().equalsIgnoreCase("N")) {
break;
}
float fCoef = comtradeCfgDTO.getLstAnalogDTO().get(j).getFCoefficent();
fValue = BitConverter.byte2ToUnsignedShort(datArray, i * nBlockSize + 2 * 4 + j * 2) * fCoef;
//WW 2019-11-14
/**************************
* 1、接口返回的默认是二次值
* 2、P是一次值 S是二次值
* 3、S(二次值)情况下:
* ①、单位为"V"时候则直接等于;
* ②、单位为"kV"时候需要乘以1000
* 4、P(一次值)情况下:
* ①、单位为"V"时候则直接等于;
* ②、单位为"kV"时候需要乘以1000
**************************/
//P是一次值 S是二次值
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzValueType().equalsIgnoreCase("S")) {
//判断单位是V还是kV
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzUnitName().equalsIgnoreCase("KV")) {
fValue = fValue * 1000.0f;
} else {
fValue = fValue;
}
}
//P是一次值 S是二次值
else if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzValueType().equalsIgnoreCase("P")) {
//判断单位是V还是kV
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzUnitName().equalsIgnoreCase("V")) {
//根据cfg内的变比将一次值转换成二次值
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary() != 0.0f) {
fValue = fValue * comtradeCfgDTO.getLstAnalogDTO().get(j).getFSecondary() / comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary();
} else {
fValue = fValue;
}
}
//判断单位是V还是kV
else if (comtradeCfgDTO.getLstAnalogDTO().get(j).getSzUnitName().equalsIgnoreCase("KV")) {
//根据cfg内的变比将一次值转换成二次值
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary() != 0.0f) {
fValue = fValue * 1000.0f * comtradeCfgDTO.getLstAnalogDTO().get(j).getFSecondary() / comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary();
} else {
fValue = fValue;
}
} else //还有可能是 电流单位是A
{
//根据cfg内的变比将一次值转换成二次值
if (comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary() != 0.0f) {
fValue = fValue *comtradeCfgDTO.getLstAnalogDTO().get(j).getFSecondary() / comtradeCfgDTO.getLstAnalogDTO().get(j).getFPrimary();
} else {
fValue = fValue;
}
}
}
//xValue前移量假如是第一次时候则需要前移
if (!blxValue && j == 0) {
xValueAll = (float) (i * 20) / tmpRateDTO.getNOneSample() - comtradeCfgDTO.getNPush();
blxValue = true;
//只增加一个xValue的值 //增加时间值
tmpWaveData.add((float) (Math.round(xValueAll * 100)) / 100);
} else if (j == 0) {
xValueAll += (float) nWaveSpan * dfValue;
//只增加一个xValue的值 //增加时间值
tmpWaveData.add((float) (Math.round(xValueAll * 100)) / 100);
}
//不同通道yValue的值都需要增加最终成ABC三相 //每个通道的值
tmpWaveData.add((float) (Math.round(fValue * 100)) / 100);
}
//把每个单独的值赋予到整体里面去
listWaveData.add(tmpWaveData);
}
}
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -1370,10 +1720,10 @@ public class WaveFileComponent {
s = sdf.format(d); s = sdf.format(d);
System.out.println(s); System.out.println(s);
WaveFileComponent waveFileComponent = new WaveFileComponent(); WaveFileComponent waveFileComponent = new WaveFileComponent();
InputStream cfgStream = waveFileComponent.getFileInputStreamByFilePath("F:\\PQ_PQLD3_9_20250821_081038_640.cfg"); InputStream cfgStream = waveFileComponent.getFileInputStreamByFilePath("C:\\Users\\无名\\Desktop\\月报\\2026\\202603\\文档\\暂态事件及波形\\新建文件夹 (3)\\Comtrade\\Comtrade\\10.95.0.201\\PQMonitor_PQM1_001183_20260320_175042_316.CFG");
InputStream datStream = waveFileComponent.getFileInputStreamByFilePath("F:\\PQ_PQLD3_9_20250821_081038_640.dat"); InputStream datStream = waveFileComponent.getFileInputStreamByFilePath("C:\\Users\\无名\\Desktop\\月报\\2026\\202603\\文档\\暂态事件及波形\\新建文件夹 (3)\\Comtrade\\Comtrade\\10.95.0.201\\PQMonitor_PQM1_001183_20260320_175042_316.DAT");
// 获取瞬时波形 //获取原始波形值 // 获取瞬时波形 //获取原始波形值
WaveDataDTO waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1); WaveDataDTO waveDataDTO = waveFileComponent.getComtradeNoAddPoints(cfgStream, datStream, 0);
d = new Date(); d = new Date();
s = sdf.format(d); s = sdf.format(d);
System.out.println(s); System.out.println(s);

View File

@@ -1,10 +1,9 @@
package com.njcn.event.file.component; package com.njcn.event.file.component;
import cn.hutool.core.img.ImgUtil; import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.FileUtil; import com.njcn.common.utils.FileUtil;
import com.njcn.echarts.json.LineGenerator;
import com.njcn.echarts.pojo.constant.PicCommonData; import com.njcn.echarts.pojo.constant.PicCommonData;
import com.njcn.echarts.util.DrawPicUtil; import com.njcn.echarts.util.DrawPicUtil;
import com.njcn.event.file.pojo.bo.WaveDataDetail; import com.njcn.event.file.pojo.bo.WaveDataDetail;
@@ -12,21 +11,17 @@ import com.njcn.event.file.pojo.dto.WaveDataDTO;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum; import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
import com.njcn.oss.constant.OssPath; import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil; import com.njcn.oss.utils.FileStorageUtil;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import sun.awt.image.BufferedImageGraphicsConfig; import sun.awt.image.BufferedImageGraphicsConfig;
import javax.imageio.ImageIO;
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.util.Base64;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* @author hongawen * @author hongawen
@@ -49,36 +44,39 @@ public class WavePicComponent {
* @date 2023/9/21 15:32 * @date 2023/9/21 15:32
* @return String 文件地址 * @return String 文件地址
*/ */
public String generateInstantImageZl(List<WaveDataDetail> waveDataDetails) { public String generateInstantImageZl(Integer nPush, List<WaveDataDetail> waveDataDetails, Double lastTime) {
String firstPic = null, secondPic = null, thirdPic = null, forthPic = null; String firstPic = null, secondPic = null, thirdPic = null, forthPic = null;
WaveDataDetail waveDataDetail0 = waveDataDetails.get(0);
// 从instantData提取null边界x值作为共享参考与Shun图保持一致
List<Float> sharedNullBoundaries = LineGenerator.extractNullBoundaryXValues(waveDataDetail0.getInstantData().getAValue());
for (WaveDataDetail waveDataDetail : waveDataDetails) { for (WaveDataDetail waveDataDetail : waveDataDetails) {
if (waveDataDetail.getChannelName().toUpperCase().startsWith("SU")) { if (waveDataDetail.getChannelName().toUpperCase().startsWith("SU")) {
firstPic = drawPicUtil.drawWavePic("电压-电网侧", waveDataDetail.getInstantData().getAValue(), firstPic = drawPicUtil.drawWavePic("电压-电网侧", waveDataDetail.getInstantData().getAValue(),
waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(), waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(), waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(), waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen() waveDataDetail.getColors(), waveDataDetail.getIsOpen(),lastTime,sharedNullBoundaries,nPush
); );
} else if (waveDataDetail.getChannelName().toUpperCase().startsWith("SI")) { } else if (waveDataDetail.getChannelName().toUpperCase().startsWith("SI")) {
thirdPic = drawPicUtil.drawWavePic("电流-电网侧", waveDataDetail.getInstantData().getAValue(), thirdPic = drawPicUtil.drawWavePic("电流-电网侧", waveDataDetail.getInstantData().getAValue(),
waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(), waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(), waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(), waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen() waveDataDetail.getColors(), waveDataDetail.getIsOpen(),lastTime,sharedNullBoundaries,nPush
); );
} else if (waveDataDetail.getChannelName().toUpperCase().startsWith("LU")) { } else if (waveDataDetail.getChannelName().toUpperCase().startsWith("LU")) {
secondPic = drawPicUtil.drawWavePic("电压-负载侧", waveDataDetail.getInstantData().getAValue(), secondPic = drawPicUtil.drawWavePic("电压-负载侧", waveDataDetail.getInstantData().getAValue(),
waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(), waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(), waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(), waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen() waveDataDetail.getColors(), waveDataDetail.getIsOpen(),lastTime,sharedNullBoundaries,nPush
); );
} else { } else {
forthPic = drawPicUtil.drawWavePic("电流-负载侧", waveDataDetail.getInstantData().getAValue(), forthPic = drawPicUtil.drawWavePic("电流-负载侧", waveDataDetail.getInstantData().getAValue(),
waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(), waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(), waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(), waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen() waveDataDetail.getColors(), waveDataDetail.getIsOpen(),lastTime,sharedNullBoundaries,nPush
); );
} }
} }
@@ -91,36 +89,39 @@ public class WavePicComponent {
* @date 2023/9/21 15:32 * @date 2023/9/21 15:32
* @return String 文件地址 * @return String 文件地址
*/ */
public String generateRmsImageZl(List<WaveDataDetail> waveDataDetails) { public String generateRmsImageZl(Integer nPush, List<WaveDataDetail> waveDataDetails, Double lastTime) {
String firstPic = null, secondPic = null, thirdPic = null, forthPic = null; String firstPic = null, secondPic = null, thirdPic = null, forthPic = null;
WaveDataDetail waveDataDetail0 = waveDataDetails.get(0);
// 从instantData提取null边界x值作为共享参考与Shun图保持一致
List<Float> sharedNullBoundaries = LineGenerator.extractNullBoundaryXValues(waveDataDetail0.getInstantData().getAValue());
for (WaveDataDetail waveDataDetail : waveDataDetails) { for (WaveDataDetail waveDataDetail : waveDataDetails) {
if (waveDataDetail.getChannelName().toUpperCase().startsWith("SU")) { if (waveDataDetail.getChannelName().toUpperCase().startsWith("SU")) {
firstPic = drawPicUtil.drawWavePic("电压-电网侧", waveDataDetail.getRmsData().getAValue(), firstPic = drawPicUtil.drawWavePic("电压-电网侧", waveDataDetail.getRmsData().getAValue(),
waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(), waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(), waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(), waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen() waveDataDetail.getColors(), waveDataDetail.getIsOpen(),lastTime,sharedNullBoundaries,nPush
); );
} else if (waveDataDetail.getChannelName().toUpperCase().startsWith("SI")) { } else if (waveDataDetail.getChannelName().toUpperCase().startsWith("SI")) {
thirdPic = drawPicUtil.drawWavePic("电流-电网侧", waveDataDetail.getRmsData().getAValue(), thirdPic = drawPicUtil.drawWavePic("电流-电网侧", waveDataDetail.getRmsData().getAValue(),
waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(), waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(), waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(), waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen() waveDataDetail.getColors(), waveDataDetail.getIsOpen(),lastTime,sharedNullBoundaries,nPush
); );
} else if (waveDataDetail.getChannelName().toUpperCase().startsWith("LU")) { } else if (waveDataDetail.getChannelName().toUpperCase().startsWith("LU")) {
secondPic = drawPicUtil.drawWavePic("电压-负载侧", waveDataDetail.getRmsData().getAValue(), secondPic = drawPicUtil.drawWavePic("电压-负载侧", waveDataDetail.getRmsData().getAValue(),
waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(), waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(), waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(), waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen() waveDataDetail.getColors(), waveDataDetail.getIsOpen(),lastTime,sharedNullBoundaries,nPush
); );
} else { } else {
forthPic = drawPicUtil.drawWavePic("电流-负载侧", waveDataDetail.getRmsData().getAValue(), forthPic = drawPicUtil.drawWavePic("电流-负载侧", waveDataDetail.getRmsData().getAValue(),
waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(), waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(), waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(), waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen() waveDataDetail.getColors(), waveDataDetail.getIsOpen(),lastTime,sharedNullBoundaries,nPush
); );
} }
} }
@@ -209,6 +210,47 @@ public class WavePicComponent {
return picPath; return picPath;
} }
/***
* 绘制瞬时波形图 App端用来绘制图片会去掉部分数据只保留开始数据 结束数据
* @author xy
* @return String 文件地址
*/
public String generateImageShun(Integer nPush, List<WaveDataDetail> waveDataDetails, Double lastTime) {
String picPath = null;
WaveDataDetail waveDataDetail = waveDataDetails.get(0);
// 从instantData提取null边界x值作为共享参考
List<Float> sharedNullBoundaries = LineGenerator.extractNullBoundaryXValues(waveDataDetail.getInstantData().getAValue());
String firstPic = drawPicUtil.drawWavePic(getTitle(waveDataDetail.getChannelName()), waveDataDetail.getInstantData().getAValue(),
waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen(), lastTime, sharedNullBoundaries,nPush
);
String secondPic;
if (waveDataDetails.size() == 1) {
if (firstPic.contains(PicCommonData.PNG_PREFIX)) {
firstPic = firstPic.replace(PicCommonData.PNG_PREFIX, "");
}
byte[] bytes = Base64.getDecoder().decode(firstPic);
picPath = fileStorageUtil.uploadStream(new ByteArrayInputStream(bytes), OssPath.EVENT_WAVE_PIC, FileUtil.generateFileName("png"));
} else if (waveDataDetails.size() == 2) {
waveDataDetail = waveDataDetails.get(1);
secondPic = drawPicUtil.drawWavePic(getTitle(waveDataDetail.getChannelName()), waveDataDetail.getInstantData().getAValue(),
waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen(), lastTime, sharedNullBoundaries,nPush
);
picPath = composeImage(firstPic, secondPic);
}
return picPath;
}
public String getTitle(String channelName) {
return channelName.toUpperCase().startsWith("U1") ? "电压" : "电流";
}
/*** /***
* 绘制RMS波形图 * 绘制RMS波形图
* @author hongawen * @author hongawen
@@ -248,6 +290,44 @@ public class WavePicComponent {
return picPath; return picPath;
} }
/***
* 绘制RMS波形图 App端用来绘制图片会去掉部分数据只保留开始数据 结束数据
* @author xy
* @return String 文件地址
*/
public String generateImageRms(Integer nPush, List<WaveDataDetail> waveDataDetails, Double lastTime) {
String picPath = null;
WaveDataDetail waveDataDetail = waveDataDetails.get(0);
// 从instantData提取null边界x值作为共享参考与Shun图保持一致
List<Float> sharedNullBoundaries = LineGenerator.extractNullBoundaryXValues(waveDataDetail.getInstantData().getAValue());
String firstPic = drawPicUtil.drawWavePic(getTitle(waveDataDetail.getChannelName()), waveDataDetail.getRmsData().getAValue(),
waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen(), lastTime, sharedNullBoundaries,nPush
);
String secondPic;
if (waveDataDetails.size() == 1) {
if (firstPic.contains(PicCommonData.PNG_PREFIX)) {
firstPic = firstPic.replace(PicCommonData.PNG_PREFIX, "");
}
byte[] bytes = Base64.getDecoder().decode(firstPic);
picPath = fileStorageUtil.uploadStream(new ByteArrayInputStream(bytes), OssPath.EVENT_WAVE_PIC, FileUtil.generateFileName("png"));
} else if (waveDataDetails.size() == 2) {
waveDataDetail = waveDataDetails.get(1);
secondPic = drawPicUtil.drawWavePic(getTitle(waveDataDetail.getChannelName()), waveDataDetail.getRmsData().getAValue(),
waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
waveDataDetail.getColors(), waveDataDetail.getIsOpen(), lastTime, sharedNullBoundaries,nPush
);
picPath = composeImage(firstPic, secondPic);
}
return picPath;
}
/*** /***
* 合成图片 * 合成图片
* @author hongawen * @author hongawen

View File

@@ -7,6 +7,7 @@ import com.njcn.event.file.pojo.dto.WaveDataDTO;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
/** /**
* @author hongawen * @author hongawen
@@ -80,6 +81,12 @@ public class WaveUtil {
//根据相别来确认标题的名称 //根据相别来确认标题的名称
for (int m = 0; m < iPhase; m++) { for (int m = 0; m < iPhase; m++) {
if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("A")) { if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("A")) {
if (Objects.isNull(sunData.get(j).get(iPhase * i + m + 1))) {
sAValue.add(new ArrayList<Float>() {{
add(x);
add(null);
}});
} else {
float tmpShunFirstA = sunData.get(j).get(iPhase * i + m + 1) * xishu; float tmpShunFirstA = sunData.get(j).get(iPhase * i + m + 1) * xishu;
shunFirstA = tmpShunFirstA; shunFirstA = tmpShunFirstA;
sAValue.add(new ArrayList<Float>() {{ sAValue.add(new ArrayList<Float>() {{
@@ -87,7 +94,14 @@ public class WaveUtil {
add(tmpShunFirstA); add(tmpShunFirstA);
}}); }});
} }
}
if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("B")) { if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("B")) {
if (Objects.isNull(sunData.get(j).get(iPhase * i + m + 1))) {
sBValue.add(new ArrayList<Float>() {{
add(x);
add(null);
}});
} else {
float tmpShunFirstB = sunData.get(j).get(iPhase * i + m + 1) * xishu; float tmpShunFirstB = sunData.get(j).get(iPhase * i + m + 1) * xishu;
shunFirstB = tmpShunFirstB; shunFirstB = tmpShunFirstB;
sBValue.add(new ArrayList<Float>() {{ sBValue.add(new ArrayList<Float>() {{
@@ -95,7 +109,14 @@ public class WaveUtil {
add(tmpShunFirstB); add(tmpShunFirstB);
}}); }});
} }
}
if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("C")) { if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("C")) {
if (Objects.isNull(sunData.get(j).get(iPhase * i + m + 1))) {
sCValue.add(new ArrayList<Float>() {{
add(x);
add(null);
}});
} else {
float tmpShunFirstC = sunData.get(j).get(iPhase * i + m + 1) * xishu; float tmpShunFirstC = sunData.get(j).get(iPhase * i + m + 1) * xishu;
shunFirstC = tmpShunFirstC; shunFirstC = tmpShunFirstC;
sCValue.add(new ArrayList<Float>() {{ sCValue.add(new ArrayList<Float>() {{
@@ -104,6 +125,7 @@ public class WaveUtil {
}}); }});
} }
} }
}
sfMax = getMax(sfMax, shunFirstA, shunFirstB, shunFirstC); sfMax = getMax(sfMax, shunFirstA, shunFirstB, shunFirstC);
if (openTri) { if (openTri) {
sfMin = getMinOpen(sfMin, shunFirstA, shunFirstC); sfMin = getMinOpen(sfMin, shunFirstA, shunFirstC);
@@ -124,6 +146,12 @@ public class WaveUtil {
//根据相别来确认标题的名称 //根据相别来确认标题的名称
for (int m = 0; m < iPhase; m++) { for (int m = 0; m < iPhase; m++) {
if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("A")) { if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("A")) {
if (Objects.isNull(rmsData.get(k).get(iPhase * i + m + 1))) {
rAValue.add(new ArrayList<Float>() {{
add(x);
add(null);
}});
} else {
float tmpRmsFirstA = rmsData.get(k).get(iPhase * i + m + 1) * xishu; float tmpRmsFirstA = rmsData.get(k).get(iPhase * i + m + 1) * xishu;
rmsFirstA = tmpRmsFirstA; rmsFirstA = tmpRmsFirstA;
rAValue.add(new ArrayList<Float>() {{ rAValue.add(new ArrayList<Float>() {{
@@ -131,7 +159,14 @@ public class WaveUtil {
add(tmpRmsFirstA); add(tmpRmsFirstA);
}}); }});
} }
}
if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("B")) { if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("B")) {
if (Objects.isNull(rmsData.get(k).get(iPhase * i + m + 1))) {
rBValue.add(new ArrayList<Float>() {{
add(x);
add(null);
}});
} else {
float tmpRmsFirstB = rmsData.get(k).get(iPhase * i + m + 1) * xishu; float tmpRmsFirstB = rmsData.get(k).get(iPhase * i + m + 1) * xishu;
rmsFirstB = tmpRmsFirstB; rmsFirstB = tmpRmsFirstB;
rBValue.add(new ArrayList<Float>() {{ rBValue.add(new ArrayList<Float>() {{
@@ -139,7 +174,15 @@ public class WaveUtil {
add(tmpRmsFirstB); add(tmpRmsFirstB);
}}); }});
} }
}
if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("C")) { if (waveTitle.get(iPhase * i + m + 1).substring(1).contains("C")) {
if (Objects.isNull(rmsData.get(k).get(iPhase * i + m + 1))) {
rCValue.add(new ArrayList<Float>() {{
add(x);
add(null);
}});
} else {
float tmpRmsFirstC = rmsData.get(k).get(iPhase * i + m + 1) * xishu; float tmpRmsFirstC = rmsData.get(k).get(iPhase * i + m + 1) * xishu;
rmsFirstC = tmpRmsFirstC; rmsFirstC = tmpRmsFirstC;
rCValue.add(new ArrayList<Float>() {{ rCValue.add(new ArrayList<Float>() {{
@@ -148,6 +191,7 @@ public class WaveUtil {
}}); }});
} }
} }
}
rfMax = getMax(sfMax, rmsFirstA, rmsFirstB, rmsFirstC); rfMax = getMax(sfMax, rmsFirstA, rmsFirstB, rmsFirstC);
if (openTri) { if (openTri) {
rfMin = getMinOpen(sfMin, rmsFirstA, rmsFirstC); rfMin = getMinOpen(sfMin, rmsFirstA, rmsFirstC);

View File

@@ -77,10 +77,41 @@ public interface BusinessTopic {
*/ */
String REPLY_RECALL_TOPIC = "reply_recall_Topic"; String REPLY_RECALL_TOPIC = "reply_recall_Topic";
/**
* 治理心跳过期处理主题
*/
String HEARTBEAT_TIMEOUT_TOPIC = "heartbeat_timeout_topic";
/********************************数据中心*********************************/ /********************************数据中心*********************************/
String RMP_EVENT_DETAIL_TOPIC = "rmpEventDetailTopic"; String RMP_EVENT_DETAIL_TOPIC = "rmpEventDetailTopic";
// /**
// * 云前置文件信息请求主题
// */
// String FILE_INFO_REQUEST_TOPIC = "fileInfoRequestTopic";
//
// /**
// * 云前置文件信息响应主题
// */
// String FILE_INFO_RESPONSE_TOPIC = "fileInfoResponseTopic";
//
// /**
// * 云前置文件下载请求主题
// */
// String FILE_DOWNLOAD_REQUEST_TOPIC = "fileDownloadRequestTopic";
// /**
// * 云前置文件下载响应主题
// */
// String FILE_DOWNLOAD_RESPONSE_TOPIC = "fileDownloadResponseTopic";
String CLOUD_TOPIC = "Cloud_Topic";
String CLOUD_REPLY_TOPIC = "Cloud_Reply_Topic";
String ZL_LOG_TOPIC = "ZL_LOG_Topic";
interface AppDataTag { interface AppDataTag {
@@ -124,4 +155,23 @@ public interface BusinessTopic {
String STREAM_TAG = "streamInfo"; String STREAM_TAG = "streamInfo";
} }
interface HeartTag {
/**
* apf 心跳
*/
String APF_TAG = "apf";
/**
* cld 心跳
*/
String CLD_TAG = "cld";
}
interface LogTag {
//日志
String LOG_TAG = "log";
}
} }

View File

@@ -0,0 +1,27 @@
package com.njcn.mq.message;
import com.njcn.middle.rocket.domain.BaseMessage;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author xy
*/
@Data
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
public class HeartbeatTimeoutMessage extends BaseMessage implements Serializable {
private static final long serialVersionUID = 1L;
private String nDid;
private Long timestamp;
private Integer delayLevel;
}

View File

@@ -0,0 +1,43 @@
package com.njcn.mq.message;
import com.njcn.middle.rocket.domain.BaseMessage;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* 类的介绍:
*
* @author xuyang
* @version 1.0.0
* @createTime 2025/9/29 15:06
*/
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LogMessage extends BaseMessage {
@ApiModelProperty("唯一标识")
private String guid;
@ApiModelProperty("日志类型 0:设备接入日志")
private String dataType;
@ApiModelProperty("操作人员")
private String userIndex;
@ApiModelProperty("用户登录名")
private String loginName;
@ApiModelProperty("当前操作")
private String operate;
@ApiModelProperty("结果")
private Integer result;
@ApiModelProperty("失败原因")
private String failReason;
}

View File

@@ -0,0 +1,29 @@
package com.njcn.mq.template;
import com.njcn.middle.rocket.template.RocketMQEnhanceTemplate;
import com.njcn.mq.constant.BusinessResource;
import com.njcn.mq.constant.BusinessTopic;
import com.njcn.mq.message.HeartbeatTimeoutMessage;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Component;
/**
* 类的介绍:
*
* @author xuyang
* @version 1.0.0
* @createTime 2023/8/11 15:28
*/
@Component
public class HeartbeatTimeoutMessageTemplate extends RocketMQEnhanceTemplate {
public HeartbeatTimeoutMessageTemplate(RocketMQTemplate template) {
super(template);
}
public SendResult sendMember(HeartbeatTimeoutMessage heartbeatTimeoutMessage) {
heartbeatTimeoutMessage.setSource(BusinessResource.WEB_RESOURCE);
return send(BusinessTopic.HEARTBEAT_TIMEOUT_TOPIC, BusinessTopic.HeartTag.APF_TAG, heartbeatTimeoutMessage, heartbeatTimeoutMessage.getDelayLevel());
}
}

View File

@@ -0,0 +1,28 @@
package com.njcn.mq.template;
import com.njcn.middle.rocket.template.RocketMQEnhanceTemplate;
import com.njcn.mq.constant.BusinessResource;
import com.njcn.mq.constant.BusinessTopic;
import com.njcn.mq.message.LogMessage;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Component;
/**
* 类的介绍:记录日志
*
* @author xuyang
* @version 1.0.0
*/
@Component
public class LogMessageTemplate extends RocketMQEnhanceTemplate {
public LogMessageTemplate(RocketMQTemplate template) {
super(template);
}
public SendResult sendMember(LogMessage logMessage) {
logMessage.setSource(BusinessResource.APP_RESOURCE);
return send(BusinessTopic.ZL_LOG_TOPIC, BusinessTopic.LogTag.LOG_TAG, logMessage);
}
}

View File

@@ -2,9 +2,12 @@ package com.njcn.oss.utils;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.njcn.ali.oss.config.AliYunOssConfig;
import com.njcn.ali.oss.util.AliYunOssUtils; import com.njcn.ali.oss.util.AliYunOssUtils;
import com.njcn.common.config.GeneralInfo; import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.huawei.obs.config.HuaweiObsProperties;
import com.njcn.huawei.obs.util.OBSUtil; import com.njcn.huawei.obs.util.OBSUtil;
import com.njcn.minioss.bo.MinIoUploadResDTO; import com.njcn.minioss.bo.MinIoUploadResDTO;
import com.njcn.minioss.config.MinIossProperties; import com.njcn.minioss.config.MinIossProperties;
@@ -12,6 +15,8 @@ import com.njcn.minioss.util.MinIoUtils;
import com.njcn.oss.constant.GeneralConstant; import com.njcn.oss.constant.GeneralConstant;
import com.njcn.oss.constant.OssPath; import com.njcn.oss.constant.OssPath;
import com.njcn.oss.enums.OssResponseEnum; import com.njcn.oss.enums.OssResponseEnum;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectRequest;
import io.minio.*; import io.minio.*;
import io.minio.messages.Item; import io.minio.messages.Item;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -70,6 +75,11 @@ public class FileStorageUtil {
*/ */
private final AliYunOssUtils aliYunOssUtils; private final AliYunOssUtils aliYunOssUtils;
private final HuaweiObsProperties huaweiObsProperties;
private final OSS ossClient;
private final AliYunOssConfig ossConfig;
/*** /***
* 上传MultipartFile文件 * 上传MultipartFile文件
@@ -92,8 +102,11 @@ public class FileStorageUtil {
throw new BusinessException(OssResponseEnum.UPLOAD_FILE_ERROR); throw new BusinessException(OssResponseEnum.UPLOAD_FILE_ERROR);
} }
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) { } else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
filePath = dir; filePath = dir.endsWith("/")?dir+getFileNameWithoutPath(multipartFile):dir+"/"+getFileNameWithoutPath(multipartFile);
aliYunOssUtils.uploadFile(dir, multipartFile); if (filePath.charAt(0) == '/') {
filePath= filePath.substring(1);
}
aliYunOssUtils.uploadFile(filePath, multipartFile);
} else { } else {
try { try {
// 构建完整目录:基准目录 + dir子目录 // 构建完整目录:基准目录 + dir子目录
@@ -144,8 +157,11 @@ public class FileStorageUtil {
filePath = dir + minIoUtils.minFileName(multipartFile.getOriginalFilename()); filePath = dir + minIoUtils.minFileName(multipartFile.getOriginalFilename());
obsUtil.uploadMultipart(multipartFile, filePath); obsUtil.uploadMultipart(multipartFile, filePath);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) { } else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
filePath = dir; filePath = dir.endsWith("/")?dir+getFileNameWithoutPath(multipartFile):dir+"/"+getFileNameWithoutPath(multipartFile);
aliYunOssUtils.uploadFile(dir, multipartFile); if (filePath.charAt(0) == '/') {
filePath= filePath.substring(1);
}
aliYunOssUtils.uploadFile(filePath, multipartFile);
} else { } else {
try { try {
//把名称存入数据 //把名称存入数据
@@ -157,6 +173,15 @@ public class FileStorageUtil {
} }
return filePath; return filePath;
} }
public static String getFileNameWithoutPath(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
return null;
}
// 统一分隔符为 '/',再取最后一部分
String normalized = originalFilename.replace('\\', '/');
return normalized.substring(normalized.lastIndexOf('/') + 1);
}
/*** /***
* 上传InputStream流 * 上传InputStream流
@@ -442,4 +467,62 @@ public class FileStorageUtil {
return file; return file;
} }
public void mkdir(String directoryPath) {
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
this.createDirectoryHW(directoryPath);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS) {
minIoUtils.createDirectory(minIossProperties.getBucket(), directoryPath);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
this.createDirectoryAli(directoryPath);
} else {
}
}
/**
* 华为文件服务器创建空目录
*
* @param dirPath
*/
private void createDirectoryHW(String dirPath) {
ObsClient obsClient = null;
try {
obsClient = this.huaweiObsProperties.getInstance();
String bucketName = this.huaweiObsProperties.getObs().getBucket();
// 确保路径以 / 结尾
String directoryKey = dirPath.endsWith("/") ? dirPath : dirPath + "/";
// 创建空对象作为目录占位符
InputStream emptyStream = new ByteArrayInputStream(new byte[0]);
PutObjectRequest request = new PutObjectRequest(bucketName, directoryKey, emptyStream);
obsClient.putObject(request);
log.info("已创建目录占位符:" + directoryKey);
} catch (Exception e) {
throw new RuntimeException("创建目录失败" + dirPath, e);
} finally {
this.huaweiObsProperties.destroy(obsClient);
}
}
/**
* 阿里云文件服务器创建空目录
*
* @param dirPath
*/
public void createDirectoryAli(String dirPath) {
try {
// 确保路径以 / 结尾,表示目录
String directoryKey = dirPath.endsWith("/") ? dirPath : dirPath + "/";
// 创建空输入流作为目录占位符
ByteArrayInputStream emptyStream = new ByteArrayInputStream(new byte[0]);
this.ossClient.putObject(this.ossConfig.getBucket(), directoryKey, emptyStream);
} catch (Exception e) {
throw new RuntimeException("创建目录失败:" + dirPath, e);
}
}
} }

View File

@@ -239,18 +239,47 @@ public class ExcelUtil {
* @param strings 下拉内容 * @param strings 下拉内容
*/ */
public static void selectList(Workbook workbook, int firstCol, int lastCol, String[] strings) { public static void selectList(Workbook workbook, int firstCol, int lastCol, String[] strings) {
Sheet sheet = workbook.getSheetAt(0); // Sheet sheet = workbook.getSheetAt(0);
// 生成下拉列表 // // 生成下拉列表
// 只对(xx)单元格有效 // // 只对(xx)单元格有效
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(2, 65535, firstCol, lastCol); // CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(2, 65535, firstCol, lastCol);
// 生成下拉框内容 // // 生成下拉框内容
DataValidationHelper dvHelper = sheet.getDataValidationHelper(); // DataValidationHelper dvHelper = sheet.getDataValidationHelper();
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) // XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
dvHelper.createExplicitListConstraint(strings); // dvHelper.createExplicitListConstraint(strings);
XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation( // XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(
dvConstraint, cellRangeAddressList); // dvConstraint, cellRangeAddressList);
// 对sheet页生效 // // 对sheet页生效
sheet.addValidationData(validation); // sheet.addValidationData(validation);
Sheet targetSheet = workbook.getSheetAt(0);
// ===================== 关键每个下拉用唯一名称的隐藏Sheet =====================
String uniqueHiddenName = "dropdown_" + firstCol + "_" + lastCol + "_" + System.currentTimeMillis();
Sheet hiddenSheet = workbook.createSheet(uniqueHiddenName);
// 隐藏数据源Sheet
workbook.setSheetHidden(workbook.getSheetIndex(hiddenSheet), true);
// 写入选项到隐藏Sheet
for (int i = 0; i < strings.length; i++) {
Row row = hiddenSheet.createRow(i);
Cell cell = row.createCell(0);
cell.setCellValue(strings[i]);
}
// 构造引用公式(无长度限制)
String formula = uniqueHiddenName + "!$A$1:$A$" + strings.length;
// 下拉作用范围第3行 ~ 65536行
CellRangeAddressList range = new CellRangeAddressList(2, 65535, firstCol, lastCol);
DataValidationHelper helper = targetSheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createFormulaListConstraint(formula);
DataValidation validation = helper.createValidation(constraint, range);
// 必加:防止下拉冲突、不显示
validation.setShowErrorBox(true);
validation.setShowPromptBox(true);
targetSheet.addValidationData(validation);
} }
/** /**

View File

@@ -4,13 +4,15 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import com.njcn.common.pojo.enums.response.CommonResponseEnum; import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import javax.servlet.ServletOutputStream; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Objects;
/** /**
* @author hongawen * @author hongawen
@@ -76,6 +78,59 @@ public class PoiUtil {
fileName = URLEncoder.encode(fileName, CharsetUtil.UTF_8); fileName = URLEncoder.encode(fileName, CharsetUtil.UTF_8);
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setContentType("application/octet-stream;charset=" + CharsetUtil.UTF_8); response.setContentType("application/octet-stream;charset=" + CharsetUtil.UTF_8);
//将带*号的列变成红色
Sheet sheetAt = workbook.getSheetAt(0);
//获取列数
int physicalNumberOfCells = sheetAt.getRow(0).getPhysicalNumberOfCells();
//没有表格标题,只有表格头
for (int i = 0; i < 2; i++) {
//获取行
Row row = sheetAt.getRow(i);
if (Objects.isNull(row)) {
continue;
}
for (int j = 0; j < physicalNumberOfCells; j++) {
//获取单元格对象
Cell cell = row.getCell(j);
//获取单元格样式对象
CellStyle cellStyle = workbook.createCellStyle();
//获取单元格内容对象
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 12);
//一定要装入 样式中才会生效
cellStyle.setFont(font);
//设置居中对齐
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//设置单元格字体颜色
cell.setCellStyle(cellStyle);
//获取当前值
String stringCellValue = cell.getStringCellValue();
if (stringCellValue.contains("*")) {
// 创建一个富文本
XSSFRichTextString xssfRichTextString = new XSSFRichTextString(stringCellValue);
int startIndex = stringCellValue.indexOf("*");
int entIndex = stringCellValue.lastIndexOf("*");
if (entIndex != 0) {
Font font3 = workbook.createFont();
font3.setFontHeightInPoints((short) 12);
font3.setColor(Font.COLOR_NORMAL);
xssfRichTextString.applyFont(0, entIndex, font3);
}
//设置带*样式
Font font1 = workbook.createFont();
font1.setFontHeightInPoints((short) 12);
font1.setColor(Font.COLOR_RED);
xssfRichTextString.applyFont(startIndex, entIndex + 1, font1);
//其他样式
Font font2 = workbook.createFont();
font2.setFontHeightInPoints((short) 12);
font2.setColor(Font.COLOR_NORMAL);
xssfRichTextString.applyFont(entIndex + 1, stringCellValue.length(), font2);
cell.setCellValue(xssfRichTextString);
}
}
}
workbook.write(outputStream); workbook.write(outputStream);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@@ -13,7 +13,7 @@ public interface AppRedisKey {
/** /**
* 设备模板前缀 * 设备模板前缀
*/ */
String MODEL = "MODEL"; String MODEL = "MODEL:";
/** /**
@@ -39,7 +39,7 @@ public interface AppRedisKey {
/** /**
* 监测点位置数据 * 监测点位置数据
*/ */
String LINE_POSITION = "LINEPOSITION"; String LINE_POSITION = "LINEPOSITION:";
/** /**
* rocketMQ消费key * rocketMQ消费key
@@ -115,4 +115,8 @@ public interface AppRedisKey {
* 补召文件 * 补召文件
*/ */
String MAKE_UP_FILES = "makeUpFilesKey:"; String MAKE_UP_FILES = "makeUpFilesKey:";
String COMMON_REQUEST = "commonRequestKey:";
String COMMON_RESOPNSE = "commonResponseKey:";
} }

View File

@@ -2,9 +2,7 @@ package com.njcn.redis.utils;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -326,12 +324,53 @@ public class RedisUtil {
*/ */
public List<?> getLikeListAllValues(String key) { public List<?> getLikeListAllValues(String key) {
List<Object> info = new ArrayList<>(); List<Object> info = new ArrayList<>();
for (String s : redisTemplate.keys(key + "*")) { // 使用 SCAN 替代 keys解决 Tair 禁用 KEYS 命令的问题
Set<String> keys = redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Set<String> keySet = new HashSet<>();
ScanOptions options = ScanOptions.scanOptions()
.match(key + "*")
.count(1000)
.build();
try (Cursor<byte[]> cursor = connection.scan(options)) {
while (cursor.hasNext()) {
keySet.add(new String(cursor.next()));
}
} catch (Exception e) {
throw new RuntimeException("Redis SCAN 模糊查询失败", e);
}
return keySet;
});
for (String s : keys) {
info.add(redisTemplate.opsForValue().get(s)); info.add(redisTemplate.opsForValue().get(s));
} }
return info; return info;
} }
/**
* 根据key模糊查询,并取出所有符合条件的key集合
* @return
*/
public Set<String> scanKeysByPattern(String pattern, int count) {
Set<String> keys = new HashSet<>();
ScanOptions options = ScanOptions.scanOptions()
.match(pattern)
.count(count)
.build();
try (Cursor<byte[]> cursor = redisTemplate.getConnectionFactory()
.getConnection()
.scan(options)) {
while (cursor.hasNext()) {
keys.add(new String(cursor.next()));
}
} catch (Exception e) {
throw new RuntimeException("扫描Redis keys失败", e);
}
return keys;
}
/** /**
* 数据切库 * 数据切库
* @param dbIndex * @param dbIndex

View File

@@ -1,5 +1,8 @@
package com.njcn.web.utils; package com.njcn.web.utils;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.*; import org.springframework.http.*;
@@ -149,7 +152,8 @@ public class RestTemplateUtil {
* @return ResponseEntity 响应对象封装类 * @return ResponseEntity 响应对象封装类
*/ */
public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType) { public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType) {
return restTemplate.postForEntity(url, requestBody, responseType); Object actualBody = convertHutoolJsonToStandard(requestBody);
return restTemplate.postForEntity(url, actualBody, responseType);
} }
/** /**
@@ -162,7 +166,8 @@ public class RestTemplateUtil {
* @return ResponseEntity 响应对象封装类 * @return ResponseEntity 响应对象封装类
*/ */
public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Object... uriVariables) { public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Object... uriVariables) {
return restTemplate.postForEntity(url, requestBody, responseType, uriVariables); Object actualBody = convertHutoolJsonToStandard(requestBody);
return restTemplate.postForEntity(url, actualBody, responseType, uriVariables);
} }
/** /**
@@ -175,7 +180,21 @@ public class RestTemplateUtil {
* @return ResponseEntity 响应对象封装类 * @return ResponseEntity 响应对象封装类
*/ */
public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
return restTemplate.postForEntity(url, requestBody, responseType, uriVariables); Object actualBody = convertHutoolJsonToStandard(requestBody);
return restTemplate.postForEntity(url, actualBody, responseType, uriVariables);
}
private static Object convertHutoolJsonToStandard(Object requestBody) {
if (requestBody instanceof JSONObject || requestBody instanceof JSONArray) {
try {
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
return objectMapper.readValue(JSONUtil.toJsonStr(requestBody), Object.class);
} catch (Exception e) {
log.warn("Hutool JSON转标准结构失败尝试直接使用字符串", e);
return requestBody;
}
}
return requestBody;
} }
/** /**

View File

@@ -19,14 +19,16 @@ public enum RunFlagEnum {
QUIT(4, "退运"), QUIT(4, "退运"),
POWER_FLAG(0,"电网侧"),
NO_POWER_FLAG(1,"非电网侧"),
GW_FLAG(0,"主网"), GW_FLAG(0,"主网"),
PW_FLAG(1,"配网"), PW_FLAG(1,"配网"),
I_SORT(1,"I类测点"),
II_SORT(2,"II类测点"),
III_SORT(3,"III类测点"),
; ;

View File

@@ -41,6 +41,11 @@ public class LineALLInfoDTO {
private Integer num; private Integer num;
@ApiModelProperty(name = "objName",value = "监测点对象名称") @ApiModelProperty(name = "objName",value = "监测点对象名称")
private String objName; private String objName;
@ApiModelProperty(name = "objName",value = "电网侧监测点对象名称Id")
private String objId;
@ApiModelProperty(name = "objName",value = "电网侧监测点对象名称")
private String objName2;
@ApiModelProperty(name = "loadType",value = "监测对象类型") @ApiModelProperty(name = "loadType",value = "监测对象类型")
private String loadType; private String loadType;
@ApiModelProperty(name = "voltageLevel",value = "电压等级") @ApiModelProperty(name = "voltageLevel",value = "电压等级")

View File

@@ -25,6 +25,9 @@ public class MonitorCommLedgerInfoDTO implements Serializable {
private String busBarName; private String busBarName;
private String objName;
private String voltageLevel; private String voltageLevel;
private String shortCapacity; private String shortCapacity;

View File

@@ -2,7 +2,6 @@ package com.njcn.device.biz.pojo.po;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.device.biz.utils.COverlimit;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;

View File

@@ -18,7 +18,8 @@ import java.util.Objects;
*/ */
public class COverlimitUtil { public class COverlimitUtil {
/** 配网占位默认值 */
private static final float PLACEHOLDER = -3.14159f;
/** /**
* 谐波电流系数 * 谐波电流系数
*/ */
@@ -34,15 +35,15 @@ public class COverlimitUtil {
/** /**
* 计算监测点限值 * 计算监测点限值
* @param voltageLevel 电压等级10kV = 10 220kV = 220 * @param voltageLevel 电压等级(kV)
* @param protocolCapacity 协议容量 * @param protocolCapacity 协议容量(MVA)
* @param devCapacity 设备容量 * @param devCapacity 供电设备容量(MVA),为空/0自动取对应电压默认值
* @param shortCapacity 短路容量 * @param shortCapacity 实际最小短路容量(MVA)
* @param powerFlag 0.用户侧 1.电网侧 * @param powerFlag 0=电网侧(不执行两步计算) 1=非电网侧/用户侧(执行两步计算)
* @param lineType 0.主网 1.配网 需要注意配网目前没有四种容量,谐波电流幅值限值,负序电流限值无法计算默认-3.14159 * @param pointClass 配网点类型 0=Ⅱ类 1=Ⅲ类光伏主网该字段传0即可
*/ */
public static Overlimit globalAssemble(Float voltageLevel, Float protocolCapacity, Float devCapacity, public static Overlimit globalAssemble(Float voltageLevel, Float protocolCapacity, Float devCapacity,
Float shortCapacity, Integer powerFlag, Integer lineType) { Float shortCapacity, Integer powerFlag,Integer pointClass) {
Overlimit overlimit = new Overlimit(); Overlimit overlimit = new Overlimit();
voltageDeviation(overlimit, voltageLevel); voltageDeviation(overlimit, voltageLevel);
frequency(overlimit); frequency(overlimit);
@@ -52,20 +53,56 @@ public class COverlimitUtil {
uHarm(overlimit, voltageLevel); uHarm(overlimit, voltageLevel);
threeVoltageUnbalance(overlimit); threeVoltageUnbalance(overlimit);
interharmonicCurrent(overlimit, voltageLevel); interharmonicCurrent(overlimit, voltageLevel);
negativeSequenceCurrent(overlimit, voltageLevel, shortCapacity);
//谐波电流限值
int lineType;
if (voltageLevel >= DicDataEnum.KV220.getValue()) {
lineType = 0; // 主网
} else {
lineType = 1; // 配网110、66、35、10kV
}
float sc = Objects.isNull(shortCapacity) ? 0f : shortCapacity;
float pc = Objects.isNull(protocolCapacity) ? 0f : protocolCapacity;
float dc;
if (Objects.isNull(devCapacity) || devCapacity <= 0) {
dc = getDefaultDevCapacity(voltageLevel);
} else {
dc = devCapacity;
}
// 1. 配网 lineType = 1
if (Objects.equals(lineType, RunFlagEnum.PW_FLAG.getStatus())) { if (Objects.equals(lineType, RunFlagEnum.PW_FLAG.getStatus())) {
//配网 Float[] iHarmTem = new Float[49];
// 配网-电网侧(powerFlag=0) / 配网Ⅱ类:直接基准限值,不折算
if (Objects.equals(powerFlag,RunFlagEnum.POWER_FLAG.getStatus()) || Objects.equals(pointClass, 0)) {
for (int i = 0; i <= 48; i++) {
iHarmTem[i] = getHarmTag(i + 2, voltageLevel).floatValue();
}
}
// 配网-非电网侧 且 Ⅲ类光伏两步计算折算系数固定为1
else {
float calCap = 1.0f;
for (int i = 0; i <= 48; i++) {
float inHarm = iHarmCalculate(i + 2, voltageLevel, pc, dc, calCap);
iHarmTem[i] = inHarm;
}
}
overlimit.buildIHarm(iHarmTem);
} else {
// 主网-电网侧(powerFlag=0):直接基准限值
if (Objects.equals(powerFlag, RunFlagEnum.POWER_FLAG.getStatus())) {
Float[] iHarmTem = new Float[49]; Float[] iHarmTem = new Float[49];
for (int i = 0; i <= 48; i++) { for (int i = 0; i <= 48; i++) {
//目前只处理了配网II类测点III类测点暂未处理III类测点参考主网
iHarmTem[i] = getHarmTag(i + 2, voltageLevel).floatValue(); iHarmTem[i] = getHarmTag(i + 2, voltageLevel).floatValue();
} }
overlimit.buildIHarm(iHarmTem); overlimit.buildIHarm(iHarmTem);
overlimit.setINeg(-3.14159f); }
}else { // 主网-非电网侧/用户侧(风光场站):完整两步计算
//主网 else {
iHarm(overlimit, voltageLevel, protocolCapacity, devCapacity, shortCapacity); iHarm(overlimit, voltageLevel, pc, dc, sc);
negativeSequenceCurrent(overlimit, voltageLevel, shortCapacity); }
} }
return overlimit; return overlimit;
} }
@@ -304,6 +341,30 @@ public class COverlimitUtil {
} }
/**
* 根据电压等级获取【默认公共连接点供电设备容量】St(MVA)
* 无实际台账容量时兜底使用
*/
public static float getDefaultDevCapacity(Float voltageLevel) {
if (voltageLevel < 0.4f) {
return 1.0f;
} else if (voltageLevel < 6f) {
return 100f;
} else if (voltageLevel < 20f) {
return 200f;
} else if (voltageLevel < 35f) {
return 500f;
} else if (voltageLevel < 66f) {
return 800f;
} else if (voltageLevel < 110f) {
return 1000f;
} else if (voltageLevel < 220f) {
return 2000f;
} else {
return 3000f;
}
}
/*---------------------------------谐波电流限值end-----------------------------------*/ /*---------------------------------谐波电流限值end-----------------------------------*/
@@ -376,8 +437,9 @@ public class COverlimitUtil {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("sss"); System.out.println("sss");
float aa = iHarmCalculate(9,500f,10,10,0.002222222222f); Overlimit overlimit = new Overlimit();
iHarm(overlimit, 220f, 100f, 100f, 2000f);
System.out.println(aa); System.out.println(overlimit);
} }
} }

View File

@@ -22,65 +22,65 @@ import java.math.BigDecimal;
public class TerminalBaseExcel implements Serializable { public class TerminalBaseExcel implements Serializable {
@Excel(name = "项目", width = 15) @Excel(name = "*项目", width = 15)
@NotBlank(message = DeviceValidMessage.PROJECT_NAME_NOT) @NotBlank(message = DeviceValidMessage.PROJECT_NAME_NOT)
@Pattern(regexp = PatternRegex.DEPT_NAME_REGEX, message = DeviceValidMessage.PROJECT_NAME_RULE) @Pattern(regexp = PatternRegex.DEPT_NAME_REGEX, message = DeviceValidMessage.PROJECT_NAME_RULE)
private String projectName; private String projectName;
@Excel(name = "工程", width = 15) @Excel(name = "*省份", width = 15)
@NotBlank(message = DeviceValidMessage.PROVINCE_NAME_NOT) @NotBlank(message = DeviceValidMessage.PROVINCE_NAME_NOT)
private String provinceName; private String provinceName;
@Excel(name = "单位", width = 15) @Excel(name = "*供电公司", width = 15)
@NotBlank(message = "供电公司名称") @NotBlank(message = "供电公司名称")
@Pattern(regexp = PatternRegex.DEV_NAME_REGEX, message = "供电公司名称违规") @Pattern(regexp = PatternRegex.DEV_NAME_REGEX, message = "供电公司名称违规")
private String gdName; private String gdName;
@Excel(name = "部门", width = 15) @Excel(name = "*变电站", width = 15)
@NotBlank(message = "变电站名称不可为空") @NotBlank(message = "变电站名称不可为空")
@Pattern(regexp = PatternRegex.DEV_NAME_REGEX, message = "变电站名称违规") @Pattern(regexp = PatternRegex.DEV_NAME_REGEX, message = "变电站名称违规")
private String substationName; private String substationName;
@Excel(name = "部门电压等级", width = 15) @Excel(name = "*变电站电压等级", width = 15)
@NotBlank(message = "电压等级不可为空") @NotBlank(message = "变电站电压等级不可为空")
private String subStationScale; private String subStationScale;
@Excel(name = "经度", width = 15) @Excel(name = "*经度", width = 15)
private BigDecimal lng; private BigDecimal lng;
@Excel(name = "纬度", width = 15) @Excel(name = "*纬度", width = 15)
private BigDecimal lat; private BigDecimal lat;
@Excel(name = "终端", width = 15) @Excel(name = "*装置名称", width = 15)
@Pattern(regexp = PatternRegex.DEV_NAME_REGEX, message = "设备名称违规") @Pattern(regexp = PatternRegex.DEV_NAME_REGEX, message = "装置名称违规")
private String deviceName; private String deviceName;
@Excel(name = "终端模型", replace = {"虚拟设备_0", "实际设备_1", "离线设备_2"}, width = 15) @Excel(name = "*终端模型", replace = {"虚拟设备_0", "实际设备_1", "离线设备_2"}, width = 15)
@NotNull(message = "设备模型不能为空") @NotNull(message = "设备模型不能为空")
private Integer devModel; private Integer devModel;
@Excel(name = "数据类型", replace = {"暂态系统_0", "稳态系统_1", "双系统_2"}, width = 15) @Excel(name = "*数据类型", replace = {"暂态系统_0", "稳态系统_1", "双系统_2"}, width = 15)
@NotNull(message = "数据类型不能为空") @NotNull(message = "数据类型不能为空")
private Integer devDataType; private Integer devDataType;
@Excel(name = "运行状态", replace = {"投运_0", "热备用_1", "停运_2"}, width = 15) @Excel(name = "*运行状态", replace = {"投运_0", "热备用_1", "停运_2"}, width = 15)
@NotNull(message = "运行状态不能为空") @NotNull(message = "运行状态不能为空")
private Integer runFlag; private Integer runFlag;
@Excel(name = "终端厂家", width = 15) @Excel(name = "*终端厂家", width = 15)
@NotBlank(message = "终端厂家不能为空") @NotBlank(message = "终端厂家不能为空")
private String manufacturer; private String manufacturer;
@Excel(name = "设备型号", width = 15) @Excel(name = "*设备型号", width = 15)
@NotBlank(message = "设备型号不能为空") @NotBlank(message = "设备型号不能为空")
private String devType; private String devType;
@Excel(name = "网络参数", width = 15) @Excel(name = "*网络参数", width = 15)
@NotBlank(message = "设备网络参数不能为空") @NotBlank(message = "设备网络参数不能为空")
private String ip; private String ip;
@Excel(name = "端口", width = 15) @Excel(name = "*端口", width = 15)
@Range(min = 1, max = 100000, message = "端口号违规") @Range(min = 1, max = 100000, message = "端口号违规")
@NotNull(message = "设备端口号不能为空") @NotNull(message = "设备端口号不能为空")
private Integer port; private Integer port;
@@ -91,15 +91,15 @@ public class TerminalBaseExcel implements Serializable {
@Excel(name = "终端秘钥", width = 15) @Excel(name = "终端秘钥", width = 15)
private String devKey; private String devKey;
@Excel(name = "召唤标志",replace = {"周期触发_0", "变为触发_1"}, width = 15) @Excel(name = "*召唤标志",replace = {"周期触发_0", "变为触发_1"}, width = 15)
@NotNull(message = "召唤标志不为空") @NotNull(message = "召唤标志不为空")
private Integer callFlag; private Integer callFlag;
@Excel(name = "前置名称", width = 15) @Excel(name = "*前置名称", width = 15)
@NotBlank(message = "前置名称不能为空") @NotBlank(message = "前置名称不能为空")
private String nodeName; private String nodeName;
@Excel(name = "前置类型", width = 15) @Excel(name = "*前置类型", width = 15)
@NotBlank(message = "前置类型不能为空") @NotBlank(message = "前置类型不能为空")
private String frontType; private String frontType;
@@ -109,71 +109,71 @@ public class TerminalBaseExcel implements Serializable {
@Excel(name = "SIM卡号", width = 15) @Excel(name = "SIM卡号", width = 15)
private String sim; private String sim;
@Excel(name = "母线", width = 15) @Excel(name = "*母线", width = 15)
@NotBlank(message = "母线名称不能为空") @NotBlank(message = "母线名称不能为空")
private String subvName; private String subvName;
@Excel(name = "母线号", width = 15) @Excel(name = "*母线号", width = 15)
@NotNull(message = "母线号不为空") @NotNull(message = "母线号不为空")
private Integer subvNum; private Integer subvNum;
@Excel(name = "母线电压等级", width = 15) @Excel(name = "*母线电压等级", width = 15)
@NotBlank(message = "母线电压等级不能为空") @NotBlank(message = "母线电压等级不能为空")
private String subvScale; private String subvScale;
@Excel(name = "母线模型", replace = {"虚拟母线_0", "实际母线_1"}, width = 15) @Excel(name = "*母线模型", replace = {"虚拟母线_0", "实际母线_1"}, width = 15)
@NotNull(message = "母线模型不为空") @NotNull(message = "母线模型不为空")
private Integer subvModel; private Integer subvModel;
@Excel(name = "监测点名称", width = 15) @Excel(name = "*监测点名称", width = 15)
@NotBlank(message = "监测点名称不能为空") @NotBlank(message = "监测点名称不能为空")
private String lineName; private String lineName;
@Excel(name = "监测点线路号", width = 15) @Excel(name = "*监测点线路号", width = 15)
@NotNull(message = "监测点线路号不为空") @NotNull(message = "监测点线路号不为空")
private Integer lineNum; private Integer lineNum;
@Excel(name = "监测点等级", width = 15) @Excel(name = "*监测点等级", width = 15)
private String lineGrade; private String lineGrade;
@Excel(name = "pt", width = 20) @Excel(name = "*pt(格式pt1/pt2)", width = 20)
@NotBlank(message = "pt不能为空") @NotBlank(message = "pt不能为空")
private String pt; private String pt;
@Excel(name = "ct", width = 20) @Excel(name = "*ct(格式ct1/ct2)", width = 20)
@NotBlank(message = "ct不能为空") @NotBlank(message = "ct不能为空")
private String ct; private String ct;
@Excel(name = "设备容量", width = 15) @Excel(name = "*设备容量", width = 15)
@NotNull(message = "设备容量不为空") @NotNull(message = "设备容量不为空")
private Float devCapacity; private Float devCapacity;
@Excel(name = "短路容量", width = 15) @Excel(name = "*短路容量", width = 15)
@NotNull(message = "短路容量不为空") @NotNull(message = "短路容量不为空")
private Float shortCapacity; private Float shortCapacity;
@Excel(name = "基准容量", width = 15) @Excel(name = "*基准容量", width = 15)
@NotNull(message = "基准容量不为空") @NotNull(message = "基准容量不为空")
private Float standardCapacity; private Float standardCapacity;
@Excel(name = "协议容量", width = 15) @Excel(name = "*协议容量", width = 15)
@NotNull(message = "协议容量不为空") @NotNull(message = "协议容量不为空")
private Float dealCapacity; private Float dealCapacity;
@Excel(name = "接线方式", replace = {"星型接法_0", "三角型接法_1", "开口三角型接法_2"}, width = 15) @Excel(name = "*接线方式", replace = {"星型接法_0", "三角型接法_1", "开口三角型接法_2"}, width = 15)
@NotNull(message = "接线方式不为空") @NotNull(message = "接线方式不为空")
private Integer ptType; private Integer ptType;
@Excel(name = "测量间隔", width = 15) @Excel(name = "*测量间隔", width = 15)
@NotNull(message = "测量间隔不为空") @NotNull(message = "测量间隔不为空")
private Integer timeInterval; private Integer timeInterval;
@Excel(name = "干扰源类型", width = 15) @Excel(name = "*干扰源类型", width = 15)
@NotBlank(message = "干扰源类型不为空") @NotBlank(message = "干扰源类型不为空")
private String loadType; private String loadType;
@Excel(name = "行业类型", width = 15) @Excel(name = "*行业类型", width = 15)
@NotBlank(message = "行业类型不为空") @NotBlank(message = "行业类型不为空")
private String businessType; private String businessType;
@@ -183,11 +183,11 @@ public class TerminalBaseExcel implements Serializable {
@Excel(name = "监测点对象名称", width = 15) @Excel(name = "监测点对象名称", width = 15)
private String objName; private String objName;
@Excel(name = "电网侧标志", replace = {"电网侧_0", "非电网侧_1"}, width = 15) @Excel(name = "*电网侧标志", replace = {"电网侧_0", "非电网侧_1"}, width = 15)
@NotNull(message = "电网侧标志不为空") @NotNull(message = "电网侧标志不为空")
private Integer powerFlag; private Integer powerFlag;
@Excel(name = "人为干预统计", replace = {"不参与统计_0", "参与统计_1"}, width = 15) @Excel(name = "*人为干预统计", replace = {"不参与统计_0", "参与统计_1"}, width = 15)
@NotNull(message = "统计标志不为空") @NotNull(message = "统计标志不为空")
private Integer statFlag; private Integer statFlag;

View File

@@ -0,0 +1,19 @@
package com.njcn.device.pq.pojo.param;
import lombok.Data;
/**
* Description:请求装置文件系统参数
* Date: 2026/04/30 上午 10:51【需求编号】
*
* @author clam
* @version V1.0.0
*/
@Data
public class AskFileSysParam {
private String devId;
private String path;
private String remotePath;
}

View File

@@ -1,6 +1,8 @@
package com.njcn.device.pq.pojo.po; package com.njcn.device.pq.pojo.po;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
@@ -17,6 +19,7 @@ import java.io.Serializable;
public class DeviceProcess implements Serializable { public class DeviceProcess implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
//设备id //设备id
@TableId("Id")
private String id; private String id;
//设备设备所在前置机进程号 //设备设备所在前置机进程号
private Integer processNo; private Integer processNo;

View File

@@ -105,6 +105,12 @@ public class LineDetailVO implements Serializable {
@ApiModelProperty(name = "终端厂家") @ApiModelProperty(name = "终端厂家")
private String manufacturer; private String manufacturer;
@ApiModelProperty(name = "监测对象ID")
private String objId;
@ApiModelProperty(name = "监测对象名称")
private String objName;
} }
@Data @Data

View File

@@ -125,6 +125,8 @@ public class LineIntegrityDataVO implements Serializable {
private Integer algoDescribe; private Integer algoDescribe;
@ApiModelProperty(name = "devType",value = "终端型号")
private String devType;
@ApiModelProperty(name = "loadType",value = "干扰源类型") @ApiModelProperty(name = "loadType",value = "干扰源类型")
private String loadType; private String loadType;

View File

@@ -116,6 +116,9 @@ public class DeviceOnlineRate {
@ApiModelProperty("监测点名称") @ApiModelProperty("监测点名称")
private String lineName; private String lineName;
@ApiModelProperty("监测对象")
private String objName;
@ApiModelProperty("监测点运行状态") @ApiModelProperty("监测点运行状态")
private String runFlag; private String runFlag;

View File

@@ -90,7 +90,7 @@ public class LineIntegrityDataController extends BaseController {
String methodDescribe = getMethodDescribe("getIntegrityByLineIds"); String methodDescribe = getMethodDescribe("getIntegrityByLineIds");
if(CollUtil.isNotEmpty(lineIds)){ if(CollUtil.isNotEmpty(lineIds)){
QueryWrapper<RStatIntegrityD> queryWrapper = new QueryWrapper<>(); QueryWrapper<RStatIntegrityD> queryWrapper = new QueryWrapper<>();
queryWrapper.select("sum(real_time) as realTime,sum(due_time) as dueTime,sum(real_time)/sum(due_time) as integrityData","line_index").in("line_index",lineIds).between("time_id",startTime,endTime).groupBy("line_index"); queryWrapper.select("sum(real_time) as realTime,sum(due_time) as dueTime,avg(real_time*1.0/due_time) as integrityData","line_index").in("line_index",lineIds).between("time_id",startTime,endTime).groupBy("line_index");
List<RStatIntegrityD> rStatIntegrityDList = irStatIntegrityDService.list(queryWrapper); List<RStatIntegrityD> rStatIntegrityDList = irStatIntegrityDService.list(queryWrapper);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, rStatIntegrityDList, methodDescribe); return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, rStatIntegrityDList, methodDescribe);
} }
@@ -154,7 +154,6 @@ public class LineIntegrityDataController extends BaseController {
@ApiOperation("监测点数据完整性(冀北)") @ApiOperation("监测点数据完整性(冀北)")
@ApiImplicitParam(name = "param", value = "参数实体", required = true) @ApiImplicitParam(name = "param", value = "参数实体", required = true)
public HttpResult<DeviceOnlineRate> getData(@RequestBody DeviceInfoParam.BusinessParam param) { public HttpResult<DeviceOnlineRate> getData(@RequestBody DeviceInfoParam.BusinessParam param) {
param.setLineOrDevice(0);
String methodDescribe = getMethodDescribe("getData"); String methodDescribe = getMethodDescribe("getData");
DeviceOnlineRate rate = irStatIntegrityDService.getData(param); DeviceOnlineRate rate = irStatIntegrityDService.getData(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, rate, methodDescribe); return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, rate, methodDescribe);

View File

@@ -6,14 +6,14 @@ package com.njcn.device.pq.controller;
* @Description: 异常告警数据指标范围 * @Description: 异常告警数据指标范围
*/ */
import com.njcn.algorithm.pojo.dto.PqReasonableRangeDto;
import com.njcn.algorithm.pojo.param.DataCleanParam;
import com.njcn.common.pojo.annotation.OperateInfo; import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType; import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum; import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum; import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult; import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil; import com.njcn.common.utils.HttpResultUtil;
import com.njcn.dataProcess.param.DataCleanParam;
import com.njcn.dataProcess.pojo.dto.PqReasonableRangeDto;
import com.njcn.device.pq.service.ReasonableRangeService; import com.njcn.device.pq.service.ReasonableRangeService;
import com.njcn.web.controller.BaseController; import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;

View File

@@ -0,0 +1,181 @@
package com.njcn.device.pq.controller.file;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.IdUtil;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.device.device.service.DeviceProcessService;
import com.njcn.device.device.service.IDeviceService;
import com.njcn.device.pq.pojo.param.AskFileSysParam;
import com.njcn.device.pq.pojo.po.Device;
import com.njcn.device.pq.pojo.po.DeviceProcess;
import com.njcn.message.api.ProduceFeignClient;
import com.njcn.message.message.AskFileSysMessage;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
/**
* Description:
* Date: 2026/04/29 上午 11:41【需求编号】
*
* @author clam
* @version V1.0.0
*/
@RestController
@RequestMapping("/dir")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "装置文件系统")
public class DirectoryController extends BaseController {
private final ProduceFeignClient produceFeignClient;
private final PendingRequestManager pendingRequestManager;
private final IDeviceService iDeviceService;
private final DeviceProcessService deviceProcessService;
@PostMapping("/list")
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("获取装置文件目录")
public DeferredResult<Object> listDirectory(@RequestBody AskFileSysParam askFileSysParam) {
String methodDescribe = getMethodDescribe("listDirectory");
long timeoutMs = 15000L; // 15 秒超时
// 构造指令 body
Device device = iDeviceService.getById(askFileSysParam.getDevId());
DeviceProcess deviceProcess = deviceProcessService.getById(askFileSysParam.getDevId());
// 发送 MQ 指令,获取 msgId
AskFileSysMessage askFileSysMessage = new AskFileSysMessage();
askFileSysMessage.setGuid(IdUtil.simpleUUID());
askFileSysMessage.setNodeId(device.getNodeId());
askFileSysMessage.setProcessNo(deviceProcess.getProcessNo());
askFileSysMessage.setDevId(askFileSysParam.getDevId());
askFileSysMessage.setType(0);
askFileSysMessage.setPath(askFileSysParam.getPath());
produceFeignClient.askFileSys(askFileSysMessage);
// 创建挂起请求
DeferredResult<Object> deferredResult = pendingRequestManager.createPendingRequest(askFileSysMessage.getGuid(), timeoutMs);
// 可额外在 Redis 中记录初始状态(可选)
// 返回 DeferredResultSpring 将挂起此请求
return deferredResult;
}
@PostMapping("/downLoadFile")
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("获取装置文件文件")
public DeferredResult<Object> downLoadFile(@RequestBody AskFileSysParam askFileSysParam) {
String methodDescribe = getMethodDescribe("downLoadFile");
long timeoutMs = 15000L; // 15 秒超时
// 构造指令 body
Device device = iDeviceService.getById(askFileSysParam.getDevId());
DeviceProcess deviceProcess = deviceProcessService.getById(askFileSysParam.getDevId());
// 发送 MQ 指令,获取 msgId
AskFileSysMessage askFileSysMessage = new AskFileSysMessage();
askFileSysMessage.setGuid(IdUtil.simpleUUID());
askFileSysMessage.setNodeId(device.getNodeId());
askFileSysMessage.setProcessNo(deviceProcess.getProcessNo());
askFileSysMessage.setDevId(askFileSysParam.getDevId());
askFileSysMessage.setType(1);
askFileSysMessage.setPath(askFileSysParam.getPath());
produceFeignClient.askFileSys(askFileSysMessage);
// 创建挂起请求
DeferredResult<Object> deferredResult = pendingRequestManager.createPendingRequest(askFileSysMessage.getGuid(), timeoutMs);
// 可额外在 Redis 中记录初始状态(可选)
// 返回 DeferredResultSpring 将挂起此请求
return deferredResult;
}
@PostMapping("/upLoadFile")
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("上传装置文件文件")
public DeferredResult<Object> upLoadFile(@RequestBody AskFileSysParam askFileSysParam) {
String methodDescribe = getMethodDescribe("upLoadFile");
long timeoutMs = 15000L; // 15 秒超时
// 构造指令 body
Device device = iDeviceService.getById(askFileSysParam.getDevId());
DeviceProcess deviceProcess = deviceProcessService.getById(askFileSysParam.getDevId());
// 发送 MQ 指令,获取 msgId
AskFileSysMessage askFileSysMessage = new AskFileSysMessage();
askFileSysMessage.setGuid(IdUtil.simpleUUID());
askFileSysMessage.setNodeId(device.getNodeId());
askFileSysMessage.setProcessNo(deviceProcess.getProcessNo());
askFileSysMessage.setDevId(askFileSysParam.getDevId());
askFileSysMessage.setType(2);
askFileSysMessage.setPath(askFileSysParam.getPath());
askFileSysMessage.setRemotePath(askFileSysParam.getRemotePath());
produceFeignClient.askFileSys(askFileSysMessage);
// 创建挂起请求
DeferredResult<Object> deferredResult = pendingRequestManager.createPendingRequest(askFileSysMessage.getGuid(), timeoutMs);
// 可额外在 Redis 中记录初始状态(可选)
// 返回 DeferredResultSpring 将挂起此请求
return deferredResult;
}
@PostMapping("/delete")
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("装置目录,文件删除")
public DeferredResult<Object> delete(@RequestBody AskFileSysParam askFileSysParam) {
String methodDescribe = getMethodDescribe("delete");
long timeoutMs = 15000L; // 15 秒超时
// 构造指令 body
Device device = iDeviceService.getById(askFileSysParam.getDevId());
DeviceProcess deviceProcess = deviceProcessService.getById(askFileSysParam.getDevId());
// 发送 MQ 指令,获取 msgId
AskFileSysMessage askFileSysMessage = new AskFileSysMessage();
askFileSysMessage.setGuid(IdUtil.simpleUUID());
askFileSysMessage.setNodeId(device.getNodeId());
askFileSysMessage.setProcessNo(deviceProcess.getProcessNo());
askFileSysMessage.setDevId(askFileSysParam.getDevId());
askFileSysMessage.setType(3);
askFileSysMessage.setPath(askFileSysParam.getPath());
askFileSysMessage.setRemotePath(askFileSysParam.getRemotePath());
produceFeignClient.askFileSys(askFileSysMessage);
// 创建挂起请求
DeferredResult<Object> deferredResult = pendingRequestManager.createPendingRequest(askFileSysMessage.getGuid(), timeoutMs);
// 可额外在 Redis 中记录初始状态(可选)
// 返回 DeferredResultSpring 将挂起此请求
return deferredResult;
}
@PostMapping("/restart")
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("装置重启")
public DeferredResult<Object> restart(@RequestBody AskFileSysParam askFileSysParam) {
String methodDescribe = getMethodDescribe("restart");
long timeoutMs = 15000L; // 15 秒超时
// 构造指令 body
Device device = iDeviceService.getById(askFileSysParam.getDevId());
DeviceProcess deviceProcess = deviceProcessService.getById(askFileSysParam.getDevId());
// 发送 MQ 指令,获取 msgId
AskFileSysMessage askFileSysMessage = new AskFileSysMessage();
askFileSysMessage.setGuid(IdUtil.simpleUUID());
askFileSysMessage.setNodeId(device.getNodeId());
askFileSysMessage.setProcessNo(deviceProcess.getProcessNo());
askFileSysMessage.setDevId(askFileSysParam.getDevId());
askFileSysMessage.setPath("reboot");
askFileSysMessage.setType(4);
produceFeignClient.askFileSys(askFileSysMessage);
// 创建挂起请求
DeferredResult<Object> deferredResult = pendingRequestManager.createPendingRequest(askFileSysMessage.getGuid(), timeoutMs);
// 可额外在 Redis 中记录初始状态(可选)
// 返回 DeferredResultSpring 将挂起此请求
return deferredResult;
}
}

View File

@@ -0,0 +1,61 @@
package com.njcn.device.pq.controller.file;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.HttpResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.concurrent.ConcurrentHashMap;
@Component
@Slf4j
public class PendingRequestManager {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 本地映射msgId -> DeferredResult主要用于超时清理和主动完成
private final ConcurrentHashMap<String, DeferredResult<Object>> deferredResultMap = new ConcurrentHashMap<>();
// 创建挂起请求
public DeferredResult<Object> createPendingRequest(String msgId, long timeoutMs) {
DeferredResult<Object> deferredResult = new DeferredResult<>(timeoutMs);
// 超时回调
deferredResult.onTimeout(() -> {
// 清理 Redis 中的等待记录
redisTemplate.delete("pending:" + msgId);
deferredResultMap.remove(msgId);
deferredResult.setErrorResult(new BusinessException("前置超时...."));
});
// 完成回调(正常或异常后移出本地映射)
deferredResult.onCompletion(() -> deferredResultMap.remove(msgId));
deferredResultMap.put(msgId, deferredResult);
return deferredResult;
}
// 收到 Redis 通知后,根据 msgId 完成请求
public void completeRequest(String msgId) {
if (deferredResultMap.containsKey(msgId)) {
DeferredResult<Object> deferredResult = deferredResultMap.get(msgId);
// 从 Redis 中获取结果内容
String key = "pending:" + msgId;
Object result = redisTemplate.opsForValue().get(key);
if (result != null) {
deferredResult.setResult( HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result,""));
} else {
log.info("Receive notification for unknown msgId: " + msgId);
deferredResult.setErrorResult(new BusinessException("前置未返回结果"));
}
// 清理 Redis 中的记录(可选,利用过期时间自动删除也可)
redisTemplate.delete(key);
} else {
// 可能请求已超时被移除了,仅记录日志即可
log.info("Receive notification for unknown msgId: " + msgId);
}
}
}

View File

@@ -0,0 +1,20 @@
package com.njcn.device.pq.controller.file;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
@Component
public class RedisMessageSubscriber implements MessageListener {
@Autowired
private PendingRequestManager pendingRequestManager;
@Override
public void onMessage(Message message, byte[] pattern) {
String msgId = new String(message.getBody(), StandardCharsets.UTF_8);
pendingRequestManager.completeRequest(msgId);
}
}

View File

@@ -0,0 +1,44 @@
package com.njcn.device.pq.controller.file;
import com.njcn.redis.config.RedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;
import org.springframework.data.redis.connection.MessageListener;
import java.nio.charset.StandardCharsets;
/**
* Description:
* Date: 2026/04/29 下午 3:37【需求编号】
*
* @author clam
* @version V1.0.0
*/
@Configuration
@Import(RedisConfig.class) // 引入公共配置
public class RedisSubscriptionConfig {
@Bean
public RedisMessageListenerContainer redisContainer(
RedisConnectionFactory connectionFactory,
MessageListenerAdapter resultListenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(resultListenerAdapter, new ChannelTopic("result_ready_channel"));
return container;
}
@Bean
public MessageListenerAdapter resultListenerAdapter(RedisMessageSubscriber subscriber) {
return new MessageListenerAdapter(subscriber, "onMessage");
}
}

View File

@@ -10,9 +10,11 @@ import com.njcn.device.node.mapper.NodeMapper;
import com.njcn.device.pq.pojo.po.Device; import com.njcn.device.pq.pojo.po.Device;
import com.njcn.device.pq.pojo.po.DeviceProcess; import com.njcn.device.pq.pojo.po.DeviceProcess;
import com.njcn.device.pq.pojo.po.Node; import com.njcn.device.pq.pojo.po.Node;
import com.njcn.message.constant.RedisKeyPrefix;
import com.njcn.redis.utils.RedisUtil; import com.njcn.redis.utils.RedisUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -21,6 +23,7 @@ import org.springframework.util.CollectionUtils;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -33,6 +36,7 @@ import java.util.stream.Collectors;
@Component @Component
@EnableScheduling @EnableScheduling
@RequiredArgsConstructor @RequiredArgsConstructor
@ConditionalOnProperty(name = "business.task-enabled", havingValue = "true", matchIfMissing = true)
public class DeviceComflagTasks { public class DeviceComflagTasks {
private final NodeMapper nodeMapper; private final NodeMapper nodeMapper;
private final IDeviceService iDeviceService; private final IDeviceService iDeviceService;
@@ -63,8 +67,17 @@ public class DeviceComflagTasks {
pqsCommunicateDto.setTime(LocalDateTimeUtil.now().format(DatePattern.NORM_DATETIME_FORMATTER)); pqsCommunicateDto.setTime(LocalDateTimeUtil.now().format(DatePattern.NORM_DATETIME_FORMATTER));
pqsCommunicateDto.setDevId(temp); pqsCommunicateDto.setDevId(temp);
pqsCommunicateDto.setType(0); pqsCommunicateDto.setType(0);
//获取之前设备状态
String devFalg =redisUtil.getStringByKey(RedisKeyPrefix.DEVICE_RUN_FLAG.concat(temp));
if(StringUtils.isBlank(devFalg)||(!Objects.equals(Integer.valueOf(devFalg),pqsCommunicateDto.getType()))){
//状态翻转
redisUtil.saveByKey(RedisKeyPrefix.DEVICE_RUN_FLAG.concat(temp),pqsCommunicateDto.getType()+"");
pqsCommunicateFeignClient.insertion(pqsCommunicateDto) ; pqsCommunicateFeignClient.insertion(pqsCommunicateDto) ;
}
}); });
} }

View File

@@ -1,7 +1,7 @@
package com.njcn.device.pq.mapper; package com.njcn.device.pq.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.dataProcess.pojo.po.PqReasonableRange; import com.njcn.algorithm.pojo.po.PqReasonableRange;
/** /**
* <p> * <p>

View File

@@ -84,6 +84,7 @@
pldsdd.id AS lineGrade, pldsdd.id AS lineGrade,
pldsdd.Algo_Describe AS algoDescribe, pldsdd.Algo_Describe AS algoDescribe,
pld.Load_Type AS loadType, pld.Load_Type AS loadType,
pd.Dev_Type AS devType,
pld.obj_id as objId pld.obj_id as objId
FROM FROM
pq_line AS line pq_line AS line

View File

@@ -1,9 +1,10 @@
package com.njcn.device.pq.service; package com.njcn.device.pq.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.dataProcess.param.DataCleanParam; import com.njcn.algorithm.pojo.dto.PqReasonableRangeDto;
import com.njcn.dataProcess.pojo.dto.PqReasonableRangeDto; import com.njcn.algorithm.pojo.param.DataCleanParam;
import com.njcn.dataProcess.pojo.po.PqReasonableRange; import com.njcn.algorithm.pojo.po.PqReasonableRange;
import java.util.List; import java.util.List;

View File

@@ -9,20 +9,17 @@ import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray; import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.algorithm.pojo.api.PqReasonableRangeFeignClient;
import com.njcn.algorithm.pojo.dto.PqReasonableRangeDto;
import com.njcn.algorithm.pojo.param.DataCleanParam;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.dataProcess.api.DataLimitRateDetailFeignClient; import com.njcn.dataProcess.api.DataLimitRateDetailFeignClient;
import com.njcn.dataProcess.api.DataLimitRateFeignClient; import com.njcn.dataProcess.api.DataLimitRateFeignClient;
import com.njcn.dataProcess.api.DataLimitTargetFeignClient; import com.njcn.dataProcess.api.DataLimitTargetFeignClient;
import com.njcn.dataProcess.api.PqReasonableRangeFeignClient;
import com.njcn.dataProcess.enums.DataCleanEnum; import com.njcn.dataProcess.enums.DataCleanEnum;
import com.njcn.dataProcess.param.DataCleanParam;
import com.njcn.dataProcess.param.LineCountEvaluateParam; import com.njcn.dataProcess.param.LineCountEvaluateParam;
import com.njcn.dataProcess.pojo.dto.DataLimitRateDetailDto; import com.njcn.dataProcess.pojo.dto.DataLimitRateDetailDto;
import com.njcn.dataProcess.pojo.dto.DataLimitRateDto;
import com.njcn.dataProcess.pojo.dto.DataLimitTargetDto; import com.njcn.dataProcess.pojo.dto.DataLimitTargetDto;
import com.njcn.dataProcess.pojo.dto.PqReasonableRangeDto;
import com.njcn.device.biz.enums.DeviceResponseEnum;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.biz.pojo.po.Overlimit; import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.device.line.mapper.LineMapper; import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.line.service.DeptLineService; import com.njcn.device.line.service.DeptLineService;

View File

@@ -19,12 +19,12 @@ import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.algorithm.pojo.api.PqReasonableRangeFeignClient;
import com.njcn.algorithm.pojo.dto.PqReasonableRangeDto;
import com.njcn.algorithm.pojo.param.DataCleanParam;
import com.njcn.common.pojo.dto.SimpleDTO; import com.njcn.common.pojo.dto.SimpleDTO;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.dataProcess.api.PqReasonableRangeFeignClient;
import com.njcn.dataProcess.enums.DataCleanEnum; import com.njcn.dataProcess.enums.DataCleanEnum;
import com.njcn.dataProcess.param.DataCleanParam;
import com.njcn.dataProcess.pojo.dto.PqReasonableRangeDto;
import com.njcn.device.common.mapper.onlinerate.OnLineRateMapper; import com.njcn.device.common.mapper.onlinerate.OnLineRateMapper;
import com.njcn.device.common.service.GeneralDeviceService; import com.njcn.device.common.service.GeneralDeviceService;
import com.njcn.device.line.mapper.LineMapper; import com.njcn.device.line.mapper.LineMapper;

View File

@@ -2,12 +2,15 @@ package com.njcn.device.pq.service.impl;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl; import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.device.biz.commApi.CommLineClient;
import com.njcn.device.biz.pojo.dto.LineALLInfoDTO;
import com.njcn.device.common.service.GeneralDeviceService; import com.njcn.device.common.service.GeneralDeviceService;
import com.njcn.device.line.mapper.LineDetailMapper; import com.njcn.device.line.mapper.LineDetailMapper;
import com.njcn.device.line.mapper.LineMapper; import com.njcn.device.line.mapper.LineMapper;
@@ -30,7 +33,11 @@ import com.njcn.device.pq.pojo.vo.RStatIntegrityVO;
import com.njcn.device.pq.pojo.vo.common.DeviceOnlineRate; import com.njcn.device.pq.pojo.vo.common.DeviceOnlineRate;
import com.njcn.device.pq.service.IRStatIntegrityDService; import com.njcn.device.pq.service.IRStatIntegrityDService;
import com.njcn.device.rstatintegrity.mapper.RStatIntegrityDMapper; import com.njcn.device.rstatintegrity.mapper.RStatIntegrityDMapper;
import com.njcn.device.userledger.service.UserLedgerService;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -149,12 +156,12 @@ public class RStatIntegrityDServiceImpl extends MppServiceImpl<RStatIntegrityDMa
.stream() .stream()
.distinct() .distinct()
.collect(Collectors.toList()); .collect(Collectors.toList());
rate.setTotalNum(lineIds.size());
//获取所有监测点的数据完整性 //获取所有监测点的数据完整性
List<RStatIntegrityVO> lineIntegrityRateInfo = rStatIntegrityDMapper.getLineIntegrityRateInfo(lineIds, param.getSearchBeginTime(), param.getSearchEndTime()); List<RStatIntegrityVO> lineIntegrityRateInfo = rStatIntegrityDMapper.getLineIntegrityRateInfo(lineIds, param.getSearchBeginTime(), param.getSearchEndTime());
//获取所有监测点信息信息 //获取所有监测点信息信息
List<LineDetailVO.Detail> LineInfoByIds = lineService.getLineDetailByIds(lineIds); List<LineDetailVO.Detail> LineInfoByIds = lineService.getLineDetailByIds(lineIds);
rate.setTotalNum(lineIds.size());
rate.setBelowNum(CollUtil.isNotEmpty(lineIntegrityRateInfo) ? calculateIntegrityRate(lineIntegrityRateInfo, 90, lineIds.size()) : lineIds.size()); rate.setBelowNum(CollUtil.isNotEmpty(lineIntegrityRateInfo) ? calculateIntegrityRate(lineIntegrityRateInfo, 90, lineIds.size()) : lineIds.size());
rate.setTotalOnlineRate(calculateIntegrityRate(lineIntegrityRateInfo, lineIds).doubleValue() > 100.0 ? BigDecimal.valueOf(100.0) : calculateIntegrityRate(lineIntegrityRateInfo, lineIds)); rate.setTotalOnlineRate(calculateIntegrityRate(lineIntegrityRateInfo, lineIds).doubleValue() > 100.0 ? BigDecimal.valueOf(100.0) : calculateIntegrityRate(lineIntegrityRateInfo, lineIds));
List<DeviceOnlineRate.CitDetail> citDetailList = new ArrayList<>(); List<DeviceOnlineRate.CitDetail> citDetailList = new ArrayList<>();
@@ -166,12 +173,12 @@ public class RStatIntegrityDServiceImpl extends MppServiceImpl<RStatIntegrityDMa
Map<String, BigDecimal> onlineRateByDevMap = citDevOnRate.stream() Map<String, BigDecimal> onlineRateByDevMap = citDevOnRate.stream()
.collect(Collectors.toMap(RStatIntegrityVO::getLineIndex, RStatIntegrityVO::getIntegrityRate)); .collect(Collectors.toMap(RStatIntegrityVO::getLineIndex, RStatIntegrityVO::getIntegrityRate));
citDetail = new DeviceOnlineRate.CitDetail(); citDetail = new DeviceOnlineRate.CitDetail();
List<LineDetailVO.Detail> lineDetail = LineInfoByIds.stream().filter(x -> dto.getLineIndexes().contains(x.getLineId())).collect(Collectors.toList());
citDetail.setCitName(dto.getName()); citDetail.setCitName(dto.getName());
citDetail.setCitTotalNum(dto.getLineIndexes().size()); citDetail.setCitTotalNum(dto.getLineIndexes().size());
citDetail.setCitBelowNum(CollUtil.isNotEmpty(citDevOnRate) ? calculateIntegrityRate(citDevOnRate, 90, dto.getLineIndexes().size()) : dto.getLineIndexes().size()); citDetail.setCitBelowNum(CollUtil.isNotEmpty(citDevOnRate) ? calculateIntegrityRate(citDevOnRate, 90, dto.getLineIndexes().size()) : dto.getLineIndexes().size());
citDetail.setCitTotalOnlineRate(calculateIntegrityRate(lineIntegrityRateInfo, dto.getLineIndexes()).doubleValue() > 100.0 ? BigDecimal.valueOf(100.0) : calculateIntegrityRate(lineIntegrityRateInfo, dto.getLineIndexes())); citDetail.setCitTotalOnlineRate(calculateIntegrityRate(lineIntegrityRateInfo, dto.getLineIndexes()).doubleValue() > 100.0 ? BigDecimal.valueOf(100.0) : calculateIntegrityRate(lineIntegrityRateInfo, dto.getLineIndexes()));
List<DeviceOnlineRate.LineDetail> detailList = new ArrayList<>(); List<DeviceOnlineRate.LineDetail> detailList = new ArrayList<>();
List<LineDetailVO.Detail> lineDetail = LineInfoByIds.stream().filter(x -> dto.getLineIndexes().contains(x.getLineId())).collect(Collectors.toList());
for (LineDetailVO.Detail line : lineDetail) { for (LineDetailVO.Detail line : lineDetail) {
detail = new DeviceOnlineRate.LineDetail(); detail = new DeviceOnlineRate.LineDetail();
detail.setCit(line.getDeptName()); detail.setCit(line.getDeptName());
@@ -184,6 +191,8 @@ public class RStatIntegrityDServiceImpl extends MppServiceImpl<RStatIntegrityDMa
detail.setRunFlag(RunFlagEnum.getRunFlagRemarkByStatus(Integer.valueOf(line.getLineRunType()))); detail.setRunFlag(RunFlagEnum.getRunFlagRemarkByStatus(Integer.valueOf(line.getLineRunType())));
detail.setLineId(line.getLineId()); detail.setLineId(line.getLineId());
detail.setLineName(line.getLineName()); detail.setLineName(line.getLineName());
//用户侧监测点 监测对象
detail.setObjName(StringUtils.isBlank(line.getObjName()) ? "/" : line.getObjName());
detail.setLatestTime(line.getTimeID()); detail.setLatestTime(line.getTimeID());
detail.setIntegrity(onlineRateByDevMap.getOrDefault(line.getLineId(), BigDecimal.valueOf(0)).doubleValue() > 100.0 ? BigDecimal.valueOf(100.0) : onlineRateByDevMap.getOrDefault(line.getLineId(), BigDecimal.valueOf(0))); detail.setIntegrity(onlineRateByDevMap.getOrDefault(line.getLineId(), BigDecimal.valueOf(0)).doubleValue() > 100.0 ? BigDecimal.valueOf(100.0) : onlineRateByDevMap.getOrDefault(line.getLineId(), BigDecimal.valueOf(0)));
detailList.add(detail); detailList.add(detail);

View File

@@ -3,10 +3,11 @@ package com.njcn.device.pq.service.impl;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.dataProcess.param.DataCleanParam; import com.njcn.algorithm.pojo.dto.PqReasonableRangeDto;
import com.njcn.dataProcess.pojo.dto.PqReasonableRangeDto; import com.njcn.algorithm.pojo.param.DataCleanParam;
import com.njcn.dataProcess.pojo.po.PqReasonableRange; import com.njcn.algorithm.pojo.po.PqReasonableRange;
import com.njcn.device.pq.mapper.ReasonableRangeMapper; import com.njcn.device.pq.mapper.ReasonableRangeMapper;
import com.njcn.device.pq.service.ReasonableRangeService; import com.njcn.device.pq.service.ReasonableRangeService;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;

View File

@@ -139,7 +139,7 @@ public class RunManageServiceImpl implements RunManageService {
List<String> devIndexes = generalDeviceDTOList.stream().flatMap(list -> list.getDeviceIndexes().stream()).collect(Collectors.toList()); List<String> devIndexes = generalDeviceDTOList.stream().flatMap(list -> list.getDeviceIndexes().stream()).collect(Collectors.toList());
List<String> manuList = runManageParam.getManufacturer().stream().map(SimpleDTO::getId).collect(Collectors.toList()); List<String> manuList = runManageParam.getManufacturer().stream().map(SimpleDTO::getId).collect(Collectors.toList());
if (CollectionUtil.isEmpty(devIndexes)) { if (CollectionUtil.isEmpty(devIndexes)) {
throw new BusinessException("当前部门没有装置台账"); return new Page<>(PageFactory.getPageNum(runManageParam), PageFactory.getPageSize(runManageParam));
} }
return deviceMapper.getRunManageDevList(new Page<>(PageFactory.getPageNum(runManageParam), PageFactory.getPageSize(runManageParam)),devIndexes, runManageParam.getComFlag(), runManageParam.getRunFlag(), manuList, runManageParam.getSearchValue()); return deviceMapper.getRunManageDevList(new Page<>(PageFactory.getPageNum(runManageParam), PageFactory.getPageSize(runManageParam)),devIndexes, runManageParam.getComFlag(), runManageParam.getRunFlag(), manuList, runManageParam.getSearchValue());
} }

View File

@@ -37,6 +37,7 @@ import com.njcn.device.device.mapper.DeviceMapper;
import com.njcn.device.device.service.DeviceBakService; import com.njcn.device.device.service.DeviceBakService;
import com.njcn.device.device.service.DeviceProcessService; import com.njcn.device.device.service.DeviceProcessService;
import com.njcn.device.device.service.NodeDeviceService; import com.njcn.device.device.service.NodeDeviceService;
import com.njcn.device.device.service.PqDevTypeService;
import com.njcn.device.line.mapper.DeptLineMapper; import com.njcn.device.line.mapper.DeptLineMapper;
import com.njcn.device.line.mapper.LineDetailMapper; import com.njcn.device.line.mapper.LineDetailMapper;
import com.njcn.device.line.mapper.LineMapper; import com.njcn.device.line.mapper.LineMapper;
@@ -63,6 +64,7 @@ import com.njcn.device.subvoltage.mapper.VoltageMapper;
import com.njcn.device.terminal.mapper.PqsTerminalLogsMapper; import com.njcn.device.terminal.mapper.PqsTerminalLogsMapper;
import com.njcn.device.userledger.service.UserLedgerService; import com.njcn.device.userledger.service.UserLedgerService;
import com.njcn.device.utils.ExcelStyleUtil; import com.njcn.device.utils.ExcelStyleUtil;
import com.njcn.device.utils.LineSortHelper;
import com.njcn.message.api.ProduceFeignClient; import com.njcn.message.api.ProduceFeignClient;
import com.njcn.message.constant.DeviceRebootType; import com.njcn.message.constant.DeviceRebootType;
import com.njcn.message.constant.RedisKeyPrefix; import com.njcn.message.constant.RedisKeyPrefix;
@@ -74,6 +76,8 @@ import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.poi.excel.ExcelUtil; import com.njcn.poi.excel.ExcelUtil;
import com.njcn.poi.util.PoiUtil; import com.njcn.poi.util.PoiUtil;
import com.njcn.redis.utils.RedisUtil; import com.njcn.redis.utils.RedisUtil;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.po.user.UserReportPO;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO; import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import com.njcn.system.api.AreaFeignClient; import com.njcn.system.api.AreaFeignClient;
import com.njcn.system.api.DicDataFeignClient; import com.njcn.system.api.DicDataFeignClient;
@@ -140,6 +144,8 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
private final DeviceProcessService deviceProcessService; private final DeviceProcessService deviceProcessService;
private final ProduceFeignClient produceFeignClient; private final ProduceFeignClient produceFeignClient;
private final UserLedgerService userLedgerService; private final UserLedgerService userLedgerService;
private final PqDevTypeService pqDevTypeService;
private final LineSortHelper lineSortHelper;
@Value("${oracle.isSync}") @Value("${oracle.isSync}")
private Boolean isSync; private Boolean isSync;
@@ -201,6 +207,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
if (StrUtil.isBlank(projectIndex)) { if (StrUtil.isBlank(projectIndex)) {
checkName(addTerminalParam, PROJECT_LEVEL.getCode(), null); checkName(addTerminalParam, PROJECT_LEVEL.getCode(), null);
Line line = assembleLine(addTerminalParam.getProjectParam().getName(), PROJECT_LEVEL.getCode(), "0", "0", addTerminalParam.getProjectParam().getSort()); Line line = assembleLine(addTerminalParam.getProjectParam().getName(), PROJECT_LEVEL.getCode(), "0", "0", addTerminalParam.getProjectParam().getSort());
lineSortHelper.handleSort(PROJECT_LEVEL.getCode(),addTerminalParam.getProjectParam().getSort(),line);
this.baseMapper.insert(line); this.baseMapper.insert(line);
projectIndex = line.getId(); projectIndex = line.getId();
} }
@@ -215,6 +222,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
LogUtil.njcnDebug(log, "获取区域信息:{}", result.toString()); LogUtil.njcnDebug(log, "获取区域信息:{}", result.toString());
checkName(addTerminalParam, PROVINCE_LEVEL.getCode(), projectIndex); checkName(addTerminalParam, PROVINCE_LEVEL.getCode(), projectIndex);
Line province = assembleLine(result.getId(), PROVINCE_LEVEL.getCode(), projectIndex, projectIndex, addTerminalParam.getProvinceParam().getSort()); Line province = assembleLine(result.getId(), PROVINCE_LEVEL.getCode(), projectIndex, projectIndex, addTerminalParam.getProvinceParam().getSort());
lineSortHelper.handleSort(PROVINCE_LEVEL.getCode(),addTerminalParam.getProvinceParam().getSort(),province);
this.baseMapper.insert(province); this.baseMapper.insert(province);
provinceIndex = province.getId(); provinceIndex = province.getId();
} }
@@ -225,6 +233,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
if (StrUtil.isBlank(gdIndex) && StrUtil.isNotBlank(provinceIndex)) { if (StrUtil.isBlank(gdIndex) && StrUtil.isNotBlank(provinceIndex)) {
checkName(addTerminalParam, GD_LEVEL.getCode(), provinceIndex); checkName(addTerminalParam, GD_LEVEL.getCode(), provinceIndex);
Line gdInformation = assembleLine(addTerminalParam.getGdInformationParam().getName(), GD_LEVEL.getCode(), provinceIndex, projectIndex + StrUtil.COMMA + provinceIndex, addTerminalParam.getGdInformationParam().getSort()); Line gdInformation = assembleLine(addTerminalParam.getGdInformationParam().getName(), GD_LEVEL.getCode(), provinceIndex, projectIndex + StrUtil.COMMA + provinceIndex, addTerminalParam.getGdInformationParam().getSort());
lineSortHelper.handleSort(GD_LEVEL.getCode(),addTerminalParam.getGdInformationParam().getSort(),gdInformation);
this.baseMapper.insert(gdInformation); this.baseMapper.insert(gdInformation);
gdIndex = gdInformation.getId(); gdIndex = gdInformation.getId();
} }
@@ -235,6 +244,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
if (StrUtil.isBlank(subIndex) && StrUtil.isNotBlank(gdIndex)) { if (StrUtil.isBlank(subIndex) && StrUtil.isNotBlank(gdIndex)) {
checkName(addTerminalParam, LineBaseEnum.SUB_LEVEL.getCode(), gdIndex); checkName(addTerminalParam, LineBaseEnum.SUB_LEVEL.getCode(), gdIndex);
Line subStation = assembleLine(addTerminalParam.getSubStationParam().getName(), LineBaseEnum.SUB_LEVEL.getCode(), gdIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex, addTerminalParam.getSubStationParam().getSort()); Line subStation = assembleLine(addTerminalParam.getSubStationParam().getName(), LineBaseEnum.SUB_LEVEL.getCode(), gdIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex, addTerminalParam.getSubStationParam().getSort());
lineSortHelper.handleSort(SUB_LEVEL.getCode(),addTerminalParam.getSubStationParam().getSort(),subStation);
this.baseMapper.insert(subStation); this.baseMapper.insert(subStation);
subIndex = subStation.getId(); subIndex = subStation.getId();
@@ -255,6 +265,8 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
if (CollectionUtil.isNotEmpty(addTerminalParam.getDeviceParam()) && StrUtil.isNotBlank(subIndex)) { if (CollectionUtil.isNotEmpty(addTerminalParam.getDeviceParam()) && StrUtil.isNotBlank(subIndex)) {
//校验变电站下的装置名称ip是否重复 //校验变电站下的装置名称ip是否重复
checkDevNameAndIp(addTerminalParam, subIndex, lineLambdaQueryWrapper); checkDevNameAndIp(addTerminalParam, subIndex, lineLambdaQueryWrapper);
Integer devSort = lineSortHelper.getNextSort(DEVICE_LEVEL.getCode());
for (DeviceParam deviceParam : addTerminalParam.getDeviceParam()) { for (DeviceParam deviceParam : addTerminalParam.getDeviceParam()) {
//用于记录装置id //用于记录装置id
String devIdIndex; String devIdIndex;
@@ -282,9 +294,16 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
} }
} }
if (StrUtil.isBlank(deviceParam.getDevIndex())) { if (StrUtil.isBlank(deviceParam.getDevIndex())) {
Line device = assembleLine(deviceParam.getName(), LineBaseEnum.DEVICE_LEVEL.getCode(), subIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex, deviceParam.getSort()); Line device = assembleLine(deviceParam.getName(), LineBaseEnum.DEVICE_LEVEL.getCode(), subIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex, deviceParam.getSort());
if(Objects.isNull(deviceParam.getSort()) || deviceParam.getSort() == 0){
device.setSort(devSort);
}
this.baseMapper.insert(device); this.baseMapper.insert(device);
if(Objects.isNull(deviceParam.getSort()) || deviceParam.getSort() == 0){
devSort++;
}
devIdIndex = device.getId(); devIdIndex = device.getId();
//装置详情 //装置详情
@@ -389,7 +408,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
throw new BusinessException(DeviceResponseEnum.SUBV_NAME_SAME, voltageListBySubId.stream().map(Line::getName).collect(Collectors.joining(";"))); throw new BusinessException(DeviceResponseEnum.SUBV_NAME_SAME, voltageListBySubId.stream().map(Line::getName).collect(Collectors.joining(";")));
} }
} }
Integer subvSort = lineSortHelper.getNextSort(SUB_V_LEVEL.getCode());
for (SubVoltageParam subVoltageParam : deviceParam.getSubVoltageParam()) { for (SubVoltageParam subVoltageParam : deviceParam.getSubVoltageParam()) {
//母线id //母线id
String subvIndex; String subvIndex;
@@ -409,7 +428,13 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
} }
Line subVoltage = assembleLine(subVoltageParam.getName(), LineBaseEnum.SUB_V_LEVEL.getCode(), devIdIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex + StrUtil.COMMA + devIdIndex, subVoltageParam.getSort()); Line subVoltage = assembleLine(subVoltageParam.getName(), LineBaseEnum.SUB_V_LEVEL.getCode(), devIdIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex + StrUtil.COMMA + devIdIndex, subVoltageParam.getSort());
if(Objects.isNull(subVoltageParam.getSort()) || subVoltageParam.getSort() == 0) {
subVoltage.setSort(subvSort);
}
this.baseMapper.insert(subVoltage); this.baseMapper.insert(subVoltage);
if(Objects.isNull(subVoltageParam.getSort()) || subVoltageParam.getSort() == 0) {
subvSort++;
}
subvIndex = subVoltage.getId(); subvIndex = subVoltage.getId();
Voltage voltage = new Voltage(); Voltage voltage = new Voltage();
voltage.setId(subVoltage.getId()); voltage.setId(subVoltage.getId());
@@ -437,6 +462,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
} }
} }
//通用新增监测点 //通用新增监测点
Integer lineSort = lineSortHelper.getNextSort(LineBaseEnum.LINE_LEVEL.getCode());
for (LineParam lineParam : subVoltageParam.getLineParam()) { for (LineParam lineParam : subVoltageParam.getLineParam()) {
if (StrUtil.isBlank(lineParam.getLineIndex()) && StrUtil.isNotBlank(subvIndex)) { if (StrUtil.isBlank(lineParam.getLineIndex()) && StrUtil.isNotBlank(subvIndex)) {
//判断监测点序号是否重复 //判断监测点序号是否重复
@@ -450,7 +476,13 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
//删除与当前线路号重复的项 //删除与当前线路号重复的项
listLineNum.removeIf(lineNo -> lineNo.equals(lineParam.getNum())); listLineNum.removeIf(lineNo -> lineNo.equals(lineParam.getNum()));
Line line = assembleLine(lineParam.getName(), LineBaseEnum.LINE_LEVEL.getCode(), subvIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex + StrUtil.COMMA + devIdIndex + StrUtil.COMMA + subvIndex, lineParam.getSort()); Line line = assembleLine(lineParam.getName(), LineBaseEnum.LINE_LEVEL.getCode(), subvIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex + StrUtil.COMMA + devIdIndex + StrUtil.COMMA + subvIndex, lineParam.getSort());
if(Objects.isNull(lineParam.getSort()) || lineParam.getSort() == 0) {
line.setSort(lineSort);
}
this.baseMapper.insert(line); this.baseMapper.insert(line);
if(Objects.isNull(lineParam.getSort()) || lineParam.getSort() == 0) {
lineSort++;
}
LineDetail lineDetail = new LineDetail(); LineDetail lineDetail = new LineDetail();
BeanUtils.copyProperties(lineParam, lineDetail); BeanUtils.copyProperties(lineParam, lineDetail);
lineDetail.setId(line.getId()); lineDetail.setId(line.getId());
@@ -477,7 +509,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
//监测点限值 //监测点限值
DictData scaleResult = dicDataFeignClient.getDicDataById(voltage.getScale()).getData(); DictData scaleResult = dicDataFeignClient.getDicDataById(voltage.getScale()).getData();
float scaTmp = Float.parseFloat(scaleResult.getValue()); float scaTmp = Float.parseFloat(scaleResult.getValue());
Overlimit overlimit = COverlimitUtil.globalAssemble(scaTmp, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 0); Overlimit overlimit = COverlimitUtil.globalAssemble(scaTmp, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), lineDetail.getPowerFlag(), 0);
if (Objects.isNull(lineParam.getVoltageDev())) { if (Objects.isNull(lineParam.getVoltageDev())) {
overlimit.setVoltageDev(overlimit.getVoltageDev()); overlimit.setVoltageDev(overlimit.getVoltageDev());
@@ -748,7 +780,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
float voltageLevel = Float.parseFloat(dictData.getValue()); float voltageLevel = Float.parseFloat(dictData.getValue());
if (CollectionUtil.isNotEmpty(lineList)) { if (CollectionUtil.isNotEmpty(lineList)) {
for (LineDetail lineDetail : lineList) { for (LineDetail lineDetail : lineList) {
Overlimit overlimit = COverlimitUtil.globalAssemble(voltageLevel, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 0); Overlimit overlimit = COverlimitUtil.globalAssemble(voltageLevel, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), lineDetail.getPowerFlag(), 0);
overlimit.setId(lineDetail.getId()); overlimit.setId(lineDetail.getId());
overlimitMapper.deleteById(lineDetail.getId()); overlimitMapper.deleteById(lineDetail.getId());
overlimitMapper.insert(overlimit); overlimitMapper.insert(overlimit);
@@ -835,7 +867,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
float scaTmp = Float.parseFloat(scaleResult.getValue()); float scaTmp = Float.parseFloat(scaleResult.getValue());
//监测点限值 //监测点限值
Overlimit overlimit = COverlimitUtil.globalAssemble(scaTmp, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 0); Overlimit overlimit = COverlimitUtil.globalAssemble(scaTmp, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), lineDetail.getPowerFlag(), 0);
if (Objects.isNull(updateLineBO.getVoltageDev())) { if (Objects.isNull(updateLineBO.getVoltageDev())) {
overlimit.setVoltageDev(overlimit.getVoltageDev()); overlimit.setVoltageDev(overlimit.getVoltageDev());
} else { } else {
@@ -853,7 +885,8 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
if (!Objects.equals(lineDetail.getCt1(), lineDetailRes.getCt1()) || !Objects.equals(lineDetail.getCt2(), lineDetailRes.getCt2()) if (!Objects.equals(lineDetail.getCt1(), lineDetailRes.getCt1()) || !Objects.equals(lineDetail.getCt2(), lineDetailRes.getCt2())
|| !Objects.equals(lineDetail.getPt1(), lineDetailRes.getPt1()) || !Objects.equals(lineDetail.getPt2(), lineDetailRes.getPt2()) || !Objects.equals(lineDetail.getPt1(), lineDetailRes.getPt1()) || !Objects.equals(lineDetail.getPt2(), lineDetailRes.getPt2())
|| !Objects.equals(lineDetail.getDevCapacity(), lineDetailRes.getDevCapacity()) || !Objects.equals(lineDetail.getShortCapacity(), lineDetailRes.getShortCapacity()) || !Objects.equals(lineDetail.getDevCapacity(), lineDetailRes.getDevCapacity()) || !Objects.equals(lineDetail.getShortCapacity(), lineDetailRes.getShortCapacity())
|| !Objects.equals(lineDetail.getStandardCapacity(), lineDetailRes.getStandardCapacity()) || !Objects.equals(lineDetail.getDealCapacity(), lineDetailRes.getDealCapacity())) { || !Objects.equals(lineDetail.getStandardCapacity(), lineDetailRes.getStandardCapacity()) || !Objects.equals(lineDetail.getDealCapacity(), lineDetailRes.getDealCapacity())
|| !Objects.equals(lineDetail.getPtType(), lineDetailRes.getPtType())) {
//获取用户信息 //获取用户信息
String index = RequestUtil.getUserIndex(); String index = RequestUtil.getUserIndex();
queryUpdateAndInsertLog(userName, index, lineDetail, lineDetailRes); queryUpdateAndInsertLog(userName, index, lineDetail, lineDetailRes);
@@ -959,6 +992,11 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
sbNew.append("协议容量: ").append(newLine.getDealCapacity()).append(";"); sbNew.append("协议容量: ").append(newLine.getDealCapacity()).append(";");
sbOld.append("协议容量: ").append(oldLine.getDealCapacity()).append(";"); sbOld.append("协议容量: ").append(oldLine.getDealCapacity()).append(";");
} }
//接线方式
if (!Objects.equals(newLine.getPtType(), oldLine.getPtType())) {
sbNew.append("接线方式: ").append(newLine.getPtType()).append(";");
sbOld.append("接线方式: ").append(oldLine.getPtType()).append(";");
}
sb.append(sbNew).append(sbOld); sb.append(sbNew).append(sbOld);
HttpResult<DictData> dicDataByCode = dicDataFeignClient.getDicDataByCode(DicDataEnum.LINE_PARAMETER.getCode()); HttpResult<DictData> dicDataByCode = dicDataFeignClient.getDicDataByCode(DicDataEnum.LINE_PARAMETER.getCode());
DictData data = dicDataByCode.getData(); DictData data = dicDataByCode.getData();
@@ -1625,6 +1663,9 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
@Override @Override
public List<Line> getLineByCondition(List<String> ids, DeviceInfoParam deviceInfoParam) { public List<Line> getLineByCondition(List<String> ids, DeviceInfoParam deviceInfoParam) {
if(StrUtil.isNotBlank(deviceInfoParam.getSearchValue())){
return this.baseMapper.getLineByConditionBySearchValue(ids, deviceInfoParam);
}
return this.baseMapper.getLineByCondition(ids, deviceInfoParam); return this.baseMapper.getLineByCondition(ids, deviceInfoParam);
} }
@@ -1725,18 +1766,24 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
List<DictData> businessList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.BUSINESS_TYPE.getName()).getData(); List<DictData> businessList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.BUSINESS_TYPE.getName()).getData();
List<DictData> loadTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getName()).getData(); List<DictData> loadTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getName()).getData();
List<DictData> manufacturerList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_MANUFACTURER.getName()).getData(); List<DictData> manufacturerList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_MANUFACTURER.getName()).getData();
List<DictData> devTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_TYPE.getName()).getData(); // List<DictData> devTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_TYPE.getName()).getData();
List<PqDevType> devTypeList = pqDevTypeService.list(new LambdaQueryWrapper<PqDevType>()
.eq(PqDevType::getState, DataStateEnum.ENABLE.getCode())
.orderByDesc(PqDevType::getCreateTime));
List<DictData> frontList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.FRONT_TYPE.getName()).getData(); List<DictData> frontList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.FRONT_TYPE.getName()).getData();
List<DictData> scaleList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData(); List<DictData> scaleList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData();
List<UserLedgerVO> userLedgerVOS = userLedgerService.selectUserList(new UserReportParam());
List<Node> nodeList = nodeService.nodeAllList(); List<Node> nodeList = nodeService.nodeAllList();
ExcelUtil.selectList(workbook, 4, 4, scaleList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
ExcelUtil.selectList(workbook, 40, 40, userLedgerVOS.stream().map(UserLedgerVO::getProjectName).collect(Collectors.toList()).toArray(new String[]{}));
//这里是自己加的 带下拉框的代码 //这里是自己加的 带下拉框的代码
ExcelUtil.selectList(workbook, 8, 8, new String[]{"虚拟设备", "实际设备", "离线设备"}); ExcelUtil.selectList(workbook, 8, 8, new String[]{"虚拟设备", "实际设备", "离线设备"});
ExcelUtil.selectList(workbook, 9, 9, new String[]{"暂态系统", "稳态系统", "双系统"}); ExcelUtil.selectList(workbook, 9, 9, new String[]{"暂态系统", "稳态系统", "双系统"});
ExcelUtil.selectList(workbook, 10, 10, new String[]{"投运", "热备用", "停运"}); ExcelUtil.selectList(workbook, 10, 10, new String[]{"投运", "热备用", "停运"});
ExcelUtil.selectList(workbook, 11, 11, manufacturerList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{})); ExcelUtil.selectList(workbook, 11, 11, manufacturerList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
ExcelUtil.selectList(workbook, 12, 12, devTypeList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{})); ExcelUtil.selectList(workbook, 12, 12, devTypeList.stream().map(PqDevType::getName).collect(Collectors.toList()).toArray(new String[]{}));
ExcelUtil.selectList(workbook, 17, 17, new String[]{"周期触发", "变为触发"}); ExcelUtil.selectList(workbook, 17, 17, new String[]{"周期触发", "变为触发"});
ExcelUtil.selectList(workbook, 18, 18, nodeList.stream().map(Node::getName).collect(Collectors.toList()).toArray(new String[]{})); ExcelUtil.selectList(workbook, 18, 18, nodeList.stream().map(Node::getName).collect(Collectors.toList()).toArray(new String[]{}));
ExcelUtil.selectList(workbook, 19, 19, frontList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{})); ExcelUtil.selectList(workbook, 19, 19, frontList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
@@ -1754,6 +1801,8 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
ExcelUtil.selectList(workbook, 41, 41, new String[]{"电网侧", "非电网侧"}); ExcelUtil.selectList(workbook, 41, 41, new String[]{"电网侧", "非电网侧"});
ExcelUtil.selectList(workbook, 42, 42, new String[]{"不参与统计", "参与统计"}); ExcelUtil.selectList(workbook, 42, 42, new String[]{"不参与统计", "参与统计"});
PoiUtil.exportFileByWorkbook(workbook, "台账导入模板.xlsx", response); PoiUtil.exportFileByWorkbook(workbook, "台账导入模板.xlsx", response);
} }
@Override @Override
@@ -1842,7 +1891,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
} }
float voltageLevel = Float.parseFloat(scaleResult.getValue()); float voltageLevel = Float.parseFloat(scaleResult.getValue());
Overlimit overlimit = COverlimitUtil.globalAssemble(voltageLevel, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 0); Overlimit overlimit = COverlimitUtil.globalAssemble(voltageLevel, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), lineDetail.getPowerFlag(), 0);
overlimit.setId(lineDetail.getId()); overlimit.setId(lineDetail.getId());
overlimitMapper.insert(overlimit); overlimitMapper.insert(overlimit);
count++; count++;
@@ -2175,7 +2224,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
//监测点限值 //监测点限值
DictData scaleResult = dicDataFeignClient.getDicDataById(voltage.getScale()).getData(); DictData scaleResult = dicDataFeignClient.getDicDataById(voltage.getScale()).getData();
float scaTmp = Float.parseFloat(scaleResult.getValue()); float scaTmp = Float.parseFloat(scaleResult.getValue());
Overlimit overlimit = COverlimitUtil.globalAssemble(scaTmp, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 0); Overlimit overlimit = COverlimitUtil.globalAssemble(scaTmp, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), lineDetail.getPowerFlag(), 0);
if (Objects.isNull(lineParam.getVoltageDev())) { if (Objects.isNull(lineParam.getVoltageDev())) {
overlimit.setVoltageDev(overlimit.getVoltageDev()); overlimit.setVoltageDev(overlimit.getVoltageDev());
@@ -2723,7 +2772,8 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
* @author cdf * @author cdf
* @date 2022/5/18 * @date 2022/5/18
*/ */
private void saveTerminalBase(List<TerminalBaseExcel> terminalBaseExcels) { @Transactional(rollbackFor = Exception.class)
public void saveTerminalBase(List<TerminalBaseExcel> terminalBaseExcels) {
List<TerminalBaseExcel.TerminalBaseExcelMsg> terminalBaseExcelMsgs = new ArrayList<>(); List<TerminalBaseExcel.TerminalBaseExcelMsg> terminalBaseExcelMsgs = new ArrayList<>();
//任意集合数据为空,不处理 //任意集合数据为空,不处理
if (CollectionUtil.isNotEmpty(terminalBaseExcels)) { if (CollectionUtil.isNotEmpty(terminalBaseExcels)) {
@@ -2838,10 +2888,16 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
} }
//处理终端类型 //处理终端类型
DictData devTypeDicData = dicDataFeignClient.getDicDataByName(terminalBaseExcel.getDevType()).getData(); DictData devTypeDicData = dicDataFeignClient.getDicDataByName(terminalBaseExcel.getDevType()).getData();
PqDevType one = new PqDevType();
if (Objects.isNull(devTypeDicData)) { if (Objects.isNull(devTypeDicData)) {
//上边逻辑不删兼容旧版本新版本查询pq_dev_type
one = pqDevTypeService.lambdaQuery().eq(PqDevType::getName, terminalBaseExcel.getDevType()).eq(PqDevType::getState, DataStateEnum.ENABLE.getCode()).one();
if(Objects.isNull(one)){
terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典装置型号不存在")); terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典装置型号不存在"));
continue; continue;
} }
}
this.baseMapper.insert(temp); this.baseMapper.insert(temp);
Device device = new Device(); Device device = new Device();
BeanUtils.copyProperties(terminalBaseExcel, device); BeanUtils.copyProperties(terminalBaseExcel, device);
@@ -2850,7 +2906,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
device.setIp(terminalBaseExcel.getIp()); device.setIp(terminalBaseExcel.getIp());
device.setNodeId(node.getId()); device.setNodeId(node.getId());
device.setFrontType(frontTypeDicData.getId()); device.setFrontType(frontTypeDicData.getId());
device.setDevType(devTypeDicData.getId()); device.setDevType(Objects.isNull(devTypeDicData)?one.getId():devTypeDicData.getId());
device.setComFlag(0); device.setComFlag(0);
device.setCheckFlag(1); device.setCheckFlag(1);
device.setLoginTime(LocalDate.now()); device.setLoginTime(LocalDate.now());
@@ -2859,7 +2915,11 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
device.setUpdateTime(LocalDateTime.now()); device.setUpdateTime(LocalDateTime.now());
device.setElectroplate(0); device.setElectroplate(0);
device.setOnTime(1); device.setOnTime(1);
//处理装置识别码秘钥
coderM3d(device, false);
deviceMapper.insert(device); deviceMapper.insert(device);
//分配前置进程
nodeDeviceService.oneKeyDistribution(node.getId());
} }
//添加终端索引 //添加终端索引
pids.add(temp.getId()); pids.add(temp.getId());
@@ -2886,6 +2946,7 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
} }
//处理电压等级字典表 //处理电压等级字典表
DictData subvScale = dicDataFeignClient.getDicDataByNameAndType(terminalBaseExcel.getSubvScale(), DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData(); DictData subvScale = dicDataFeignClient.getDicDataByNameAndType(terminalBaseExcel.getSubvScale(), DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData();
if (Objects.isNull(subvScale)) { if (Objects.isNull(subvScale)) {
terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典电压等级:" + terminalBaseExcel.getSubStationScale() + "不存在")); terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典电压等级:" + terminalBaseExcel.getSubStationScale() + "不存在"));
continue; continue;
@@ -2963,11 +3024,20 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
lineDetail.setPt2(Float.valueOf(pt[1])); lineDetail.setPt2(Float.valueOf(pt[1]));
lineDetail.setCt1(Float.valueOf(ct[0])); lineDetail.setCt1(Float.valueOf(ct[0]));
lineDetail.setCt2(Float.valueOf(ct[1])); lineDetail.setCt2(Float.valueOf(ct[1]));
if(StringUtils.isNoneBlank(terminalBaseExcel.getObjName())){
UserReportPO one = userLedgerService.lambdaQuery().eq(UserReportPO::getProjectName, terminalBaseExcel.getObjName())
.eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode()).one();
if(Objects.nonNull(one)){
lineDetail.setObjId(one.getId());
DictData dictData = dicDataFeignClient.getDicDataByNameAndTypeName(terminalBaseExcel.getSubvScale(), DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData(); }
}
DictData dictData = dicDataFeignClient.getDicDataByNameAndType(terminalBaseExcel.getSubvScale(), DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData();
lineDetailMapper.insert(lineDetail); lineDetailMapper.insert(lineDetail);
Overlimit overlimit = COverlimitUtil.globalAssemble(Float.parseFloat(dictData.getValue()), terminalBaseExcel.getDealCapacity(), terminalBaseExcel.getDevCapacity(), terminalBaseExcel.getShortCapacity(), null, null); Overlimit overlimit = COverlimitUtil.globalAssemble(Float.parseFloat(dictData.getValue()), terminalBaseExcel.getDealCapacity(), terminalBaseExcel.getDevCapacity(), terminalBaseExcel.getShortCapacity(), terminalBaseExcel.getPowerFlag(), 0);
overlimit.setId(temp.getId()); overlimit.setId(temp.getId());
overlimitMapper.insert(overlimit); overlimitMapper.insert(overlimit);
} }
@@ -3851,6 +3921,15 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
} }
//设备删除找不到设备名称,重日志截取 //设备删除找不到设备名称,重日志截取
if (Objects.equals(temp.getOperateType(), Param.DEL)) { if (Objects.equals(temp.getOperateType(), Param.DEL)) {
//删除有2种情况1.设备删除2设备状态修改
if (lineMap.containsKey(deviceId)) {
pqsTerminalPushLogDTO.setDevName(lineMap.get(deviceId).getName());
String nodeId = deviceMap.get(deviceId).getNodeId();
pqsTerminalPushLogDTO.setNodeId(nodeId);
pqsTerminalPushLogDTO.setNodeName(nodeMap.containsKey(nodeId)?nodeMap.get(nodeId).getName():"删除前置");
}else {
if(temp.getTerminalDescribe().contains("前置信息")){
String temLos = "%s名称:%s;前置信息:%s"; String temLos = "%s名称:%s;前置信息:%s";
List<String> strings = this.parseTemplateValues(temLos, temp.getTerminalDescribe()); List<String> strings = this.parseTemplateValues(temLos, temp.getTerminalDescribe());
String devName = strings.get(1); // 设备名称 String devName = strings.get(1); // 设备名称
@@ -3859,6 +3938,12 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
String nodeId = nodeNameMap.get(nodeName).getId(); String nodeId = nodeNameMap.get(nodeName).getId();
pqsTerminalPushLogDTO.setNodeId(nodeId); pqsTerminalPushLogDTO.setNodeId(nodeId);
pqsTerminalPushLogDTO.setNodeName(nodeName); pqsTerminalPushLogDTO.setNodeName(nodeName);
}else {
return;
}
}
} else { } else {
//如果存在说明设备未被删除不存在说明有一条删除日志直接return //如果存在说明设备未被删除不存在说明有一条删除日志直接return
if (lineMap.containsKey(deviceId)) { if (lineMap.containsKey(deviceId)) {
@@ -4280,6 +4365,10 @@ public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> imple
// 比较装置 所属前置 // 比较装置 所属前置
flag |= compareAndAppend(stringBuilder, devDetail.getNodeId(), updateDeviceParam.getNodeId(), "终端所属前置机"); flag |= compareAndAppend(stringBuilder, devDetail.getNodeId(), updateDeviceParam.getNodeId(), "终端所属前置机");
//如果前置机切换可能装置在进程2上但是切换后前置机只有一个进程因此修改装置进程表设为默认进程1
if(!Objects.equals(updateDeviceParam.getNodeId(), devDetail.getNodeId())){
deviceProcessService.lambdaUpdate().eq(DeviceProcess::getId,devDetail.getId()).set(DeviceProcess::getProcessNo,1).update();
}
// 比较装置端口号 // 比较装置端口号
flag |= compareAndAppend(stringBuilder, devDetail.getPort(), updateDeviceParam.getPort(), "终端端口号"); flag |= compareAndAppend(stringBuilder, devDetail.getPort(), updateDeviceParam.getPort(), "终端端口号");

View File

@@ -3,9 +3,6 @@ package com.njcn.device.device.controller;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.github.tocrhz.mqtt.annotation.MqttSubscribe;
import com.github.tocrhz.mqtt.annotation.NamedValue;
import com.github.tocrhz.mqtt.annotation.Payload;
import com.njcn.common.pojo.annotation.OperateInfo; import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.dto.SimpleDTO; import com.njcn.common.pojo.dto.SimpleDTO;
import com.njcn.common.pojo.enums.common.LogEnum; import com.njcn.common.pojo.enums.common.LogEnum;
@@ -27,12 +24,10 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -57,132 +52,132 @@ public class DeviceController extends BaseController {
private final GeneralDeviceService generalDeviceService; private final GeneralDeviceService generalDeviceService;
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/socketLine") // @PostMapping("/socketLine")
@ApiOperation("获取监测点定值信息") // @ApiOperation("获取监测点定值信息")
public HttpResult<String> socketLine(@RequestBody @Validated ConstantValueParam.Constant param) { // public HttpResult<String> socketLine(@RequestBody @Validated ConstantValueParam.Constant param) {
String methodDescribe = getMethodDescribe("socketLine"); // String methodDescribe = getMethodDescribe("socketLine");
if(StrUtil.isBlank(param.getIp())){ // if(StrUtil.isBlank(param.getIp())){
param.setIp(RequestUtil.getRealIp()); // param.setIp(RequestUtil.getRealIp());
} // }
String s = iDeviceService.sentLine(param); // String s = iDeviceService.sentLine(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/updateSocketLine") // @PostMapping("/updateSocketLine")
@ApiOperation("修改监测点定值信息") // @ApiOperation("修改监测点定值信息")
public HttpResult<String> updateSocketLine(@RequestBody @Validated ConstantValueParam.ValueData param) { // public HttpResult<String> updateSocketLine(@RequestBody @Validated ConstantValueParam.ValueData param) {
String methodDescribe = getMethodDescribe("updateSocketLine"); // String methodDescribe = getMethodDescribe("updateSocketLine");
if(StrUtil.isBlank(param.getIp())){ // if(StrUtil.isBlank(param.getIp())){
param.setIp(RequestUtil.getRealIp()); // param.setIp(RequestUtil.getRealIp());
} // }
String s = iDeviceService.sentLineData(param); // String s = iDeviceService.sentLineData(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/socketDev") // @PostMapping("/socketDev")
@ApiOperation("获取终端定值信息") // @ApiOperation("获取终端定值信息")
public HttpResult<String> socketDev(@RequestBody @Validated ConstantValueParam.Constant param) { // public HttpResult<String> socketDev(@RequestBody @Validated ConstantValueParam.Constant param) {
String methodDescribe = getMethodDescribe("socketDev"); // String methodDescribe = getMethodDescribe("socketDev");
if(StrUtil.isBlank(param.getIp())){ // if(StrUtil.isBlank(param.getIp())){
param.setIp(RequestUtil.getRealIp()); // param.setIp(RequestUtil.getRealIp());
} // }
String s = iDeviceService.sentDev(param); // String s = iDeviceService.sentDev(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/updateSocketDev") // @PostMapping("/updateSocketDev")
@ApiOperation("修改终端定值信息") // @ApiOperation("修改终端定值信息")
public HttpResult<String> updateSocketDev(@RequestBody @Validated ConstantValueParam.ValueData param) { // public HttpResult<String> updateSocketDev(@RequestBody @Validated ConstantValueParam.ValueData param) {
String methodDescribe = getMethodDescribe("updateSocketDev"); // String methodDescribe = getMethodDescribe("updateSocketDev");
if(StrUtil.isBlank(param.getIp())){ // if(StrUtil.isBlank(param.getIp())){
param.setIp(RequestUtil.getRealIp()); // param.setIp(RequestUtil.getRealIp());
} // }
String s = iDeviceService.sentDevData(param); // String s = iDeviceService.sentDevData(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/socketDevProperty") // @PostMapping("/socketDevProperty")
@ApiOperation("获取终端性能信息") // @ApiOperation("获取终端性能信息")
public HttpResult<String> socketDevProperty(String devID) { // public HttpResult<String> socketDevProperty(String devID) {
String methodDescribe = getMethodDescribe("socketDevProperty"); // String methodDescribe = getMethodDescribe("socketDevProperty");
String s = iDeviceService.socketDevProperty(devID); // String s = iDeviceService.socketDevProperty(devID);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/socketDevPropertyClose") // @PostMapping("/socketDevPropertyClose")
@ApiOperation("终端性能关闭") // @ApiOperation("终端性能关闭")
public HttpResult<String> socketDevPropertyClose(String devID) { // public HttpResult<String> socketDevPropertyClose(String devID) {
String methodDescribe = getMethodDescribe("socketDevPropertyClose"); // String methodDescribe = getMethodDescribe("socketDevPropertyClose");
String s = iDeviceService.socketDevPropertyClose(devID); // String s = iDeviceService.socketDevPropertyClose(devID);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/realTimeData") // @PostMapping("/realTimeData")
@ApiOperation("监测点实时数据查看") // @ApiOperation("监测点实时数据查看")
public HttpResult<String> realTimeData(String lineID) { // public HttpResult<String> realTimeData(String lineID) {
String methodDescribe = getMethodDescribe("realTimeData"); // String methodDescribe = getMethodDescribe("realTimeData");
String s = iDeviceService.realTimeData(lineID); // String s = iDeviceService.realTimeData(lineID);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/heartRealTimeData") // @PostMapping("/heartRealTimeData")
@ApiOperation("监测实施数据心跳") // @ApiOperation("监测实施数据心跳")
public HttpResult<String> heartRealTimeData(String lineID) { // public HttpResult<String> heartRealTimeData(String lineID) {
String methodDescribe = getMethodDescribe("heartRealTimeData"); // String methodDescribe = getMethodDescribe("heartRealTimeData");
String s = iDeviceService.heartRealTimeData(lineID); // String s = iDeviceService.heartRealTimeData(lineID);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/closeRealTimeData") // @PostMapping("/closeRealTimeData")
@ApiOperation("监测点实施数据关闭") // @ApiOperation("监测点实施数据关闭")
public HttpResult<String> closeRealTimeData(String lineID) { // public HttpResult<String> closeRealTimeData(String lineID) {
String methodDescribe = getMethodDescribe("closeRealTimeData"); // String methodDescribe = getMethodDescribe("closeRealTimeData");
String s = iDeviceService.closeRealTimeData(lineID); // String s = iDeviceService.closeRealTimeData(lineID);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/getDevUpgrades") // @PostMapping("/getDevUpgrades")
@ApiOperation("终端版本升级") // @ApiOperation("终端版本升级")
public HttpResult<String> getDevUpgrades(@RequestBody @Validated ConstantValueParam.Upgrades param) { // public HttpResult<String> getDevUpgrades(@RequestBody @Validated ConstantValueParam.Upgrades param) {
String methodDescribe = getMethodDescribe("getDevUpgrades"); // String methodDescribe = getMethodDescribe("getDevUpgrades");
String s = iDeviceService.getDevUpgrades(param.getList(),param.getEdIndex()); // String s = iDeviceService.getDevUpgrades(param.getList(),param.getEdIndex());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/closeUpgrades") // @PostMapping("/closeUpgrades")
@ApiOperation("终端升级取消") // @ApiOperation("终端升级取消")
public HttpResult<String> closeUpgrades(@RequestBody List<String> devList) { // public HttpResult<String> closeUpgrades(@RequestBody List<String> devList) {
String methodDescribe = getMethodDescribe("closeUpgrades"); // String methodDescribe = getMethodDescribe("closeUpgrades");
String s = iDeviceService.closeUpgrades(devList); // String s = iDeviceService.closeUpgrades(devList);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
//
@OperateInfo(info = LogEnum.SYSTEM_COMMON) // @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/restartDev") // @PostMapping("/restartDev")
@ApiOperation("重启装置命令") // @ApiOperation("重启装置命令")
public HttpResult<String> restartDev(@RequestBody List<String> devList) { // public HttpResult<String> restartDev(@RequestBody List<String> devList) {
String methodDescribe = getMethodDescribe("restartDev"); // String methodDescribe = getMethodDescribe("restartDev");
String s = iDeviceService.restartDev(devList); // String s = iDeviceService.restartDev(devList);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe); // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, s, methodDescribe);
} // }
@MqttSubscribe(value = "/zl/devData/{devID}",qos = 1) // @MqttSubscribe(value = "/zl/devData/{devID}",qos = 1)
public void responseRtData(String topic, @NamedValue("devID") String pageId, MqttMessage message, @Payload String payload) { // public void responseRtData(String topic, @NamedValue("devID") String pageId, MqttMessage message, @Payload String payload) {
Console.log("receive from : {}", topic); // Console.log("receive from : {}", topic);
Console.log("receive from : {}", pageId); // Console.log("receive from : {}", pageId);
Console.log("message : {}", message.getPayload()); // Console.log("message : {}", message.getPayload());
Console.log("message payload : {}", new String(message.getPayload(), StandardCharsets.UTF_8)); // Console.log("message payload : {}", new String(message.getPayload(), StandardCharsets.UTF_8));
Console.log("string payload : {}", payload); // Console.log("string payload : {}", payload);
} // }
@OperateInfo(info = LogEnum.SYSTEM_COMMON) @OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/updateDevCheckTime") @PostMapping("/updateDevCheckTime")

View File

@@ -19,113 +19,113 @@ import java.util.List;
public interface IDeviceService extends IService<Device> { public interface IDeviceService extends IService<Device> {
/*** // /***
* @Description: mqtt获取外部定值 // * @Description: mqtt获取外部定值
* @param param // * @param param
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/14 10:17 // * @Date: 2023/8/14 10:17
*/ // */
String sentLine(ConstantValueParam.Constant param); // String sentLine(ConstantValueParam.Constant param);
//
/*** // /***
* @Description: mqtt修改外部定值 // * @Description: mqtt修改外部定值
* @param param // * @param param
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/14 11:07 // * @Date: 2023/8/14 11:07
*/ // */
String sentLineData(ConstantValueParam.ValueData param); // String sentLineData(ConstantValueParam.ValueData param);
//
/** // /**
* @param param // * @param param
* @Description: mqtt获取内部定值 // * @Description: mqtt获取内部定值
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/14 14:51 // * @Date: 2023/8/14 14:51
*/ // */
String sentDev(ConstantValueParam.Constant param); // String sentDev(ConstantValueParam.Constant param);
//
/** // /**
* @param param // * @param param
* @Description: mqtt修改内部定值 // * @Description: mqtt修改内部定值
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/14 14:51 // * @Date: 2023/8/14 14:51
*/ // */
String sentDevData(ConstantValueParam.ValueData param); // String sentDevData(ConstantValueParam.ValueData param);
//
/** // /**
* @param devID // * @param devID
* @Description: 终端性能查看 // * @Description: 终端性能查看
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/15 11:27 // * @Date: 2023/8/15 11:27
*/ // */
String socketDevProperty(String devID); // String socketDevProperty(String devID);
//
/** // /**
* @param devID // * @param devID
* @Description: 终端性能关闭 // * @Description: 终端性能关闭
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/15 16:13 // * @Date: 2023/8/15 16:13
*/ // */
String socketDevPropertyClose(String devID); // String socketDevPropertyClose(String devID);
//
/** // /**
* @param lineIndex // * @param lineIndex
* @Description: 监测点实时数据查看 // * @Description: 监测点实时数据查看
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/15 16:13 // * @Date: 2023/8/15 16:13
*/ // */
String realTimeData(String lineIndex); // String realTimeData(String lineIndex);
//
/** // /**
* @param lineIndex // * @param lineIndex
* @Description: 监测实施数据心跳 // * @Description: 监测实施数据心跳
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/15 16:14 // * @Date: 2023/8/15 16:14
*/ // */
String heartRealTimeData(String lineIndex); // String heartRealTimeData(String lineIndex);
//
/** // /**
* @param lineIndex // * @param lineIndex
* @Description: 监测点实施数据关闭 // * @Description: 监测点实施数据关闭
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/15 16:14 // * @Date: 2023/8/15 16:14
*/ // */
String closeRealTimeData(String lineIndex); // String closeRealTimeData(String lineIndex);
//
/** // /**
* 终端版本升级,批量升级条件必须是相同终端系列的终端才能升级 // * 终端版本升级,批量升级条件必须是相同终端系列的终端才能升级
* // *
* @param list // * @param list
* @param edIndex // * @param edIndex
* @return // * @return
*/ // */
String getDevUpgrades(List<String> list, String edIndex); // String getDevUpgrades(List<String> list, String edIndex);
//
/** // /**
* @param devList // * @param devList
* @Description: 终端升级取消 // * @Description: 终端升级取消
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/17 9:24 // * @Date: 2023/8/17 9:24
*/ // */
String closeUpgrades(List<String> devList); // String closeUpgrades(List<String> devList);
//
/** // /**
* @param devList // * @param devList
* @Description: 重启装置命令 // * @Description: 重启装置命令
* @return: java.lang.String // * @return: java.lang.String
* @Author: wr // * @Author: wr
* @Date: 2023/8/17 9:24 // * @Date: 2023/8/17 9:24
*/ // */
String restartDev(List<String> devList); // String restartDev(List<String> devList);
/** /**
* @param devId 装置id * @param devId 装置id

View File

@@ -1,10 +1,6 @@
package com.njcn.device.device.service.impl; package com.njcn.device.device.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -14,16 +10,11 @@ import com.njcn.device.device.mapper.DeviceMapper;
import com.njcn.device.device.service.IDeviceService; import com.njcn.device.device.service.IDeviceService;
import com.njcn.device.device.service.ProgramVersionService; import com.njcn.device.device.service.ProgramVersionService;
import com.njcn.device.line.mapper.LineMapper; import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.pq.pojo.advanced.*;
import com.njcn.device.pq.pojo.param.ConstantValueParam;
import com.njcn.device.pq.pojo.po.DevVersion;
import com.njcn.device.pq.pojo.po.Device; import com.njcn.device.pq.pojo.po.Device;
import com.njcn.device.pq.pojo.po.Line;
import com.njcn.device.pq.pojo.po.Version;
import com.njcn.device.pq.pojo.vo.DevStatusNumVO; import com.njcn.device.pq.pojo.vo.DevStatusNumVO;
import com.njcn.device.pq.pojo.vo.DeviceIpRVO;
import com.njcn.device.utils.SocketClient;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -45,360 +36,360 @@ import java.util.stream.Collectors;
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService { public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
private final LineMapper lineMapper; private final LineMapper lineMapper;
private final SocketClient socketClient; // private final SocketClient socketClient;
private final DevVersionMapper devVersionMapper; private final DevVersionMapper devVersionMapper;
private final ProgramVersionService programVersionService; private final ProgramVersionService programVersionService;
@Value("${socket.port:60000}") @Value("${socket.port:60000}")
private Integer socketPort; private Integer socketPort;
@Override // @Override
public String sentLine(ConstantValueParam.Constant param) { // public String sentLine(ConstantValueParam.Constant param) {
try { // try {
//获取根据监测点获取终端信息 // //获取根据监测点获取终端信息
UpDevVO upDevVO = lineMapper.getDevInfo(param.getId()); // UpDevVO upDevVO = lineMapper.getDevInfo(param.getId());
//查询前置ip // //查询前置ip
String host = lineMapper.getNodeIp(upDevVO.getDevIndex(),0); // String host = lineMapper.getNodeIp(upDevVO.getDevIndex(),0);
//拼接属性 // //拼接属性
ContValueRVO upParamVO = new ContValueRVO(); // ContValueRVO upParamVO = new ContValueRVO();
ContValueVO valueVO = new ContValueVO(); // ContValueVO valueVO = new ContValueVO();
valueVO.setType(param.getType()); // valueVO.setType(param.getType());
valueVO.setLineid(param.getId()); // valueVO.setLineid(param.getId());
valueVO.setHander(param.getHander()); // valueVO.setHander(param.getHander());
JSONObject jsonStr = new JSONObject(valueVO); // JSONObject jsonStr = new JSONObject(valueVO);
Integer len = jsonStr.toString().length(); // Integer len = jsonStr.toString().length();
upParamVO.setLen(len.toString()); // upParamVO.setLen(len.toString());
upParamVO.setData(valueVO); // upParamVO.setData(valueVO);
JSONObject jsonObject = new JSONObject(upParamVO); // JSONObject jsonObject = new JSONObject(upParamVO);
String str = jsonObject.toString(); // String str = jsonObject.toString();
List<UpDevVO> devList = new ArrayList<>(); // List<UpDevVO> devList = new ArrayList<>();
devList.add(upDevVO); // devList.add(upDevVO);
return socketClient.sentLine(param.getIp(), str, host, socketPort, "wr", devList); // return socketClient.sentLine(param.getIp(), str, host, socketPort, "wr", devList);
} catch (Exception e) { // } catch (Exception e) {
return "获取定值失败"; // return "获取定值失败";
} // }
//
} // }
//
@Override // @Override
public String sentLineData(ConstantValueParam.ValueData param) { // public String sentLineData(ConstantValueParam.ValueData param) {
try { // try {
//获取根据监测点获取终端信息 // //获取根据监测点获取终端信息
UpDevVO upDevVO = lineMapper.getDevInfo(param.getId()); // UpDevVO upDevVO = lineMapper.getDevInfo(param.getId());
//查询前置ip // //查询前置ip
String host = lineMapper.getNodeIp(upDevVO.getDevIndex(),0); // String host = lineMapper.getNodeIp(upDevVO.getDevIndex(),0);
ContUpdateValueRVO upParamVO = new ContUpdateValueRVO(); // ContUpdateValueRVO upParamVO = new ContUpdateValueRVO();
ContUpdateValueVO valueVO = new ContUpdateValueVO(); // ContUpdateValueVO valueVO = new ContUpdateValueVO();
valueVO.setType(param.getType()); // valueVO.setType(param.getType());
valueVO.setLineid(param.getId()); // valueVO.setLineid(param.getId());
valueVO.setHander(param.getHander()); // valueVO.setHander(param.getHander());
float[] intArr; // float[] intArr;
if (StrUtil.isBlank(param.getInterValue())) { // if (StrUtil.isBlank(param.getInterValue())) {
intArr = new float[0]; // intArr = new float[0];
} else { // } else {
String[] valueArr = param.getInterValue().split(","); // String[] valueArr = param.getInterValue().split(",");
intArr = new float[valueArr.length]; // intArr = new float[valueArr.length];
for (int i = 0; i < valueArr.length; i++) { // for (int i = 0; i < valueArr.length; i++) {
intArr[i] = Float.parseFloat(valueArr[i]); // intArr[i] = Float.parseFloat(valueArr[i]);
} // }
} // }
valueVO.setValue(intArr); // valueVO.setValue(intArr);
JSONObject jsonStr = new JSONObject(valueVO); // JSONObject jsonStr = new JSONObject(valueVO);
Integer len = jsonStr.toString().length(); // Integer len = jsonStr.toString().length();
upParamVO.setLen(len.toString()); // upParamVO.setLen(len.toString());
upParamVO.setData(valueVO); // upParamVO.setData(valueVO);
JSONObject jsonObject = new JSONObject(upParamVO); // JSONObject jsonObject = new JSONObject(upParamVO);
String str = jsonObject.toString(); // String str = jsonObject.toString();
List<UpDevVO> devList = new ArrayList<>(); // List<UpDevVO> devList = new ArrayList<>();
devList.add(upDevVO); // devList.add(upDevVO);
return socketClient.sentLine(param.getIp(), str, host, socketPort, "wr", devList); // return socketClient.sentLine(param.getIp(), str, host, socketPort, "wr", devList);
} catch (Exception e) { // } catch (Exception e) {
return "运行失败"; // return "运行失败";
} // }
} // }
//
@Override // @Override
public String sentDev(ConstantValueParam.Constant param) { // public String sentDev(ConstantValueParam.Constant param) {
try { // try {
Line line = lineMapper.selectById(param.getId()); // Line line = lineMapper.selectById(param.getId());
UpDevVO upDevVO = new UpDevVO(); // UpDevVO upDevVO = new UpDevVO();
upDevVO.setDevIndex(line.getId()); // upDevVO.setDevIndex(line.getId());
upDevVO.setDevName(line.getName()); // upDevVO.setDevName(line.getName());
String host = lineMapper.getNodeIp(line.getId(),1); // String host = lineMapper.getNodeIp(line.getId(),1);
ContValueRVO upParamVO = new ContValueRVO(); // ContValueRVO upParamVO = new ContValueRVO();
ContValueVO valueVO = new ContValueVO(); // ContValueVO valueVO = new ContValueVO();
valueVO.setType(param.getType()); // valueVO.setType(param.getType());
valueVO.setIndex(param.getId()); // valueVO.setIndex(param.getId());
valueVO.setHander(param.getHander()); // valueVO.setHander(param.getHander());
JSONObject jsonStr = new JSONObject(valueVO); // JSONObject jsonStr = new JSONObject(valueVO);
Integer len = jsonStr.toString().length(); // Integer len = jsonStr.toString().length();
upParamVO.setLen(len.toString()); // upParamVO.setLen(len.toString());
upParamVO.setData(valueVO); // upParamVO.setData(valueVO);
JSONObject jsonObject = new JSONObject(upParamVO); // JSONObject jsonObject = new JSONObject(upParamVO);
String str = jsonObject.toString(); // String str = jsonObject.toString();
List<UpDevVO> devList = new ArrayList<>(); // List<UpDevVO> devList = new ArrayList<>();
devList.add(upDevVO); // devList.add(upDevVO);
return socketClient.sentDZDev(param.getIp(), str, host, socketPort, "wr", devList); // return socketClient.sentDZDev(param.getIp(), str, host, socketPort, "wr", devList);
} catch (Exception e) { // } catch (Exception e) {
return "获取定值失败"; // return "获取定值失败";
} // }
} // }
//
@Override // @Override
public String sentDevData(ConstantValueParam.ValueData param) { // public String sentDevData(ConstantValueParam.ValueData param) {
try { // try {
Line line = lineMapper.selectById(param.getId()); // Line line = lineMapper.selectById(param.getId());
UpDevVO upDevVO = new UpDevVO(); // UpDevVO upDevVO = new UpDevVO();
upDevVO.setDevIndex(line.getId()); // upDevVO.setDevIndex(line.getId());
upDevVO.setDevName(line.getName()); // upDevVO.setDevName(line.getName());
String host = lineMapper.getNodeIp(line.getId(),1); // String host = lineMapper.getNodeIp(line.getId(),1);
ContUpdateDevValueRVO upParamVO = new ContUpdateDevValueRVO(); // ContUpdateDevValueRVO upParamVO = new ContUpdateDevValueRVO();
ContUpdateDevValueVO valueVO = new ContUpdateDevValueVO(); // ContUpdateDevValueVO valueVO = new ContUpdateDevValueVO();
valueVO.setType(param.getType()); // valueVO.setType(param.getType());
valueVO.setIndex(line.getId()); // valueVO.setIndex(line.getId());
valueVO.setHander(String.valueOf(param.getHander())); // valueVO.setHander(String.valueOf(param.getHander()));
int[] intArr; // int[] intArr;
if (StrUtil.isBlank(param.getInterValue())) { // if (StrUtil.isBlank(param.getInterValue())) {
intArr = new int[0]; // intArr = new int[0];
} else { // } else {
String[] valueArr = param.getInterValue().split(","); // String[] valueArr = param.getInterValue().split(",");
intArr = new int[valueArr.length]; // intArr = new int[valueArr.length];
for (int i = 0; i < valueArr.length; i++) { // for (int i = 0; i < valueArr.length; i++) {
intArr[i] = Integer.parseInt(valueArr[i]); // intArr[i] = Integer.parseInt(valueArr[i]);
} // }
} // }
valueVO.setInterValue(intArr); // valueVO.setInterValue(intArr);
JSONObject jsonStr = new JSONObject(valueVO); // JSONObject jsonStr = new JSONObject(valueVO);
Integer len = jsonStr.toString().length(); // Integer len = jsonStr.toString().length();
upParamVO.setLen(len.toString()); // upParamVO.setLen(len.toString());
upParamVO.setData(valueVO); // upParamVO.setData(valueVO);
JSONObject jsonObject = new JSONObject(upParamVO); // JSONObject jsonObject = new JSONObject(upParamVO);
String str = jsonObject.toString(); // String str = jsonObject.toString();
//
List<UpDevVO> devList = new ArrayList<>(); // List<UpDevVO> devList = new ArrayList<>();
devList.add(upDevVO); // devList.add(upDevVO);
return socketClient.sentDZDev(param.getIp(), str, host, socketPort, "wr", devList); // return socketClient.sentDZDev(param.getIp(), str, host, socketPort, "wr", devList);
} catch (Exception e) { // } catch (Exception e) {
return "运行失败"; // return "运行失败";
} // }
} // }
//
@Override // @Override
public String socketDevProperty(String devID) { // public String socketDevProperty(String devID) {
String host = lineMapper.getNodeIp(devID,1); // String host = lineMapper.getNodeIp(devID,1);
if(StrUtil.isBlank(host)){ // if(StrUtil.isBlank(host)){
return "前置ip获取失败"; // return "前置ip获取失败";
} // }
JSONObject jsonObject = new JSONObject(); // JSONObject jsonObject = new JSONObject();
Map<String,String> map = new HashMap<>(); // Map<String,String> map = new HashMap<>();
map.put("type","190"); // map.put("type","190");
map.put("index",devID); // map.put("index",devID);
map.put("hander","1"); // map.put("hander","1");
jsonObject.set("data", map); // jsonObject.set("data", map);
Integer len = jsonObject.get("data").toString().length(); // Integer len = jsonObject.get("data").toString().length();
jsonObject.set("len", len.toString()); // jsonObject.set("len", len.toString());
socketClient.showProperty(jsonObject.toString(),host,socketPort,RequestUtil.getLoginName()); // socketClient.showProperty(jsonObject.toString(),host,socketPort,RequestUtil.getLoginName());
return "终端性能获取成功"; // return "终端性能获取成功";
} // }
//
@Override // @Override
public String socketDevPropertyClose(String devID) { // public String socketDevPropertyClose(String devID) {
String host = lineMapper.getNodeIp(devID,1); // String host = lineMapper.getNodeIp(devID,1);
try { // try {
JSONObject jsonObject = new JSONObject(); // JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>(); // Map<String, String> map = new HashMap<>();
map.put("type", "190"); // map.put("type", "190");
map.put("index", devID); // map.put("index", devID);
map.put("hander", "0"); // map.put("hander", "0");
jsonObject.set("data", map); // jsonObject.set("data", map);
Integer len = jsonObject.get("data").toString().length(); // Integer len = jsonObject.get("data").toString().length();
jsonObject.set("len", len.toString()); // jsonObject.set("len", len.toString());
socketClient.closeDevSocket(jsonObject.toString(),host,socketPort,RequestUtil.getLoginName()); // socketClient.closeDevSocket(jsonObject.toString(),host,socketPort,RequestUtil.getLoginName());
return "执行成功"; // return "执行成功";
}catch (Exception e){ // }catch (Exception e){
return "执行失败"; // return "执行失败";
} // }
} // }
//
@Override // @Override
public String realTimeData(String lineIndex) { // public String realTimeData(String lineIndex) {
//查询前置ip // //查询前置ip
String host = lineMapper.getNodeIp(lineIndex,0); // String host = lineMapper.getNodeIp(lineIndex,0);
if(StrUtil.isBlank(host)){ // if(StrUtil.isBlank(host)){
return "设备前置机服务器配置异常,请联系管理员"; // return "设备前置机服务器配置异常,请联系管理员";
}else { // }else {
JSONObject jsonObject = new JSONObject(); // JSONObject jsonObject = new JSONObject();
jsonObject.set("LineId", lineIndex); // jsonObject.set("LineId", lineIndex);
jsonObject.set("type", 0); // jsonObject.set("type", 0);
JSONObject jsonObject1 = new JSONObject(); // JSONObject jsonObject1 = new JSONObject();
jsonObject1.set("len",0); // jsonObject1.set("len",0);
jsonObject1.set("data",jsonObject); // jsonObject1.set("data",jsonObject);
socketClient.realTimeData(jsonObject1.toString(),host,socketPort,lineIndex); // socketClient.realTimeData(jsonObject1.toString(),host,socketPort,lineIndex);
} // }
return "请求成功"; // return "请求成功";
} // }
//
@Override // @Override
public String heartRealTimeData(String lineIndex) { // public String heartRealTimeData(String lineIndex) {
JSONObject jsonObject = new JSONObject(); // JSONObject jsonObject = new JSONObject();
jsonObject.set("LineId", lineIndex); // jsonObject.set("LineId", lineIndex);
jsonObject.set("type", 1); // jsonObject.set("type", 1);
JSONObject jsonObject1 = new JSONObject(); // JSONObject jsonObject1 = new JSONObject();
jsonObject1.set("len", 0); // jsonObject1.set("len", 0);
jsonObject1.set("data", jsonObject); // jsonObject1.set("data", jsonObject);
String host = lineMapper.getNodeIp(lineIndex,0); // String host = lineMapper.getNodeIp(lineIndex,0);
socketClient.heartRealData(jsonObject1.toString(),host,socketPort,lineIndex); // socketClient.heartRealData(jsonObject1.toString(),host,socketPort,lineIndex);
return "实时数据心跳请求成功"; // return "实时数据心跳请求成功";
} // }
//
@Override // @Override
public String closeRealTimeData(String lineIndex) { // public String closeRealTimeData(String lineIndex) {
socketClient.closeRealData(lineIndex); // socketClient.closeRealData(lineIndex);
return "关闭实时数据请求成功"; // return "关闭实时数据请求成功";
} // }
//
@Override // @Override
public String getDevUpgrades(List<String> list, String edIndex) { // public String getDevUpgrades(List<String> list, String edIndex) {
List<DeviceIpRVO> resTemlist = new ArrayList<>(); // List<DeviceIpRVO> resTemlist = new ArrayList<>();
//
List<DeviceIpRVO> relist = lineMapper.getDevicesIp(list); // List<DeviceIpRVO> relist = lineMapper.getDevicesIp(list);
//判断设备版本号 // //判断设备版本号
Integer isExit = devVersionMapper.selectCount(new LambdaQueryWrapper<DevVersion>() // Integer isExit = devVersionMapper.selectCount(new LambdaQueryWrapper<DevVersion>()
.eq(DevVersion::getVersionId,edIndex) // .eq(DevVersion::getVersionId,edIndex)
.in(DevVersion::getLineId,list) // .in(DevVersion::getLineId,list)
.eq(DevVersion::getState,1) // .eq(DevVersion::getState,1)
); // );
if (isExit > 0) { // if (isExit > 0) {
return "请勿选择相同版本号升级"; // return "请勿选择相同版本号升级";
} // }
if (!CollectionUtil.isEmpty(relist)) { // if (!CollectionUtil.isEmpty(relist)) {
Version version = programVersionService.getById(edIndex); // Version version = programVersionService.getById(edIndex);
String series = version.getDevType(); // String series = version.getDevType();
//判断设备是否存在相同型号 // //判断设备是否存在相同型号
for (DeviceIpRVO deviceIpRVO : relist) { // for (DeviceIpRVO deviceIpRVO : relist) {
if (!series.equals(deviceIpRVO.getDevSeries())) { // if (!series.equals(deviceIpRVO.getDevSeries())) {
return "当前装置版本系列与目标版本系列不相同"; // return "当前装置版本系列与目标版本系列不相同";
} // }
} // }
//
//判断是否断开 // //判断是否断开
if (relist.stream().filter(w -> w.getComFlag() == 0).findAny().isPresent()) { // if (relist.stream().filter(w -> w.getComFlag() == 0).findAny().isPresent()) {
return "存在通讯中断设备"; // return "存在通讯中断设备";
} // }
//
//
Set<String> set = new HashSet<>(); // Set<String> set = new HashSet<>();
for (DeviceIpRVO d : relist) { // for (DeviceIpRVO d : relist) {
set.add(d.getIp()); // set.add(d.getIp());
} // }
Iterator<String> iterator = set.iterator(); // Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) { // while (iterator.hasNext()) {
List<UpDevVO> devIndex = new ArrayList<>(); // List<UpDevVO> devIndex = new ArrayList<>();
DeviceIpRVO deviceIpRVO = new DeviceIpRVO(); // DeviceIpRVO deviceIpRVO = new DeviceIpRVO();
String ip = iterator.next(); // String ip = iterator.next();
for (DeviceIpRVO d : relist) { // for (DeviceIpRVO d : relist) {
UpDevVO upDevVO = new UpDevVO(); // UpDevVO upDevVO = new UpDevVO();
upDevVO.setDevIndex(d.getDevIndex()); // upDevVO.setDevIndex(d.getDevIndex());
upDevVO.setDevName(d.getDevName()); // upDevVO.setDevName(d.getDevName());
if (ip.equals(d.getIp())) { // if (ip.equals(d.getIp())) {
devIndex.add(upDevVO); // devIndex.add(upDevVO);
} // }
} // }
deviceIpRVO.setIp(ip); // deviceIpRVO.setIp(ip);
deviceIpRVO.setDevlist(devIndex); // deviceIpRVO.setDevlist(devIndex);
resTemlist.add(deviceIpRVO); // resTemlist.add(deviceIpRVO);
} // }
} else { // } else {
return "存在未知错误"; // return "存在未知错误";
} // }
for (DeviceIpRVO deviceIpRVO : resTemlist) { // for (DeviceIpRVO deviceIpRVO : resTemlist) {
String ip = deviceIpRVO.getIp(); // String ip = deviceIpRVO.getIp();
List<UpDevVO> devlist = deviceIpRVO.getDevlist(); // List<UpDevVO> devlist = deviceIpRVO.getDevlist();
UpDataVO upDataVO = new UpDataVO(); // UpDataVO upDataVO = new UpDataVO();
UpParamVO upParamVO = new UpParamVO(); // UpParamVO upParamVO = new UpParamVO();
upDataVO.setTerminal(devlist); // upDataVO.setTerminal(devlist);
upDataVO.setType("180"); // upDataVO.setType("180");
upDataVO.setEdIndex(edIndex); // upDataVO.setEdIndex(edIndex);
upDataVO.setUserIndex(RequestUtil.getUserIndex()); // upDataVO.setUserIndex(RequestUtil.getUserIndex());
JSONObject jsonstr = new JSONObject(upDataVO); // JSONObject jsonstr = new JSONObject(upDataVO);
Integer len = jsonstr.toString().length(); // Integer len = jsonstr.toString().length();
upParamVO.setData(upDataVO); // upParamVO.setData(upDataVO);
upParamVO.setLen(len.toString()); // upParamVO.setLen(len.toString());
JSONObject jsonObject = new JSONObject(upParamVO); // JSONObject jsonObject = new JSONObject(upParamVO);
String str = jsonObject.toString(); // String str = jsonObject.toString();
socketClient.sentUpgrades(str, ip, socketPort, RequestUtil.getLoginName(), edIndex, devlist); // socketClient.sentUpgrades(str, ip, socketPort, RequestUtil.getLoginName(), edIndex, devlist);
} // }
return "运行成功"; // return "运行成功";
} // }
//
@Override // @Override
public String closeUpgrades(List<String> devList) { // public String closeUpgrades(List<String> devList) {
List<DeviceIpRVO> relist = lineMapper.getDevicesIp(devList); // List<DeviceIpRVO> relist = lineMapper.getDevicesIp(devList);
if(CollectionUtil.isEmpty(relist)){ // if(CollectionUtil.isEmpty(relist)){
return "前置机为空"; // return "前置机为空";
}else { // }else {
List<String> nodeIp = relist.stream().map(DeviceIpRVO::getIp).distinct().collect(Collectors.toList()); // List<String> nodeIp = relist.stream().map(DeviceIpRVO::getIp).distinct().collect(Collectors.toList());
for(String ip: nodeIp){ // for(String ip: nodeIp){
List<DeviceIpRVO> devLl= relist.stream().filter(item->item.getIp().equals(ip)).collect(Collectors.toList()); // List<DeviceIpRVO> devLl= relist.stream().filter(item->item.getIp().equals(ip)).collect(Collectors.toList());
if(CollectionUtil.isEmpty(devLl)){ // if(CollectionUtil.isEmpty(devLl)){
return "出错啦"; // return "出错啦";
} // }
//
List<JSONObject> list = new ArrayList<>(); // List<JSONObject> list = new ArrayList<>();
for(DeviceIpRVO devRVO:devLl){ // for(DeviceIpRVO devRVO:devLl){
JSONObject dev = new JSONObject(); // JSONObject dev = new JSONObject();
dev.put("devIndex",devRVO.getDevIndex()); // dev.put("devIndex",devRVO.getDevIndex());
dev.put("devName",devRVO.getDevName()); // dev.put("devName",devRVO.getDevName());
list.add(dev); // list.add(dev);
} // }
JSONObject jsonObject = new JSONObject(); // JSONObject jsonObject = new JSONObject();
jsonObject.set("terminal", list); // jsonObject.set("terminal", list);
jsonObject.set("type", 182); // jsonObject.set("type", 182);
JSONObject jsonObject1 = new JSONObject(); // JSONObject jsonObject1 = new JSONObject();
jsonObject1.set("len", 0); // jsonObject1.set("len", 0);
jsonObject1.set("data", jsonObject); // jsonObject1.set("data", jsonObject);
socketClient.cancelUp(jsonObject1.toString(),ip,socketPort,devLl.size()); // socketClient.cancelUp(jsonObject1.toString(),ip,socketPort,devLl.size());
} // }
} // }
return "取消命令发送成功"; // return "取消命令发送成功";
} // }
//
@Override // @Override
public String restartDev(List<String> devList) { // public String restartDev(List<String> devList) {
List<DeviceIpRVO> relist = lineMapper.getDevicesIp(devList); // List<DeviceIpRVO> relist = lineMapper.getDevicesIp(devList);
if(CollUtil.isEmpty(relist)){ // if(CollUtil.isEmpty(relist)){
return "前置机为空"; // return "前置机为空";
}else { // }else {
List<String> nodeIp = relist.stream().map(DeviceIpRVO::getIp).distinct().collect(Collectors.toList()); // List<String> nodeIp = relist.stream().map(DeviceIpRVO::getIp).distinct().collect(Collectors.toList());
for(String ip: nodeIp){ // for(String ip: nodeIp){
List<DeviceIpRVO> devLl = relist.stream().filter(item->item.getIp().equals(ip)).collect(Collectors.toList()); // List<DeviceIpRVO> devLl = relist.stream().filter(item->item.getIp().equals(ip)).collect(Collectors.toList());
if(CollUtil.isEmpty(devLl)){ // if(CollUtil.isEmpty(devLl)){
return "出错啦"; // return "出错啦";
} // }
//
List<JSONObject> list = new ArrayList<>(); // List<JSONObject> list = new ArrayList<>();
List<String> devIn = new ArrayList<>(); // List<String> devIn = new ArrayList<>();
for(DeviceIpRVO devRVO:devLl){ // for(DeviceIpRVO devRVO:devLl){
devIn.add(devRVO.getDevIndex()); // devIn.add(devRVO.getDevIndex());
JSONObject dev = new JSONObject(); // JSONObject dev = new JSONObject();
dev.set("devIndex", devRVO.getDevIndex()); // dev.set("devIndex", devRVO.getDevIndex());
dev.set("devName", devRVO.getDevName()); // dev.set("devName", devRVO.getDevName());
list.add(dev); // list.add(dev);
} // }
//
JSONObject jsonObject = new JSONObject(); // JSONObject jsonObject = new JSONObject();
jsonObject.set("terminal", list); // jsonObject.set("terminal", list);
jsonObject.set("type", 181); // jsonObject.set("type", 181);
jsonObject.set("userIndex", RequestUtil.getUserIndex()); // jsonObject.set("userIndex", RequestUtil.getUserIndex());
JSONObject jsonObject1 = new JSONObject(); // JSONObject jsonObject1 = new JSONObject();
jsonObject1.set("len", 0); // jsonObject1.set("len", 0);
jsonObject1.set("data", jsonObject); // jsonObject1.set("data", jsonObject);
//
socketClient.restartDev(jsonObject1.toString(),ip,socketPort,devIn); // socketClient.restartDev(jsonObject1.toString(),ip,socketPort,devIn);
} // }
} // }
return "命令发送成功"; // return "命令发送成功";
} // }
@Override @Override
public void updateDevCheckTime(String devId, String thisTimeCheck, String nextTimeCheck) { public void updateDevCheckTime(String devId, String thisTimeCheck, String nextTimeCheck) {

View File

@@ -148,6 +148,8 @@ public interface LineMapper extends BaseMapper<Line> {
*/ */
List<Line> getLineByCondition(@Param("ids") List<String> ids, @Param("deviceInfoParam") DeviceInfoParam deviceInfoParam); List<Line> getLineByCondition(@Param("ids") List<String> ids, @Param("deviceInfoParam") DeviceInfoParam deviceInfoParam);
List<Line> getLineByConditionBySearchValue(@Param("ids") List<String> ids, @Param("deviceInfoParam") DeviceInfoParam deviceInfoParam);
/** /**
* 查询终端信息 * 查询终端信息
* *

View File

@@ -88,7 +88,9 @@
voltage.name busBarname, voltage.name busBarname,
pq_voltage.scale voltageLevel, pq_voltage.scale voltageLevel,
bd.name bdName, bd.name bdName,
gd.name gdName gd.name gdName,
supervision_user_report.project_name objName
from pq_dept_line pq_dept_line from pq_dept_line pq_dept_line
inner join pq_line point on pq_dept_line.line_id = point.id inner join pq_line point on pq_dept_line.line_id = point.id
inner join pq_line_detail lineDetail on point.id = lineDetail.id inner join pq_line_detail lineDetail on point.id = lineDetail.id
@@ -98,6 +100,7 @@
inner join pq_device device on dev.id = device.id inner join pq_device device on dev.id = device.id
inner join pq_line bd on dev.pid = bd.id inner join pq_line bd on dev.pid = bd.id
inner join pq_line gd on bd.pid = gd.id inner join pq_line gd on bd.pid = gd.id
left join supervision_user_report on lineDetail.Obj_Id = supervision_user_report.id
where device.Dev_Model = 1 where device.Dev_Model = 1
and point.state = 1 and point.state = 1
and device.Dev_Data_Type in and device.Dev_Data_Type in

View File

@@ -147,8 +147,6 @@
<!--华丽分割线 ++++ --> <!--华丽分割线 ++++ -->
<select id="getUnBindList" resultType="TerminalTree"> <select id="getUnBindList" resultType="TerminalTree">
select id, pid, name, level, sort select id, pid, name, level, sort
from pq_line from pq_line
@@ -294,9 +292,6 @@
#{item.id} #{item.id}
</foreach> </foreach>
</if> </if>
<if test="deviceInfoParam.searchValue!=null and deviceInfoParam.searchValue!='' and deviceInfoParam.lineOrDevice==0">
AND t1.name like CONCAT(CONCAT('%', #{deviceInfoParam.searchValue}), '%')
</if>
<!-- xy --> <!-- xy -->
<choose> <choose>
<when test="deviceInfoParam.statFlag"> <when test="deviceInfoParam.statFlag">
@@ -344,9 +339,6 @@
#{item.id} #{item.id}
</foreach> </foreach>
</if> </if>
<if test="deviceInfoParam.searchValue!=null and deviceInfoParam.searchValue!='' and deviceInfoParam.lineOrDevice==1">
AND t1.name like CONCAT(CONCAT('%', #{deviceInfoParam.searchValue}), '%')
</if>
<if test="devIds!=null and devIds.size()!=0"> <if test="devIds!=null and devIds.size()!=0">
AND t1.id IN AND t1.id IN
<foreach collection="devIds" open="(" close=")" item="item" separator=","> <foreach collection="devIds" open="(" close=")" item="item" separator=",">
@@ -381,8 +373,6 @@
</where> </where>
</select> </select>
<select id="getVoltageIdByScale" resultType="String"> <select id="getVoltageIdByScale" resultType="String">
@@ -901,7 +891,8 @@
<select id="getNewDeviceRunStatistics" resultType="LineFlowMealDetailVO"> <select id="getNewDeviceRunStatistics" resultType="LineFlowMealDetailVO">
select id,pid,pids,name,level,updateTime,runFlag,comFlag,deviceId,substation,flowMeal,round(statisValue,2) statisValue,statisValue/flowMeal as flowProportion from select id,pid,pids,name,level,updateTime,runFlag,comFlag,deviceId,substation,flowMeal,round(statisValue,2)
statisValue,statisValue/flowMeal as flowProportion from
( (
select select
a.id, a.id,
@@ -1016,24 +1007,25 @@
</select> </select>
<select id="getLineList" resultType="string"> <select id="getLineList" resultType="string">
SELECT SELECT A1.Id
A1.Id FROM pq_line A1,
FROM
pq_line A1,
pq_line A2, pq_line A2,
pq_line A3, pq_line A3,
pq_line_detail B, pq_line_detail B,
pq_device C pq_device C
WHERE WHERE A1.Level = 6
A1.Level = 6 AND A1.Id = B.Id AND AND A1.Id = B.Id
A1.Pid = A2.Id AND A2.Pid = A3.Id AND A3.Id = C.Id AND AND A1.Pid = A2.Id
C.Dev_Model = 1 AND C.Dev_Data_Type IN (1,2) AND C.Run_Flag = 0 AND A2.Pid = A3.Id
AND A3.Id = C.Id
AND C.Dev_Model = 1
AND C.Dev_Data_Type IN (1, 2)
AND C.Run_Flag = 0
</select> </select>
<select id="getTerminalBaseExcel" resultType="TerminalBaseExcel"> <select id="getTerminalBaseExcel" resultType="TerminalBaseExcel">
SELECT SELECT pj.NAME projectName,
pj.NAME projectName,
area.NAME provinceName, area.NAME provinceName,
gd.NAME gdName, gd.NAME gdName,
sub.NAME substationName, sub.NAME substationName,
@@ -1076,8 +1068,7 @@
de.Stat_Flag, de.Stat_Flag,
dic3.name lineGrade, dic3.name lineGrade,
de.Remark de.Remark
FROM FROM pq_line line
pq_line line
INNER JOIN pq_line vol ON line.pid = vol.id INNER JOIN pq_line vol ON line.pid = vol.id
INNER JOIN pq_line dev ON vol.pid = dev.id INNER JOIN pq_line dev ON vol.pid = dev.id
INNER JOIN pq_line sub ON dev.pid = sub.id INNER JOIN pq_line sub ON dev.pid = sub.id
@@ -1124,7 +1115,11 @@
</select> </select>
<select id="getDeviceList" resultType="string"> <select id="getDeviceList" resultType="string">
SELECT Id FROM pq_device WHERE Dev_Model = 1 AND Dev_Data_Type IN (1,2) AND Run_Flag = 0 SELECT Id
FROM pq_device
WHERE Dev_Model = 1
AND Dev_Data_Type IN (1, 2)
AND Run_Flag = 0
</select> </select>
@@ -1161,20 +1156,17 @@
<select id="getLineBySubStation" resultType="com.njcn.device.biz.pojo.dto.LineDevGetDTO"> <select id="getLineBySubStation" resultType="com.njcn.device.biz.pojo.dto.LineDevGetDTO">
SELECT SELECT pq_line.id pointId,
pq_line.id pointId,
lineDetail.Time_Interval timeInterval, lineDetail.Time_Interval timeInterval,
lineDetail.obj_Id objId, lineDetail.obj_Id objId,
dev.id devId, dev.id devId,
device.com_flag device.com_flag
FROM FROM pq_line pq_line
pq_line pq_line
INNER JOIN pq_line_detail lineDetail ON pq_line.id = lineDetail.id INNER JOIN pq_line_detail lineDetail ON pq_line.id = lineDetail.id
INNER JOIN pq_line busBar ON pq_line.pid = busBar.id INNER JOIN pq_line busBar ON pq_line.pid = busBar.id
INNER JOIN pq_line dev ON busBar.pid = dev.id INNER JOIN pq_line dev ON busBar.pid = dev.id
INNER JOIN pq_device device ON dev.id = device.id INNER JOIN pq_device device ON dev.id = device.id
WHERE WHERE (pq_line.LEVEL = 6
(pq_line.LEVEL = 6
AND pq_line.state = 1 AND pq_line.state = 1
AND device.Dev_Model = 1 AND device.Dev_Model = 1
AND device.Run_Flag = 0 AND device.Run_Flag = 0
@@ -1185,7 +1177,8 @@
</select> </select>
<select id="getMonitorListDetail" resultType="com.njcn.device.biz.pojo.dto.LineDevGetDTO"> <select id="getMonitorListDetail" resultType="com.njcn.device.biz.pojo.dto.LineDevGetDTO">
select line.id pointId,line.name pointName, dev.id devId,0 type,1 lineType,lineDetail.Time_Interval as timeInterval select line.id pointId,line.name pointName, dev.id devId,0 type,1 lineType,lineDetail.Time_Interval as
timeInterval
from pq_line line from pq_line line
inner join pq_line_detail lineDetail on line.id = lineDetail.id inner join pq_line_detail lineDetail on line.id = lineDetail.id
inner join pq_line subv on line.pid = subv.id inner join pq_line subv on line.pid = subv.id
@@ -1291,8 +1284,7 @@
</where> </where>
</select> </select>
<select id="getDevInfo" resultType="com.njcn.device.pq.pojo.advanced.UpDevVO"> <select id="getDevInfo" resultType="com.njcn.device.pq.pojo.advanced.UpDevVO">
select select dev.id as devIndex,
dev.id as devIndex,
dev.name as devName dev.name as devName
from pq_line line, from pq_line line,
pq_line vo, pq_line vo,
@@ -1379,7 +1371,8 @@
dev.NAME AS devName, dev.NAME AS devName,
pd.Dev_Series AS devSeries, pd.Dev_Series AS devSeries,
pd.ip AS ip, pd.ip AS ip,
round(ifnull(d.flow,( SELECT flow FROM cld_flow_meal WHERE type = 0 AND flag = 1 )) + ifnull( d1.flow, 0 ),2) AS flowMeal, round(ifnull(d.flow,( SELECT flow FROM cld_flow_meal WHERE type = 0 AND flag = 1 )) + ifnull( d1.flow, 0 ),2) AS
flowMeal,
round(ifnull( m.Actual_Value / 1024 / 1024, 0 ),2) AS statisValue, round(ifnull( m.Actual_Value / 1024 / 1024, 0 ),2) AS statisValue,
pd.Sim AS sim , pd.Sim AS sim ,
pld.Remark AS remark pld.Remark AS remark
@@ -1398,8 +1391,10 @@
LEFT JOIN cld_dev_meal c ON dev.id = c.line_id LEFT JOIN cld_dev_meal c ON dev.id = c.line_id
LEFT JOIN cld_flow_meal d ON c.Base_Meal_Id = d.id LEFT JOIN cld_flow_meal d ON c.Base_Meal_Id = d.id
LEFT JOIN cld_flow_meal d1 ON c.Ream_Meal_Id = d1.id LEFT JOIN cld_flow_meal d1 ON c.Ream_Meal_Id = d1.id
LEFT JOIN cld_month_flow m ON dev.id = m.Dev_Id AND m.time_id between #{param.searchBeginTime} and #{param.searchEndTime} LEFT JOIN cld_month_flow m ON dev.id = m.Dev_Id AND m.time_id between #{param.searchBeginTime} and
LEFT JOIN (SELECT dev_index,avg( online_min /( online_min + offline_min ))* 100 onlineRate FROM r_stat_onlinerate_d #{param.searchEndTime}
LEFT JOIN (SELECT dev_index,avg( online_min /( online_min + offline_min ))* 100 onlineRate FROM
r_stat_onlinerate_d
WHERE time_id BETWEEN #{param.searchBeginTime} AND #{param.searchEndTime} WHERE time_id BETWEEN #{param.searchBeginTime} AND #{param.searchEndTime}
GROUP BY dev_index) a on a.dev_index=dev.Id GROUP BY dev_index) a on a.dev_index=dev.Id
LEFT JOIN (select line_index lineId,avg(real_time/due_time)*100 integrityData from r_stat_integrity_d LEFT JOIN (select line_index lineId,avg(real_time/due_time)*100 integrityData from r_stat_integrity_d
@@ -1454,8 +1449,7 @@
lineName lineName
</select> </select>
<select id="selectLineDetail" resultType="com.njcn.device.biz.pojo.dto.LineDTO"> <select id="selectLineDetail" resultType="com.njcn.device.biz.pojo.dto.LineDTO">
SELECT SELECT line.id AS lineId,
line.id AS lineId,
dev.id AS devId, dev.id AS devId,
detail.Time_Interval AS timeInterval, detail.Time_Interval AS timeInterval,
vg.Scale AS voltageLevel, vg.Scale AS voltageLevel,
@@ -1464,15 +1458,13 @@
detail.PT_Phase_Type AS ptPhaseType, detail.PT_Phase_Type AS ptPhaseType,
detail.Obj_Id AS objId, detail.Obj_Id AS objId,
detail.Big_Obj_Type AS bigObjType detail.Big_Obj_Type AS bigObjType
FROM FROM pq_line line,
pq_line line,
pq_line_detail detail, pq_line_detail detail,
pq_line vo, pq_line vo,
pq_voltage vg, pq_voltage vg,
pq_line dev, pq_line dev,
pq_device pqd pq_device pqd
WHERE WHERE line.id = detail.id
line.id = detail.id
AND vo.id = line.pid AND vo.id = line.pid
AND dev.id = vo.pid AND dev.id = vo.pid
AND vo.id = vg.id AND vo.id = vg.id
@@ -1511,19 +1503,17 @@
</select> </select>
<select id="getCustomDetailByLineId" resultType="map"> <select id="getCustomDetailByLineId" resultType="map">
SELECT SELECT line.id AS lineId,
line.id AS lineId,
CONCAT(CONCAT(CONCAT(sub.NAME, '_'), vo.NAME), CONCAT('_', line.NAME)) AS lineName, CONCAT(CONCAT(CONCAT(sub.NAME, '_'), vo.NAME), CONCAT('_', line.NAME)) AS lineName,
CONCAT(CONCAT(COALESCE(detail.pt1, 'N/A'), ':'), COALESCE(detail.pt2, 'N/A')) AS pt, CONCAT(detail.pt1, ':', detail.pt2) AS pt,
CONCAT(CONCAT(COALESCE(detail.ct1, 'N/A'), ':'), COALESCE(detail.ct2, 'N/A')) AS ct, CONCAT(detail.ct1, ':', detail.ct2) AS ct,
detail.Dev_Capacity AS Dev_Capacity, detail.Dev_Capacity AS Dev_Capacity,
detail.Short_Capacity AS Short_Capacity, detail.Short_Capacity AS Short_Capacity,
detail.Standard_Capacity AS Standard_Capacity, detail.Standard_Capacity AS Standard_Capacity,
detail.Deal_Capacity AS Deal_Capacity, detail.Deal_Capacity AS Deal_Capacity,
pqd.This_Time_Check AS This_Time_Check, pqd.This_Time_Check AS This_Time_Check,
dic.NAME AS voltageLevel dic.NAME AS voltageLevel
FROM FROM pq_line line
pq_line line
JOIN pq_line_detail detail ON line.id = detail.id JOIN pq_line_detail detail ON line.id = detail.id
JOIN pq_line vo ON vo.id = line.pid JOIN pq_line vo ON vo.id = line.pid
JOIN pq_line dev ON dev.id = vo.pid JOIN pq_line dev ON dev.id = vo.pid
@@ -1531,8 +1521,7 @@
JOIN pq_device pqd ON pqd.id = dev.id JOIN pq_device pqd ON pqd.id = dev.id
JOIN sys_dict_data dic ON vg.scale = dic.id JOIN sys_dict_data dic ON vg.scale = dic.id
JOIN pq_line sub ON sub.id = dev.pid JOIN pq_line sub ON sub.id = dev.pid
WHERE WHERE line.id = #{lineId}
line.id = #{lineId}
</select> </select>
<select id="selectByIds" resultType="com.njcn.device.pq.pojo.vo.LineDetailVO$Detail"> <select id="selectByIds" resultType="com.njcn.device.pq.pojo.vo.LineDetailVO$Detail">
@@ -1559,7 +1548,9 @@
vg.Scale as voltageLevel, vg.Scale as voltageLevel,
voltage.name as volName, voltage.name as volName,
lineDetail.Power_Flag powerFlag, lineDetail.Power_Flag powerFlag,
lineDetail.Run_Flag lineRunType lineDetail.Run_Flag lineRunType,
lineDetail.Obj_Id objId,
lineDetail.Obj_Name objName
FROM FROM
pq_line voltage, pq_line voltage,
pq_line device, pq_line device,
@@ -1631,8 +1622,7 @@
</select> </select>
<select id="getDeviceDetailData" resultType="DeviceVO"> <select id="getDeviceDetailData" resultType="DeviceVO">
SELECT SELECT DISTINCT gd.NAME gdName,
DISTINCT gd.NAME gdName,
substation.NAME subName, substation.NAME subName,
pq_line.id devIndex, pq_line.id devIndex,
pq_line.NAME NAME, pq_line.NAME NAME,
@@ -1640,13 +1630,11 @@
pq_device.Dev_Type, pq_device.Dev_Type,
pq_device.IP, pq_device.IP,
pq_device.Run_Flag pq_device.Run_Flag
FROM FROM pq_line pq_line,
pq_line pq_line,
pq_device pq_device, pq_device pq_device,
pq_line substation, pq_line substation,
pq_line gd pq_line gd
WHERE WHERE pq_line.id = pq_device.id
pq_line.id = pq_device.id
AND pq_line.pid = substation.id AND pq_line.pid = substation.id
AND substation.pid = gd.id AND substation.pid = gd.id
AND pq_line.id = #{id} AND pq_line.id = #{id}
@@ -1714,19 +1702,16 @@
</select> </select>
<select id="getNoDataLine" resultType="com.njcn.device.pq.pojo.vo.LineDetailVO$noDataLineInfo"> <select id="getNoDataLine" resultType="com.njcn.device.pq.pojo.vo.LineDetailVO$noDataLineInfo">
select select pl3.Id lineId,
pl3.Id lineId,
pl3.Name lineName, pl3.Name lineName,
pd.Id devId, pd.Id devId,
pl1.name devName, pl1.name devName,
pd.Update_Time pd.Update_Time
from from pq_device pd
pq_device pd
left join pq_line pl1 on pd.Id = pl1.Id left join pq_line pl1 on pd.Id = pl1.Id
left join pq_line pl2 on pl1.Id = pl2.pId left join pq_line pl2 on pl1.Id = pl2.pId
left join pq_line pl3 on pl2.Id = pl3.pId left join pq_line pl3 on pl2.Id = pl3.pId
where where pd.Dev_Model = 1
pd.Dev_Model = 1
and pd.Run_Flag = 0 and pd.Run_Flag = 0
and pl1.state = 1 and pl1.state = 1
and pl3.Id is not null and pl3.Id is not null
@@ -1805,7 +1790,8 @@
</foreach> </foreach>
</if> </if>
<if test="param.searchValue!=null and param.searchValue!=''"> <if test="param.searchValue!=null and param.searchValue!=''">
AND (t1.name like CONCAT('%', #{param.searchValue}, '%') or t2.Power_Substation_Name like CONCAT('%', #{param.searchValue}, '%')) AND (t1.name like CONCAT('%', #{param.searchValue}, '%') or t2.Power_Substation_Name like CONCAT('%',
#{param.searchValue}, '%'))
</if> </if>
</where> </where>
@@ -1828,15 +1814,13 @@
</select> </select>
<select id="getLineByDeviceId" resultType="com.njcn.device.pq.pojo.dto.MonitorInfo"> <select id="getLineByDeviceId" resultType="com.njcn.device.pq.pojo.dto.MonitorInfo">
SELECT SELECT pq_line_detail.id id,
pq_line_detail.id id,
line.Name name, line.Name name,
pq_line_detail.Num lineNo, pq_line_detail.Num lineNo,
s1.Name voltageLevel, s1.Name voltageLevel,
pq_line_detail.PT_Type ptType, pq_line_detail.PT_Type ptType,
pq_line_detail.Run_Flag status pq_line_detail.Run_Flag status
FROM FROM pq_line_detail
pq_line_detail
LEFT JOIN pq_line line ON pq_line_detail.Id = line.Id LEFT JOIN pq_line line ON pq_line_detail.Id = line.Id
INNER JOIN pq_line voltage on voltage.id = line.Pid INNER JOIN pq_line voltage on voltage.id = line.Pid
LEFT JOIN pq_voltage ON pq_voltage.id = voltage.id LEFT JOIN pq_voltage ON pq_voltage.id = voltage.id
@@ -1845,10 +1829,15 @@
</select> </select>
<select id="getLineAndLineDetail" resultType="TerminalTree"> <select id="getLineAndLineDetail" resultType="TerminalTree">
select select t1.id,
t1.id,t1.name,t1.pid,t2.obj_id,t1.sort,t1.pids,t1.level t1.name,
from t1.pid,
pq_line t1 inner join pq_line_detail t2 on t1.id = t2.id t2.obj_id,
t1.sort,
t1.pids,
t1.level
from pq_line t1
inner join pq_line_detail t2 on t1.id = t2.id
where t1.state = 1 where t1.state = 1
</select> </select>
<select id="getLineDeviceByDevIds" resultType="com.njcn.device.pq.pojo.vo.DevDetailVO"> <select id="getLineDeviceByDevIds" resultType="com.njcn.device.pq.pojo.vo.DevDetailVO">
@@ -1904,7 +1893,9 @@
</select> </select>
<select id="getSubIdByPid" resultType="String"> <select id="getSubIdByPid" resultType="String">
SELECT id from pq_line where pid = #{pid} SELECT id
from pq_line
where pid = #{pid}
</select> </select>
<select id="getDeviceIdByJbPowerFlag" resultType="java.lang.String"> <select id="getDeviceIdByJbPowerFlag" resultType="java.lang.String">
select select
@@ -2021,5 +2012,58 @@
</select> </select>
<select id="getLineByConditionBySearchValue" resultType="com.njcn.device.pq.pojo.po.Line">
SELECT DISTINCT
t1.*
FROM
pq_line t1,
pq_line_detail t2,
pq_line voltage,
pq_line device,
pq_line substation
WHERE
t1.state = 1
AND t1.id = t2.id
AND t1.pid = voltage.id
AND voltage.pid = device.id
AND device.pid = substation.id
and
t1.id in
<foreach collection="ids" separator="," open="(" close=")" item="item">
#{item}
</foreach>
<if test="deviceInfoParam.monitorFlag!=2 and deviceInfoParam.monitorFlag!=null">
and t2.Monitor_Flag = #{deviceInfoParam.monitorFlag}
</if>
<if test="deviceInfoParam.powerFlag!=2 and deviceInfoParam.powerFlag!=null ">
and t2.Power_Flag = #{deviceInfoParam.powerFlag}
</if>
<if test="deviceInfoParam.lineRunFlag!=null ">
and t2.Run_Flag = #{deviceInfoParam.lineRunFlag}
</if>
<if test="deviceInfoParam.lineGrade!='' and deviceInfoParam.lineGrade!=null">
and t2.line_grade = #{deviceInfoParam.lineGrade}
</if>
<if test="deviceInfoParam.loadType!=null and deviceInfoParam.loadType.size()!=0">
AND t2.Load_Type in
<foreach collection="deviceInfoParam.loadType" open="(" close=")" item="item" separator=",">
#{item.id}
</foreach>
</if>
<if test="deviceInfoParam.searchValue!=null and deviceInfoParam.searchValue!=''">
and (
t1.name like CONCAT('%', #{deviceInfoParam.searchValue}, '%')
or t2.Obj_Name like CONCAT('%', #{deviceInfoParam.searchValue}, '%')
or device.NAME like CONCAT('%', #{deviceInfoParam.searchValue}, '%')
or substation.NAME like CONCAT('%', #{deviceInfoParam.searchValue},'%')
)
</if>
<!-- xy -->
<choose>
<when test="deviceInfoParam.statFlag">
AND t2.Stat_Flag = 1
</when>
</choose>
<!-- -->
</select>
</mapper> </mapper>

View File

@@ -235,4 +235,10 @@ public interface LineService extends IService<Line> {
* 终端运行状态修改时,同时调整监测点的运行状态 * 终端运行状态修改时,同时调整监测点的运行状态
*/ */
void updateLineRunFlag(String id, Integer status); void updateLineRunFlag(String id, Integer status);
/**
* 自动修改验证pids是否正确
*/
void updatePids();
} }

View File

@@ -83,10 +83,9 @@ public class DeptLineServiceImpl extends ServiceImpl<DeptLineMapper, DeptLine> i
List<String> deptList = Arrays.asList("130700000000", "130300000000", "130800000000", "130200000000", "131000000000"); List<String> deptList = Arrays.asList("130700000000", "130300000000", "130800000000", "130200000000", "131000000000");
Dept data = deptFeignClient.getDeptById(deptLineParam.getId()).getData(); Dept data = deptFeignClient.getDeptById(deptLineParam.getId()).getData();
if (deptList.contains(data.getArea())) { if (deptList.contains(data.getArea())) {
List<String> lineIds = list.stream().map(LineDetail::getId).collect(Collectors.toList());
detailMapper.update(null, new LambdaUpdateWrapper<LineDetail>() detailMapper.update(null, new LambdaUpdateWrapper<LineDetail>()
.set(LineDetail::getActualArea, data.getArea()) .set(LineDetail::getActualArea, data.getArea())
.in(LineDetail::getId, lineIds)); .in(LineDetail::getId, ids));
} }
} }
} }

View File

@@ -6,9 +6,11 @@ import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; 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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum; import com.njcn.common.pojo.enums.common.DataStateEnum;
@@ -45,6 +47,7 @@ import com.njcn.influx.imapper.PqsCommunicateMapper;
import com.njcn.influx.pojo.po.PqsCommunicate; import com.njcn.influx.pojo.po.PqsCommunicate;
import com.njcn.influx.query.InfluxQueryWrapper; import com.njcn.influx.query.InfluxQueryWrapper;
import com.njcn.supervision.pojo.vo.user.NewUserReportVO; import com.njcn.supervision.pojo.vo.user.NewUserReportVO;
import com.njcn.supervision.pojo.vo.user.UserReportVO;
import com.njcn.system.api.AreaFeignClient; import com.njcn.system.api.AreaFeignClient;
import com.njcn.system.api.DicDataFeignClient; import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum; import com.njcn.system.enums.DicDataTypeEnum;
@@ -616,6 +619,11 @@ public class LineServiceImpl extends ServiceImpl<LineMapper, Line> implements Li
lineLineDTO.setLinename(lineName); lineLineDTO.setLinename(lineName);
lineLineDTO.setNum(lineDetail.getNum()); lineLineDTO.setNum(lineDetail.getNum());
lineLineDTO.setObjName(lineDetail.getObjName()); lineLineDTO.setObjName(lineDetail.getObjName());
lineLineDTO.setObjId(lineDetail.getObjId());
if(StringUtils.isNotEmpty(lineDetail.getObjId())){
UserReportVO userReportVO = userLedgerService.getUserReportById(lineDetail.getObjId());
lineLineDTO.setObjName2(userReportVO.getProjectName());
}
lineLineDTO.setLoadType(dicDataFeignClient.getDicDataById(lineDetail.getLoadType()).getData().getName()); lineLineDTO.setLoadType(dicDataFeignClient.getDicDataById(lineDetail.getLoadType()).getData().getName());
//电压使用母线电压 //电压使用母线电压
lineLineDTO.setVoltageLevel(dicDataFeignClient.getDicDataById(voltage.getScale()).getData().getName()); lineLineDTO.setVoltageLevel(dicDataFeignClient.getDicDataById(voltage.getScale()).getData().getName());
@@ -834,6 +842,82 @@ public class LineServiceImpl extends ServiceImpl<LineMapper, Line> implements Li
} }
} }
@Override
public void updatePids() {
List<Line> list = this.list();
List<String> strings = this.checkPidsError(list);
if(CollUtil.isNotEmpty(strings)){
for (String msg : strings) {
// 1. 按 | 分割成三部分
String[] parts = msg.split(" \\| ");
// 2. 提取节点 ID
String id = parts[0].replace("节点ID", "").trim();
// 3. 提取正确 pids去掉括号
String newPids = parts[2].replace("正确pids[", "").replace("]", "").trim();
this.update(new LambdaUpdateWrapper<Line>()
.set(Line::getPids, newPids)
.eq(Line::getId, id));
}
}
}
/**
* 校验所有节点 pids 是否正确
* 正确规则去掉开头0 + 去掉自身ID只保留祖先链
*/
public List<String> checkPidsError(List<Line> allList) {
List<String> errorList = new ArrayList<>();
Map<String, Line> idMap = allList.stream().collect(Collectors.toMap(Line::getId,Function.identity()));
for (Line node : allList) {
// 1. 生成正确格式的 pids你的规则
String correctPids = getCorrectPids(node.getId(), idMap);
// 2. 数据库存储的 pids
String dbPids = node.getPids() == null ? "" : node.getPids().trim();
// 3. 对比,不一致就是错误
if (!correctPids.equals(dbPids)) {
errorList.add("节点ID" + node.getId() +
" | 数据库pids[" + dbPids +
"] | 正确pids[" + correctPids + "]");
}
}
return errorList;
}
/**
* 核心:生成【你要求】的正确 pids
* 规则:
* 1. 向上遍历所有祖先
* 2. 去掉开头 0
* 3. 去掉最后一位自身ID
* 4. 用逗号拼接
*/
private String getCorrectPids(String nodeId, Map<String, Line> idMap) {
Deque<String> pathDeque = new LinkedList<>();
String currentId = nodeId;
// 向上收集所有节点(包含自身 + 所有祖先 + 0
while (currentId != null && !currentId.isEmpty()) {
Line node = idMap.get(currentId);
if (ObjectUtil.isNotNull(node)) {
// 头插,保证顺序正确
pathDeque.addFirst(currentId);
currentId = node.getPid();
}
}
// 转列表
List<String> path = new ArrayList<>(pathDeque);
// 1. 去掉开头的 0
if (!path.isEmpty() && "0".equals(path.get(0))) {
path.remove(0);
}
// 2. 去掉最后一位自身ID
if (!path.isEmpty()) {
path.remove(path.size() - 1);
}
// 拼接成最终正确 pids
return String.join(",", path);
}
@Override @Override
public List<Overlimit> getOverLimitByList(PollutionParamDTO pollutionParamDTO) { public List<Overlimit> getOverLimitByList(PollutionParamDTO pollutionParamDTO) {
@@ -908,6 +992,7 @@ public class LineServiceImpl extends ServiceImpl<LineMapper, Line> implements Li
areaLineInfoVO.setSubName(newUserReportVO.getProjectName()); areaLineInfoVO.setSubName(newUserReportVO.getProjectName());
areaLineInfoVO.setLat(newUserReportVO.getLatitude()); areaLineInfoVO.setLat(newUserReportVO.getLatitude());
areaLineInfoVO.setLng(newUserReportVO.getLongitude()); areaLineInfoVO.setLng(newUserReportVO.getLongitude());
areaLineInfoVO.setObjName(newUserReportVO.getProjectName());
} }
} }
} }

View File

@@ -13,10 +13,12 @@ import com.njcn.common.pojo.response.HttpResult;
import com.njcn.device.common.mapper.SuperDataMapper; import com.njcn.device.common.mapper.SuperDataMapper;
import com.njcn.device.common.service.GeneralDeviceService; import com.njcn.device.common.service.GeneralDeviceService;
import com.njcn.device.device.mapper.DevFuctionMapper; import com.njcn.device.device.mapper.DevFuctionMapper;
import com.njcn.device.device.service.DeviceProcessService;
import com.njcn.device.device.service.IDevMealService; import com.njcn.device.device.service.IDevMealService;
import com.njcn.device.device.service.IDevStrategyService; import com.njcn.device.device.service.IDevStrategyService;
import com.njcn.device.device.service.IDeviceService; import com.njcn.device.device.service.IDeviceService;
import com.njcn.device.line.service.LineService; import com.njcn.device.line.service.LineService;
import com.njcn.device.pq.constant.Param;
import com.njcn.device.pq.enums.LineBaseEnum; import com.njcn.device.pq.enums.LineBaseEnum;
import com.njcn.device.pq.pojo.dto.GeneralDeviceDTO; import com.njcn.device.pq.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pq.pojo.param.*; import com.njcn.device.pq.pojo.param.*;
@@ -84,6 +86,7 @@ public class TerminalMaintainServiceImpl implements TerminalMaintainService {
private final CldStatisticsFlowMapper cldStatisticsFlowMapper; private final CldStatisticsFlowMapper cldStatisticsFlowMapper;
private final LineService lineService; private final LineService lineService;
private final DeviceProcessService deviceProcessService;
@Override @Override
public List<TerminalMaintainVO> getTerminalMainList(TerminalMainQueryParam terminalMainQueryParam) { public List<TerminalMaintainVO> getTerminalMainList(TerminalMainQueryParam terminalMainQueryParam) {
@@ -184,14 +187,14 @@ public class TerminalMaintainServiceImpl implements TerminalMaintainService {
if (device.getRunFlag() == 0) { if (device.getRunFlag() == 0) {
newFlag = "投运"; newFlag = "投运";
} else if (device.getRunFlag() == 1) { } else if (device.getRunFlag() == 1) {
newFlag = "热备用"; newFlag = "检修";
} else if (device.getRunFlag() == 2) { } else if (device.getRunFlag() == 2) {
newFlag = "停运"; newFlag = "停运";
} }
if (device1.getRunFlag() == 0) { if (device1.getRunFlag() == 0) {
oldFlag = "投运"; oldFlag = "投运";
} else if (device1.getRunFlag() == 1) { } else if (device1.getRunFlag() == 1) {
oldFlag = "热备用"; oldFlag = "检修";
} else if (device1.getRunFlag() == 2) { } else if (device1.getRunFlag() == 2) {
oldFlag = "停运"; oldFlag = "停运";
} }
@@ -205,7 +208,19 @@ public class TerminalMaintainServiceImpl implements TerminalMaintainService {
terminalLogsNew.setObjIndex(device.getId()); terminalLogsNew.setObjIndex(device.getId());
terminalLogsNew.setTerminalDescribe(sb.toString()); terminalLogsNew.setTerminalDescribe(sb.toString());
terminalLogsNew.setIsPush(0); terminalLogsNew.setIsPush(0);
terminalLogsNew.setOperateType("update"); if(device.getRunFlag() == 0&&device1.getRunFlag()!=0){
terminalLogsNew.setOperateType(Param.DEL);
}
if(device1.getRunFlag() == 0&&device.getRunFlag()!=0){
terminalLogsNew.setOperateType(Param.ADD);
//判断device是否绑定进程号
DeviceProcess deviceProcess = new DeviceProcess();
deviceProcess.setId(device1.getId());
deviceProcess.setProcessNo(1);
deviceProcessService.saveOrUpdate(deviceProcess);
}
terminalLogsNew.setLogsType(data.getId()); terminalLogsNew.setLogsType(data.getId());
terminalLogsNew.setTerminalType(LineBaseEnum.DEVICE_LEVEL.getCode()); terminalLogsNew.setTerminalType(LineBaseEnum.DEVICE_LEVEL.getCode());
terminalLogsNew.setState(DataStateEnum.ENABLE.getCode()); terminalLogsNew.setState(DataStateEnum.ENABLE.getCode());

View File

@@ -27,6 +27,7 @@
supervision_user_report.status, supervision_user_report.status,
supervision_user_report.dev_id, supervision_user_report.dev_id,
supervision_user_report.line_id, supervision_user_report.line_id,
supervision_user_report.station_id,
supervision_user_report.second_assessment_id secondAssessmentId supervision_user_report.second_assessment_id secondAssessmentId
FROM supervision_user_report supervision_user_report FROM supervision_user_report supervision_user_report
WHERE ${ew.sqlSegment} WHERE ${ew.sqlSegment}

View File

@@ -17,6 +17,9 @@ import com.njcn.bpm.enums.BpmTaskStatusEnum;
import com.njcn.common.pojo.constant.PatternRegex; import com.njcn.common.pojo.constant.PatternRegex;
import com.njcn.common.pojo.enums.common.DataStateEnum; import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.pq.pojo.po.Line;
import com.njcn.device.substation.mapper.SubstationMapper;
import com.njcn.device.userledger.mapper.UserReportNormalMapper; import com.njcn.device.userledger.mapper.UserReportNormalMapper;
import com.njcn.device.userledger.mapper.UserReportPOMapper; import com.njcn.device.userledger.mapper.UserReportPOMapper;
import com.njcn.device.userledger.service.UserLedgerService; import com.njcn.device.userledger.service.UserLedgerService;
@@ -67,6 +70,7 @@ public class UserLedgerServiceImpl extends ServiceImpl<UserReportPOMapper, UserR
private final UserReportNormalMapper userReportNormalMapper; private final UserReportNormalMapper userReportNormalMapper;
private final UserReportSensitivePOService userReportSensitivePOService; private final UserReportSensitivePOService userReportSensitivePOService;
private final UserFeignClient userFeignClient; private final UserFeignClient userFeignClient;
private final LineMapper substationMapper;
@Override @Override
public List<UserLedgerVO> selectUserList(UserReportParam userReportParam) { public List<UserLedgerVO> selectUserList(UserReportParam userReportParam) {
@@ -171,7 +175,16 @@ public class UserLedgerServiceImpl extends ServiceImpl<UserReportPOMapper, UserR
userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time"); userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time");
Page<UserReportVO> page; Page<UserReportVO> page;
page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(userReportQueryParam), PageFactory.getPageSize(userReportQueryParam)), userReportVOQueryWrapper); page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(userReportQueryParam), PageFactory.getPageSize(userReportQueryParam)), userReportVOQueryWrapper);
Map<String,String> atationMap = new HashMap<>();
if(CollUtil.isNotEmpty(page.getRecords())){
List<String> stationIds = page.getRecords().stream().map(UserReportVO::getStationId).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
if(CollUtil.isNotEmpty(stationIds)){
List<Line> stationList = substationMapper.selectBatchIds(stationIds);
stationList.forEach(line -> atationMap.put(line.getId(), line.getName()));
}
}
page.getRecords().forEach(temp -> { page.getRecords().forEach(temp -> {
temp.setStationId(atationMap.getOrDefault(temp.getStationId(),"/"));
Integer needGovernance = 0; Integer needGovernance = 0;
if ( if (
CollectionUtil.newArrayList( CollectionUtil.newArrayList(

View File

@@ -0,0 +1,59 @@
package com.njcn.device.utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.pq.pojo.po.Line;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.Objects;
/**
* @Author: cdf
* @CreateTime: 2026-06-13
* @Description:
*/
@Component
@RequiredArgsConstructor
public class LineSortHelper {
private final LineMapper lineMapper;
/**
* 获取同一父节点下的最大 sort 值 + 1
* @param level 层级
* @return 下一个可用的 sort 值
*/
public Integer getNextSort(Integer level) {
LambdaQueryWrapper<Line> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(Line::getState, DataStateEnum.ENABLE.getCode())
.eq(Line::getLevel,level)
.orderByDesc(Line::getSort)
.last("limit 1");
Line maxSortLine = lineMapper.selectOne(wrapper);
if (Objects.nonNull(maxSortLine) && Objects.nonNull(maxSortLine.getSort())) {
return maxSortLine.getSort() + 1;
}
return 0;
}
public void handleSort(Integer level, Integer sort,Line line) {
int lastSort;
if (Objects.isNull(sort) || sort == 0) {
lastSort = getNextSort(level);
}else {
lastSort = sort;
}
line.setSort(lastSort);
}
public Integer handleSortBatch(Integer currentSort, Line line) {
line.setSort(currentSort);
return currentSort + 1;
}
}

View File

@@ -55,6 +55,8 @@
<version>1.1.0</version> <version>1.1.0</version>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@@ -56,6 +56,12 @@
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<!--mqtt相关依赖-->
<dependency>
<groupId>com.github.tocrhz</groupId>
<artifactId>mqtt-spring-boot-starter</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.jetbrains</groupId> <groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId> <artifactId>annotations</artifactId>

View File

@@ -6,9 +6,7 @@ import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date;
/** /**
* @author xxy * @author xxy
@@ -35,4 +33,7 @@ public class StatisticsParam implements Serializable {
@ApiModelProperty(name = "flag",value = "标识") @ApiModelProperty(name = "flag",value = "标识")
private Integer flag; private Integer flag;
@ApiModelProperty(name = "isDip",value = "是否只统计暂降")
private Boolean isDip;
} }

View File

@@ -76,7 +76,7 @@ public class AdvanceEventDetailVO {
private String sagsource; private String sagsource;
@ApiModelProperty(value = "开始时间") @ApiModelProperty(value = "开始时间")
@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss.SSS") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS",timezone = "GMT+8")
private LocalDateTime startTime; private LocalDateTime startTime;
@ApiModelProperty(value = "持续时间,单位秒") @ApiModelProperty(value = "持续时间,单位秒")

View File

@@ -40,6 +40,7 @@ import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutionException;
/** /**
* @author xxy * @author xxy
@@ -237,7 +238,7 @@ public class ReportController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON) @OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/createEventReport") @PostMapping("/createEventReport")
@ApiOperation("暂态事件报告导出") @ApiOperation("暂态事件报告导出")
public void createEventReport(@RequestBody @Validated List<String> index, HttpServletResponse response) throws IOException, InvalidFormatException { public void createEventReport(@RequestBody @Validated List<String> index, HttpServletResponse response) throws IOException, InvalidFormatException, ExecutionException, InterruptedException {
commMonitorEventReportService.createEventReport(index,response); commMonitorEventReportService.createEventReport(index,response);
} }
} }

View File

@@ -143,7 +143,7 @@ public class AreaInfoServiceImpl implements AreaInfoService {
) )
.ge(StringUtils.isNotBlank(deviceInfoParam.getSearchBeginTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(deviceInfoParam.getSearchBeginTime()))) .ge(StringUtils.isNotBlank(deviceInfoParam.getSearchBeginTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(deviceInfoParam.getSearchBeginTime())))
.le(StringUtils.isNotBlank(deviceInfoParam.getSearchEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(deviceInfoParam.getSearchEndTime()))) .le(StringUtils.isNotBlank(deviceInfoParam.getSearchEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(deviceInfoParam.getSearchEndTime())))
.orderByDesc(RmpEventDetailPO::getStartTime)); .orderByDesc(RmpEventDetailPO::getStartTime).last("limit 100"));
EventDetailNew eventDetailNew; EventDetailNew eventDetailNew;
for (RmpEventDetailPO eventDetail : eventDetails) { for (RmpEventDetailPO eventDetail : eventDetails) {
eventDetailNew = BeanUtil.copyProperties(eventDetail, EventDetailNew.class); eventDetailNew = BeanUtil.copyProperties(eventDetail, EventDetailNew.class);

View File

@@ -1609,7 +1609,7 @@ public class ReportServiceImpl implements ReportService {
createTitle(doc, "4. 总汇信息", "标题 1", 0, 15); createTitle(doc, "4. 总汇信息", "标题 1", 0, 15);
//查询参数 //查询参数
StatisticsParam param = new StatisticsParam(exportParam.getLineId(), exportParam.getSearchBeginTime(), exportParam.getSearchEndTime(), exportParam.getFlag()); StatisticsParam param = new StatisticsParam(exportParam.getLineId(), exportParam.getSearchBeginTime(), exportParam.getSearchEndTime(), exportParam.getFlag(),null);
//获取暂降原因字典 //获取暂降原因字典
List<DictData> reasonData = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName()).getData(); List<DictData> reasonData = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName()).getData();
//获取暂降类型字典 //获取暂降类型字典

View File

@@ -36,6 +36,12 @@
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.12</version>
</dependency>
</dependencies> </dependencies>

View File

@@ -130,4 +130,7 @@ public class LineDetailDataCommDTO {
@ApiModelProperty(name = "对象类型大类") @ApiModelProperty(name = "对象类型大类")
private String bigObjType; private String bigObjType;
@ApiModelProperty(name = "isDip",value = "是否只统计暂降")
private Boolean isDip;
} }

View File

@@ -9,6 +9,7 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutionException;
/** /**
* pqs * pqs
@@ -25,12 +26,12 @@ public interface CommMonitorEventReportService {
* 暂态事件报告 * 暂态事件报告
* @param index * @param index
*/ */
void createEventReport(List<String> index, HttpServletResponse response) throws IOException, InvalidFormatException; void createEventReport(List<String> index, HttpServletResponse response) throws IOException, InvalidFormatException, ExecutionException, InterruptedException;
/** /**
* 暂态事件报告存储,返回文件路径 * 暂态事件报告存储,返回文件路径
* @param index * @param index
* @return * @return
*/ */
String saveStableEventReport(List<String> index, Map<String, AreaLineInfoVO> map); String saveStableEventReport(List<String> index, Map<String, AreaLineInfoVO> map, String fileName);
} }

View File

@@ -1,10 +1,10 @@
package com.njcn.event.common.service; package com.njcn.event.common.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.event.pojo.param.*; import com.njcn.event.pojo.param.EventBaseParam;
import com.njcn.event.pojo.param.StatisticsParam;
import com.njcn.event.pojo.vo.*; import com.njcn.event.pojo.vo.*;
import java.text.ParseException;
import java.util.List; import java.util.List;
/** /**
@@ -79,8 +79,6 @@ public interface EventAnalysisService {
*/ */
Page<WaveTypeVO> getMonitorEventAnalyseQuery(EventBaseParam eventBaseParam); Page<WaveTypeVO> getMonitorEventAnalyseQuery(EventBaseParam eventBaseParam);
/** /**
*监测点事件波形下载 *监测点事件波形下载
* @author zbj * @author zbj
@@ -88,6 +86,20 @@ public interface EventAnalysisService {
*/ */
//HttpServletResponse downloadMonitorEventWaveFile(WaveFileParam waveFileParam, HttpServletResponse response) throws Exception; //HttpServletResponse downloadMonitorEventWaveFile(WaveFileParam waveFileParam, HttpServletResponse response) throws Exception;
/**
* 判定压降落点区域
* <p>
* 入参:
* eventValue 特征幅值(百分比形式,如 "80.5" 表示 80.5%),内部 /100 得到 VVm0~1
* persistTime 持续时间(秒)
* <p>
* 优先规则:
* 1) 持续时间 < 0.001 秒 或 VVm = 0 → A区
* 2) 按区间表逐行匹配(左闭右开 [下限, 上限)
* 3) 都不匹配返回 null由调用方走兜底
*
* @return 区域名A区/B区/C区/D区解析失败或未匹配返回 null
*/
String determineDropZone(String eventValue, String persistTime);
} }

View File

@@ -48,6 +48,7 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -60,6 +61,7 @@ import java.net.URLEncoder;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -86,7 +88,8 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
private final FileStorageUtil fileStorageUtil; private final FileStorageUtil fileStorageUtil;
private final LineFeignClient lineFeignClient; private final LineFeignClient lineFeignClient;
private final EventCauseFeignClient eventCauseFeignClient; private final EventCauseFeignClient eventCauseFeignClient;
@Resource(name="asyncExecutor")
private Executor executor;
/** /**
* 监测点导出word * 监测点导出word
@@ -187,7 +190,7 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
createTitle(doc, "4. 总汇信息", "标题 1", 0, 15); createTitle(doc, "4. 总汇信息", "标题 1", 0, 15);
//查询参数 //查询参数
StatisticsParam param = new StatisticsParam(exportParam.getLineId(), exportParam.getSearchBeginTime(), exportParam.getSearchEndTime(), exportParam.getFlag()); StatisticsParam param = new StatisticsParam(exportParam.getLineId(), exportParam.getSearchBeginTime(), exportParam.getSearchEndTime(), exportParam.getFlag(), lineDetailData.getIsDip());
//获取暂降原因字典 //获取暂降原因字典
List<DictData> reasonData = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName()).getData(); List<DictData> reasonData = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName()).getData();
//获取暂降类型字典 //获取暂降类型字典
@@ -476,10 +479,8 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
} catch (Exception e) { } catch (Exception e) {
throw new BusinessException(CommonResponseEnum.FAIL, "导出监测点暂降报告异常"); throw new BusinessException(CommonResponseEnum.FAIL, "导出监测点暂降报告异常");
} }
} }
/** /**
* 创建标题 * 创建标题
* *
@@ -582,19 +583,19 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
* @return * @return
*/ */
private List<EventDetail> info(StatisticsParam statisticsParam) { private List<EventDetail> info(StatisticsParam statisticsParam) {
// //获取事件类型 // 构建查询条件
// List<DictData> dictType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData(); LambdaQueryWrapper<RmpEventDetailPO> queryWrapper = new LambdaQueryWrapper<RmpEventDetailPO>()
// List<String> typeIds = dictType.stream().filter(x -> DicDataEnum.VOLTAGE_DIP.getCode().equals(x.getCode()) || DicDataEnum.SHORT_INTERRUPTIONS.getCode().equals(x.getCode()))
// .map(DictData::getId).collect(Collectors.toList());
//数据暂降查询
List<RmpEventDetailPO> info = rmpEventDetailMapper.selectList(new LambdaQueryWrapper<RmpEventDetailPO>()
.eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex()) .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
// .in(RmpEventDetailPO::getEventType, typeIds)
.ge(StrUtil.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime()))) .ge(StrUtil.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
.le(StrUtil.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime()))) .le(StrUtil.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
.orderByDesc(RmpEventDetailPO::getStartTime) .orderByDesc(RmpEventDetailPO::getStartTime);
); if (!Objects.isNull(statisticsParam.getIsDip()) && statisticsParam.getIsDip()) {
List<DictData> data = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();
List<String> typeList = data.stream().filter(it->it.getCode().equals(DicDataEnum.VOLTAGE_DIP.getCode()) || it.getCode().equals(DicDataEnum.SHORT_INTERRUPTIONS.getCode())).map(DictData::getId).collect(Collectors.toList()); List<TimeVO> list = new ArrayList<>();
queryWrapper.in(RmpEventDetailPO::getEventType, typeList);
}
// 数据暂降查询
List<RmpEventDetailPO> info = rmpEventDetailMapper.selectList(queryWrapper);
return BeanUtil.copyToList(info, EventDetail.class); return BeanUtil.copyToList(info, EventDetail.class);
} }
@@ -602,8 +603,10 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
/** /**
* 生成暂降事件报告 * 生成暂降事件报告
*/ */
public void createEventReport(List<String> eventIndex, HttpServletResponse response) throws IOException, InvalidFormatException { @Override
public void createEventReport(List<String> eventIndex, HttpServletResponse response) throws IOException, InvalidFormatException, ExecutionException, InterruptedException {
WordUtil wordUtil = new WordUtil(); WordUtil wordUtil = new WordUtil();
// 创建专用的线程池建议大小为CPU核心数或稍大这里设为3个并行任务
for (String index : eventIndex) { for (String index : eventIndex) {
RmpEventDetailPO detail = rmpEventDetailMapper.selectById(index); RmpEventDetailPO detail = rmpEventDetailMapper.selectById(index);
List<AreaLineInfoVO> lineDetail = lineFeignClient.getBaseLineAreaInfo(Stream.of(detail.getLineId()).collect(Collectors.toList())).getData(); List<AreaLineInfoVO> lineDetail = lineFeignClient.getBaseLineAreaInfo(Stream.of(detail.getLineId()).collect(Collectors.toList())).getData();
@@ -614,18 +617,40 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
if (ObjUtil.isNull(waveData)) { if (ObjUtil.isNull(waveData)) {
throw new BusinessException(CommonResponseEnum.FAIL, "没有波形数据"); throw new BusinessException(CommonResponseEnum.FAIL, "没有波形数据");
} else { } else {
//获取瞬时波形 // 使用 CompletableFuture 并行执行三个耗时操作
CompletableFuture<String> instantFuture = CompletableFuture.supplyAsync(() -> {
String instantPath = wavePicComponent.generateImageShun(waveData, waveDataDetails); String instantPath = wavePicComponent.generateImageShun(waveData, waveDataDetails);
InputStream instantStream = fileStorageUtil.getFileStream(instantPath); try (InputStream instantStream = fileStorageUtil.getFileStream(instantPath)) {
String imageShun64 = cn.hutool.core.codec.Base64.encode(instantStream); return cn.hutool.core.codec.Base64.encode(instantStream);
} catch (Exception e) {
throw new RuntimeException("生成瞬时波形失败", e);
}
}, executor);
wordUtil.translateShun(index, imageShun64); CompletableFuture<String> rmsFuture = CompletableFuture.supplyAsync(() -> {
//获取rms波形
String rmsPath = wavePicComponent.generateImageRms(waveData, waveDataDetails); String rmsPath = wavePicComponent.generateImageRms(waveData, waveDataDetails);
InputStream rmsStream = fileStorageUtil.getFileStream(rmsPath); try (InputStream rmsStream = fileStorageUtil.getFileStream(rmsPath)) {
String rmsShun64 = cn.hutool.core.codec.Base64.encode(rmsStream); return cn.hutool.core.codec.Base64.encode(rmsStream);
wordUtil.translateRms(index, rmsShun64); } catch (Exception e) {
throw new RuntimeException("生成RMS波形失败", e);
}
}, executor);
// 等待所有异步任务完成并获取结果(无超时,但可加)
CompletableFuture<Void> allFutures = CompletableFuture.allOf(instantFuture, rmsFuture);
allFutures.join(); // 阻塞直到2个任务都完成
// 获取结果此时所有任务已完成get()不会阻塞)
String imageShun64 = instantFuture.get();
String rmsShun64 = rmsFuture.get();
List<EventEigDetail> eventDetailEigenvalue = waveService.eventDetailEigenvalue(index, line.getPtType());
// 主线程顺序调用 WordUtil 方法(保证线程安全)
wordUtil.translateShun(index, imageShun64);
wordUtil.translateRms(index, rmsShun64);
wordUtil.setEventDetailEigenvalue(index, eventDetailEigenvalue);
// 设置事件基本信息(不涉及耗时操作)
EventInfoDetailVO eventInfoList = new EventInfoDetailVO(); EventInfoDetailVO eventInfoList = new EventInfoDetailVO();
eventInfoList.setLineName(line.getLineName()); eventInfoList.setLineName(line.getLineName());
eventInfoList.setGdName(line.getGdName()); eventInfoList.setGdName(line.getGdName());
@@ -639,9 +664,6 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
eventInfoList.setMs(detail.getFirstMs()); eventInfoList.setMs(detail.getFirstMs());
eventInfoList.setEventValue(detail.getFeatureAmplitude()); eventInfoList.setEventValue(detail.getFeatureAmplitude());
wordUtil.setEventInfoList(index, eventInfoList); wordUtil.setEventInfoList(index, eventInfoList);
List<EventEigDetail> eventDetailEigenvalue = waveService.eventDetailEigenvalue(index,line.getPtType());
wordUtil.setEventDetailEigenvalue(index, eventDetailEigenvalue);
} }
} }
wordUtil.createReport(eventIndex); wordUtil.createReport(eventIndex);
@@ -658,7 +680,7 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
} }
@Override @Override
public String saveStableEventReport(List<String> eventIndex, Map<String, AreaLineInfoVO> map) { public String saveStableEventReport(List<String> eventIndex, Map<String, AreaLineInfoVO> map, String fileName) {
WordUtil wordUtil = new WordUtil(); WordUtil wordUtil = new WordUtil();
for (String index : eventIndex) { for (String index : eventIndex) {
RmpEventDetailPO detail = rmpEventDetailMapper.selectById(index); RmpEventDetailPO detail = rmpEventDetailMapper.selectById(index);
@@ -709,7 +731,12 @@ public class CommMonitorEventReportServiceImpl implements CommMonitorEventReport
} }
try { try {
InputStream inputStream = wordUtil.createReport2(eventIndex); InputStream inputStream = wordUtil.createReport2(eventIndex);
String filePath = fileStorageUtil.uploadStream(inputStream, OssPath.APP_EVENT_REPORT, "暂降事件报告.docx"); String filePath;
if (Objects.isNull(fileName)) {
filePath = fileStorageUtil.uploadStream(inputStream, OssPath.APP_EVENT_REPORT, null);
} else {
filePath = fileStorageUtil.uploadStreamSpecifyName(inputStream, OssPath.APP_EVENT_REPORT, fileName);
}
return filePath; return filePath;
} catch (IOException | InvalidFormatException e) { } catch (IOException | InvalidFormatException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@@ -4,7 +4,6 @@ import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil; 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.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.config.GeneralInfo; import com.njcn.common.config.GeneralInfo;
@@ -13,6 +12,7 @@ import com.njcn.common.pojo.response.HttpResult;
import com.njcn.device.pq.api.LineFeignClient; import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO; import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.device.pq.pojo.vo.LineDetailDataVO; import com.njcn.device.pq.pojo.vo.LineDetailDataVO;
import com.njcn.event.common.service.EventAnalysisService;
import com.njcn.event.common.service.EventDetailService; import com.njcn.event.common.service.EventDetailService;
import com.njcn.event.enums.EventResponseEnum; import com.njcn.event.enums.EventResponseEnum;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum; import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
@@ -21,19 +21,20 @@ import com.njcn.event.pojo.param.StatisticsParam;
import com.njcn.event.pojo.po.EventDetail; import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.pojo.po.RmpEventDetailPO; import com.njcn.event.pojo.po.RmpEventDetailPO;
import com.njcn.event.pojo.vo.*; import com.njcn.event.pojo.vo.*;
import com.njcn.event.common.service.EventAnalysisService;
import com.njcn.influx.utils.InfluxDbUtils; import com.njcn.influx.utils.InfluxDbUtils;
import com.njcn.system.api.DicDataFeignClient; import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum; import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum; import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData; import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.influxdb.dto.QueryResult; import org.influxdb.dto.QueryResult;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.*; import java.io.*;
import java.text.ParseException; import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
@@ -51,6 +52,7 @@ import java.util.zip.ZipOutputStream;
*/ */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j
public class EventAnalysisServiceImpl implements EventAnalysisService { public class EventAnalysisServiceImpl implements EventAnalysisService {
// 定义阈值常量(单位:百分比) // 定义阈值常量(单位:百分比)
@@ -1727,6 +1729,75 @@ public class EventAnalysisServiceImpl implements EventAnalysisService {
} }
@Override
public String determineDropZone(String eventValue, String persistTime) {
if (eventValue == null || eventValue.trim().isEmpty()
|| persistTime == null || persistTime.trim().isEmpty()) {
log.warn("判定压降落点区域入参为空eventValue={}, persistTime={}", eventValue, persistTime);
return null;
}
BigDecimal vvm;
BigDecimal vvtm;
try {
// params[3] 是百分比(如 "80.5"/100 得到 0~1 的 VVm
vvm = new BigDecimal(eventValue.trim()).divide(new BigDecimal("100"), 6, RoundingMode.HALF_UP);
vvtm = new BigDecimal(persistTime.trim());
} catch (Exception e) {
log.error("判定压降落点区域入参解析失败eventValue={}, persistTime={}", eventValue, persistTime, e);
return null;
}
// 1) 超短脉冲 或 完全失压 默认 A 区
if (vvtm.compareTo(new BigDecimal("0.001")) < 0
|| vvm.compareTo(BigDecimal.ZERO) == 0) {
return "A区";
}
// 2) 区间表(左闭右开)
// A区
if (inRange(vvm, "0.9", "1") && inRange(vvtm, "0.001", "60")) {
return "A区";
}
if (inRange(vvm, "0", "0.9") && inRange(vvtm, "0.001", "0.05")) {
return "A区";
}
// B区
if (inRange(vvm, "0.5", "0.7") && inRange(vvtm, "0.05", "0.2")) {
return "B区";
}
if (inRange(vvm, "0.7", "0.8") && inRange(vvtm, "0.05", "0.5")) {
return "B区";
}
if (inRange(vvm, "0.8", "0.9") && inRange(vvtm, "0.05", "60")) {
return "B区";
}
// C区
if (inRange(vvm, "0", "0.5") && inRange(vvtm, "0.05", "1")) {
return "C区";
}
if (inRange(vvm, "0.5", "0.7") && inRange(vvtm, "0.2", "1")) {
return "C区";
}
if (inRange(vvm, "0.7", "0.8") && inRange(vvtm, "0.5", "1")) {
return "C区";
}
// D区
if (inRange(vvm, "0", "0.8") && inRange(vvtm, "1", "60")) {
return "D区";
}
log.warn("压降落点区域未匹配任何规则eventValue={}, persistTime={}", eventValue, persistTime);
return null;
}
/**
* 左闭右开区间判断lowerInclusive ≤ value < upperExclusive
*/
private boolean inRange(BigDecimal value, String lowerInclusive, String upperExclusive) {
return value.compareTo(new BigDecimal(lowerInclusive)) >= 0
&& value.compareTo(new BigDecimal(upperExclusive)) < 0;
}
/** /**
* 监测点事件波形下载 * 监测点事件波形下载

View File

@@ -7,7 +7,7 @@ import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.tocrhz.mqtt.publisher.MqttPublisher; //import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.advance.api.EventCauseFeignClient; import com.njcn.advance.api.EventCauseFeignClient;
import com.njcn.advance.pojo.dto.EventAnalysisDTO; import com.njcn.advance.pojo.dto.EventAnalysisDTO;
import com.njcn.common.utils.PubUtils; import com.njcn.common.utils.PubUtils;
@@ -18,6 +18,7 @@ import com.njcn.device.pq.pojo.po.DeptLine;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO; import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.device.pq.pojo.vo.LineDetailDataVO; import com.njcn.device.pq.pojo.vo.LineDetailDataVO;
import com.njcn.event.common.mapper.RmpEventDetailMapper; import com.njcn.event.common.mapper.RmpEventDetailMapper;
import com.njcn.event.common.websocket.WebSocketServer;
import com.njcn.event.pojo.vo.SendEventVO; import com.njcn.event.pojo.vo.SendEventVO;
import com.njcn.event.utils.EventUtil; import com.njcn.event.utils.EventUtil;
import com.njcn.event.pojo.dto.EventDeatilDTO; import com.njcn.event.pojo.dto.EventDeatilDTO;
@@ -29,21 +30,28 @@ import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum; import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData; import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient; import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.Dept; import com.njcn.user.pojo.po.Dept;
import com.njcn.user.pojo.po.User;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.QueryResult; import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper; import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.time.Duration; import java.time.Duration;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
/** /**
* @author denghuajun * @author denghuajun
@@ -57,12 +65,16 @@ public class EventDetailServiceImpl extends ServiceImpl<RmpEventDetailMapper, Rm
private final InfluxDbUtils influxDbUtils; private final InfluxDbUtils influxDbUtils;
private final DicDataFeignClient dicDataFeignClient; private final DicDataFeignClient dicDataFeignClient;
private final MqttPublisher publisher; // private final MqttPublisher publisher;
private final WebSocketServer webSocketServer;
private final CommTerminalGeneralClient commTerminalGeneralClient; private final CommTerminalGeneralClient commTerminalGeneralClient;
private final LineFeignClient lineFeignClient; private final LineFeignClient lineFeignClient;
private final DeptLineFeignClient deptLineFeignClient; private final DeptLineFeignClient deptLineFeignClient;
private final DeptFeignClient deptFeignClient; private final DeptFeignClient deptFeignClient;
private final UserFeignClient userFeignClient;
@Resource(name="asyncExecutor")
private Executor executor;
private final EventCauseFeignClient eventCauseFeignClient; private final EventCauseFeignClient eventCauseFeignClient;
@Override @Override
public List<EventDetail> getEventDetailData(String id, String startTime, String endTime) { public List<EventDetail> getEventDetailData(String id, String startTime, String endTime) {
@@ -146,9 +158,15 @@ public class EventDetailServiceImpl extends ServiceImpl<RmpEventDetailMapper, Rm
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) // @Transactional(rollbackFor = Exception.class)
public Boolean addEventDetail(EventDeatilDTO deatilDTO) { public Boolean addEventDetail(EventDeatilDTO deatilDTO) {
RmpEventDetailPO one = this.lambdaQuery().eq(RmpEventDetailPO::getLineId, deatilDTO.getMonitorId()).eq(RmpEventDetailPO::getStartTime, deatilDTO.getStartTime()).one();
RmpEventDetailPO rmpEventDetailPO = new RmpEventDetailPO(); RmpEventDetailPO rmpEventDetailPO = new RmpEventDetailPO();
if(Objects.nonNull(one)){
BeanUtils.copyProperties(one,rmpEventDetailPO);
}
// rmpEventDetailPO.setMeasurementPointId(deatilDTO.getMonitorId()); // rmpEventDetailPO.setMeasurementPointId(deatilDTO.getMonitorId());
rmpEventDetailPO.setLineId(deatilDTO.getMonitorId()); rmpEventDetailPO.setLineId(deatilDTO.getMonitorId());
DictData data = dicDataFeignClient.getDicDataByCode(eventTypeReflection(deatilDTO.getEventType())).getData(); DictData data = dicDataFeignClient.getDicDataByCode(eventTypeReflection(deatilDTO.getEventType())).getData();
@@ -163,56 +181,17 @@ public class EventDetailServiceImpl extends ServiceImpl<RmpEventDetailMapper, Rm
}else { }else {
rmpEventDetailPO.setFileFlag(1); rmpEventDetailPO.setFileFlag(1);
} }
//默认给0经过高级算法在赋值
rmpEventDetailPO.setDealFlag(0);
rmpEventDetailPO.setEventDescribe(" "); rmpEventDetailPO.setEventDescribe(" ");
//如果不为空,说明是二次上传波形文件了; //如果不为空,说明是二次上传波形文件了;
String reason,type;
if(!StringUtils.isEmpty(rmpEventDetailPO.getWavePath())){
LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(rmpEventDetailPO.getLineId()).getData();
String ip = lineDetailData.getIp();
EventAnalysisDTO eventAnalysisDTO = new EventAnalysisDTO();
eventAnalysisDTO.setIp(ip);
eventAnalysisDTO.setWaveName(rmpEventDetailPO.getWavePath());
EventAnalysisDTO result = eventCauseFeignClient.analysisCauseAndType(eventAnalysisDTO).getData();
if(Objects.isNull(result.getCause())){
reason =reasonReflection(0);
}else {
reason =reasonReflection(result.getCause());
}
if(Objects.isNull(result.getType())){
type =advanceTypeReflection(10);
}else {
type =advanceTypeReflection(result.getType());
}
DictData advancereason = dicDataFeignClient.getDicDataByCode(reason).getData();
DictData advanceType = dicDataFeignClient.getDicDataByCode(type).getData();
if(Objects.equals(result.getCauseFlag(),1)&&Objects.equals(result.getTypeFlag(),1)){
rmpEventDetailPO.setDealFlag(1);
}else {
rmpEventDetailPO.setDealFlag(0);
}
rmpEventDetailPO.setAdvanceReason(advancereason.getId());
rmpEventDetailPO.setAdvanceType(advanceType.getId());
}
//默认都是其他
// DictData reason = dicDataFeignClient.getDicDataByCode(DicDataEnum.RESON_REST.getCode()).getData();
// DictData advanceType = dicDataFeignClient.getDicDataByCode(DicDataEnum.TYPE_REST.getCode()).getData();
//
// rmpEventDetailPO.setAdvanceReason(reason.getId());
// rmpEventDetailPO.setAdvanceType(advanceType.getId());
String severity = EventUtil.getYzd(deatilDTO.getDuration().floatValue(),(deatilDTO.getAmplitude().floatValue()/100)); String severity = EventUtil.getYzd(deatilDTO.getDuration().floatValue(),(deatilDTO.getAmplitude().floatValue()/100));
rmpEventDetailPO.setSeverity(Double.valueOf(severity)); rmpEventDetailPO.setSeverity(Double.valueOf(severity));
rmpEventDetailPO.setCreateTime(LocalDateTime.now()); rmpEventDetailPO.setCreateTime(LocalDateTime.now());
RmpEventDetailPO one = this.lambdaQuery().eq(RmpEventDetailPO::getLineId, rmpEventDetailPO.getLineId()).eq(RmpEventDetailPO::getStartTime, rmpEventDetailPO.getStartTime()).one();
if(Objects.nonNull(one)){ if(Objects.nonNull(one)){
rmpEventDetailPO.setEventId(one.getEventId()); rmpEventDetailPO.setEventId(one.getEventId());
@@ -226,10 +205,73 @@ public class EventDetailServiceImpl extends ServiceImpl<RmpEventDetailMapper, Rm
pushEvent(rmpEventDetailPO); pushEvent(rmpEventDetailPO);
} }
} }
//异步调用高级算法
if (!StringUtils.isEmpty(rmpEventDetailPO.getWavePath())) {
CompletableFuture.runAsync(() -> {
// 异步任务内执行分析及更新
analyzeAndUpdateEvent(rmpEventDetailPO.getEventId(), rmpEventDetailPO.getLineId(), rmpEventDetailPO.getWavePath());
}, executor).exceptionally(ex -> {
// exceptionally 也可以捕获异常,但内部已 try-catch这里仅做兜底日志
log.error("异步任务未预期的异常, eventId: {}", rmpEventDetailPO.getEventId(), ex);
return null;
});
}
return true; return true;
} }
private void analyzeAndUpdateEvent(String eventId, String lineId, String wavePath) {
// 重新查询实体,避免跨线程持久化对象问题
RmpEventDetailPO po = this.getById(eventId);
if (po == null) {
log.warn("异步分析时事件记录不存在, eventId: {}", eventId);
return;
}
try {
// Feign 调用链
LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(lineId).getData();
String ip = lineDetailData.getIp();
EventAnalysisDTO eventAnalysisDTO = new EventAnalysisDTO();
eventAnalysisDTO.setIp(ip);
eventAnalysisDTO.setWaveName(wavePath);
EventAnalysisDTO result = eventCauseFeignClient.analysisCauseAndType(eventAnalysisDTO).getData();
// 转换结果
String reasonCode, typeCode;
if (Objects.isNull(result.getCause())) {
reasonCode = reasonReflection(0);
} else {
reasonCode = reasonReflection(result.getCause());
}
if (Objects.isNull(result.getType())) {
typeCode = advanceTypeReflection(10);
} else {
typeCode = advanceTypeReflection(result.getType());
}
DictData advancereason = dicDataFeignClient.getDicDataByCode(reasonCode).getData();
DictData advanceType = dicDataFeignClient.getDicDataByCode(typeCode).getData();
po.setAdvanceReason(advancereason.getId());
po.setAdvanceType(advanceType.getId());
if (Objects.equals(result.getCauseFlag(), 1) && Objects.equals(result.getTypeFlag(), 1)) {
po.setDealFlag(1);
} else {
po.setDealFlag(0);
}
// 更新数据库
this.updateById(po);
} catch (Exception e) {
// 关键点:所有异常被捕获并记录日志,不会抛出到主线程
log.error("异步分析失败, eventId={}, wavePath={}", eventId, wavePath, e);
// 可选:设置一个错误标志,避免一直处于未分析状态
po.setDealFlag(0);
this.updateById(po);
}
}
private String advanceTypeReflection(Integer type) { private String advanceTypeReflection(Integer type) {
String result = DicDataEnum.TYPE_REST.getCode(); String result = DicDataEnum.TYPE_REST.getCode();
switch (type) { switch (type) {
@@ -306,6 +348,9 @@ public class EventDetailServiceImpl extends ServiceImpl<RmpEventDetailMapper, Rm
String[] idsArray = deptInfo.getPids().split(","); String[] idsArray = deptInfo.getPids().split(",");
dept.addAll(Arrays.asList(idsArray)); dept.addAll(Arrays.asList(idsArray));
}); });
List<String> deptList = dept.stream().collect(Collectors.toList());
List<User> data = userFeignClient.getUserInfoByDeptIds(deptList).getData();
SendEventVO vo = new SendEventVO(); SendEventVO vo = new SendEventVO();
vo.setDeptList(dept); vo.setDeptList(dept);
vo.setTime(po.getStartTime()); vo.setTime(po.getStartTime());
@@ -317,7 +362,10 @@ public class EventDetailServiceImpl extends ServiceImpl<RmpEventDetailMapper, Rm
vo.setLineName(lineInfoVOList.get(0).getLineName()); vo.setLineName(lineInfoVOList.get(0).getLineName());
vo.setPowerCompany(lineInfoVOList.get(0).getGdName()); vo.setPowerCompany(lineInfoVOList.get(0).getGdName());
vo.setSubstation(lineInfoVOList.get(0).getSubName()); vo.setSubstation(lineInfoVOList.get(0).getSubName());
publisher.send("/sendEvent", PubUtils.obj2json(vo), 1, false); for (User datum : data) {
webSocketServer.sendMessageToUser(datum.getId(),PubUtils.obj2json(vo));
}
// publisher.send("/sendEvent", PubUtils.obj2json(vo), 1, false);
} }
} }
@@ -340,5 +388,15 @@ public class EventDetailServiceImpl extends ServiceImpl<RmpEventDetailMapper, Rm
return result; return result;
} }
public static void main(String[] args) {
try{
System.out.println(1/0);
}catch (Exception e){
System.out.println(1);
}
System.out.println(1111);
}
} }

View File

@@ -849,7 +849,7 @@ public class EventReportServiceImpl implements EventReportService {
} else { } else {
builder2.append(startYear).append("-").append(startMonth + 1).append("-").append(startDays); builder2.append(startYear).append("-").append(startMonth + 1).append("-").append(startDays);
} }
query = MonitorQuery(new StatisticsParam(statisticsParam.getLineIndex(), builder1.toString(), builder2.toString(), statisticsParam.getFlag())); query = MonitorQuery(new StatisticsParam(statisticsParam.getLineIndex(), builder1.toString(), builder2.toString(), statisticsParam.getFlag(),null));
InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper(); InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
List<EventDetail> eventDetailList = influxDBResultMapper.toPOJO(query, EventDetail.class); List<EventDetail> eventDetailList = influxDBResultMapper.toPOJO(query, EventDetail.class);
long count = eventDetailList.stream().filter(x -> x.getEventType() == "1").count(); long count = eventDetailList.stream().filter(x -> x.getEventType() == "1").count();
@@ -868,7 +868,7 @@ public class EventReportServiceImpl implements EventReportService {
builder2.delete(0, builder2.length()); builder2.delete(0, builder2.length());
builder1.append(startYear).append("-").append(startMonth).append("-").append(startDays); builder1.append(startYear).append("-").append(startMonth).append("-").append(startDays);
builder2.append(startYear).append("-").append(startMonth).append("-").append(endDays); builder2.append(startYear).append("-").append(startMonth).append("-").append(endDays);
query = MonitorQuery(new StatisticsParam(statisticsParam.getLineIndex(), builder1.toString(), builder2.toString(), statisticsParam.getFlag())); query = MonitorQuery(new StatisticsParam(statisticsParam.getLineIndex(), builder1.toString(), builder2.toString(), statisticsParam.getFlag(),null));
InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper(); InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
List<EventDetail> eventDetailList = influxDBResultMapper.toPOJO(query, EventDetail.class); List<EventDetail> eventDetailList = influxDBResultMapper.toPOJO(query, EventDetail.class);
long count1 = eventDetailList.stream().filter(x -> x.getEventType() == "1").count(); long count1 = eventDetailList.stream().filter(x -> x.getEventType() == "1").count();

View File

@@ -62,7 +62,7 @@ public class WaveServiceImpl implements WaveService {
if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) { if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND); throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
} }
waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1); waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 2);
} catch (Exception e) { } catch (Exception e) {
try { try {
InputStream cfgStreamLower = fileStorageUtil.getFileStream(wavePath + GeneralConstant.CFG_LOWER); InputStream cfgStreamLower = fileStorageUtil.getFileStream(wavePath + GeneralConstant.CFG_LOWER);
@@ -70,7 +70,7 @@ public class WaveServiceImpl implements WaveService {
if (Objects.isNull(cfgStreamLower) || Objects.isNull(datStreamLower)) { if (Objects.isNull(cfgStreamLower) || Objects.isNull(datStreamLower)) {
throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND); throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
} }
waveDataDTO = waveFileComponent.getComtrade(cfgStreamLower, datStreamLower, 1); waveDataDTO = waveFileComponent.getComtrade(cfgStreamLower, datStreamLower, 2);
} catch (Exception e1) { } catch (Exception e1) {
throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID); throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID);
} }

View File

@@ -0,0 +1,41 @@
package com.njcn.event.common.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
/**
* Description:
* Date: 2024/12/13 15:09【需求编号】
*
* @author clam
* @version V1.0.0
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
/**
* 通信文本消息和二进制缓存区大小
* 避免对接 第三方 报文过大时Websocket 1009 错误
*
* @return
*/
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
// 在此处设置bufferSize
container.setMaxTextMessageBufferSize(10240000);
container.setMaxBinaryMessageBufferSize(10240000);
container.setMaxSessionIdleTimeout(15 * 60000L);
return container;
}
}

View File

@@ -0,0 +1,147 @@
package com.njcn.event.common.websocket;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Description:
* Date: 2024/12/13 15:11【需求编号】
*
* @author clam
* @version V1.0.0
*/
@Slf4j
@Component
@ServerEndpoint(value = "/event/{userId}")
public class WebSocketServer {
private static final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, Long> lastHeartbeatTime = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, ScheduledExecutorService> heartbeatExecutors = new ConcurrentHashMap<>();
private static final long HEARTBEAT_TIMEOUT = 60; // 60秒超时
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
if (StrUtil.isNotBlank(userId)) {
sessions.put(userId, session);
lastHeartbeatTime.put(userId, System.currentTimeMillis());
sendMessage(session, "连接成功");
System.out.println("用户 " + userId + " 已连接");
// 启动心跳检测
startHeartbeat(session, userId);
} else {
try {
session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "用户ID不能为空"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnMessage
public void onMessage(String message, Session session, @PathParam("userId") String userId) {
if ("alive".equalsIgnoreCase(message)) {
// 更新最后心跳时间
lastHeartbeatTime.put(userId, System.currentTimeMillis());
sendMessage(session, "over");
} else {
// 处理业务消息
System.out.println("收到用户 " + userId + " 的消息: " + message);
// TODO: 处理业务逻辑
}
}
@OnClose
public void onClose(Session session, CloseReason closeReason, @PathParam("userId") String userId) {
// 移除用户并取消心跳检测
sessions.remove(userId);
lastHeartbeatTime.remove(userId);
ScheduledExecutorService executor = heartbeatExecutors.remove(userId);
if (executor != null) {
executor.shutdownNow();
}
System.out.println("用户 " + userId + " 已断开连接,状态码: " + closeReason.getCloseCode());
}
@OnError
public void onError(Session session, Throwable throwable, @PathParam("userId") String userId) {
System.out.println("用户 " + userId + " 发生错误: " + throwable.getMessage());
try {
session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "发生错误"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessageToUser(String userId, String message) {
Session session = sessions.get(userId);
if (session != null && session.isOpen()) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
System.out.println("发送消息给用户 " + userId + " 失败: " + e.getMessage());
}
} else {
System.out.println("webSocket用户 " + userId + " 不在线或会话已关闭");
}
}
private final Object lock = new Object();
public void sendMessageToAll(String message) {
sessions.forEach((userId, session) -> {
System.out.println("给用户推送消息" + userId);
if (session.isOpen()) {
synchronized (lock) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
System.out.println("发送消息给用户 " + userId + " 失败: " + e.getMessage());
}
}
}
});
}
private void sendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
System.out.println("发送消息失败: " + e.getMessage());
}
}
private void startHeartbeat(Session session, String userId) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
heartbeatExecutors.put(userId, executor);
// 定期检查心跳
executor.scheduleAtFixedRate(() -> {
long lastTime = lastHeartbeatTime.getOrDefault(userId, 0L);
long currentTime = System.currentTimeMillis();
// 如果超过30秒没有收到心跳
if (currentTime - lastTime > HEARTBEAT_TIMEOUT * 1000) {
try {
System.out.println("用户 " + userId + " 心跳超时,关闭连接");
session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "心跳超时"));
} catch (IOException e) {
System.out.println("关闭用户 " + userId + " 连接时出错: " + e.getMessage());
}
executor.shutdown();
heartbeatExecutors.remove(userId);
}
}, 0, 5, TimeUnit.SECONDS); // 每5秒检查一次
}
}

View File

@@ -44,7 +44,7 @@ import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered { public class AuthGlobalFilter implements GlobalFilter, Ordered {
private final static List<String> USER_AGENT_IP = Arrays.asList("/pqs-auth/auth/getImgCode", "/pqs-auth/oauth/token", "/user-boot/user/generateSm2Key", "/user-boot/user/updateFirstPassword", "/user-boot/appUser/resetPsd"); private final static List<String> USER_AGENT_IP = Arrays.asList("/pqs-auth/auth/getImgCode", "/pqs-auth/oauth/token", "/user-boot/user/generateSm2Key", "/user-boot/user/updateFirstPassword", "/user-boot/appUser/resetPsd","/pqs-auth/oauth/lnLogin","/pqs-auth/oauth/lnCheck","/pqs-auth/oauth/lnRefreshToken");
private final RedisUtil redisUtil; private final RedisUtil redisUtil;

View File

@@ -223,6 +223,9 @@ whitelist:
- /user-boot/appUser/resetPsd - /user-boot/appUser/resetPsd
- /pqs-auth/oauth/logout - /pqs-auth/oauth/logout
- /pqs-auth/oauth/token - /pqs-auth/oauth/token
- /pqs-auth/oauth/lnLogin
- /pqs-auth/oauth/lnCheck
- /pqs-auth/oauth/lnRefreshToken
- /pqs-auth/oauth/autoLogin - /pqs-auth/oauth/autoLogin
- /pqs-auth/auth/getImgCode - /pqs-auth/auth/getImgCode
- /pqs-auth/oauth/getPublicKey - /pqs-auth/oauth/getPublicKey

View File

@@ -36,6 +36,9 @@ public class ReportSearchParam {
//目前用于区分不同系统资源null默认 1.无线系统配合cs-device //目前用于区分不同系统资源null默认 1.无线系统配合cs-device
private Integer resourceType; private Integer resourceType;
//区分统计数据还是分钟数据null默认统计数据 0.统计数据 1.分钟数据
private Integer isStatisticData;
//浙江无线报表特殊标识 null为通用报表 1.浙江无线报表 //浙江无线报表特殊标识 null为通用报表 1.浙江无线报表
private Integer customType; private Integer customType;

View File

@@ -3,6 +3,8 @@ package com.njcn.harmonic.pojo.param.report;
import com.njcn.harmonic.pojo.dto.report.CommReportLedgerDto; import com.njcn.harmonic.pojo.dto.report.CommReportLedgerDto;
import lombok.Data; import lombok.Data;
import java.util.List;
/** /**
* @Author: cdf * @Author: cdf
* @CreateTime: 2026-01-06 * @CreateTime: 2026-01-06
@@ -17,4 +19,6 @@ public class AreaHarmReportParam {
private String deptId; private String deptId;
private List<String> voltageIds;
} }

View File

@@ -191,6 +191,11 @@ public class OverAreaLimitVO {
private Double negativeOverDayBiLi = -1.0; private Double negativeOverDayBiLi = -1.0;
//间谐波电压超标情况 //间谐波电压超标情况
/**
* 超标监测点集合,区域报告使用
*/
private List<String> inHarmonicVMonitorList = new ArrayList<>();;
/** /**
* 个数 * 个数
*/ */

View File

@@ -58,6 +58,16 @@ public class GridDiagramHarmController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, subLineGiveAnAlarm, methodDescribe); return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, subLineGiveAnAlarm, methodDescribe);
} }
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getAreaObjAlarm")
@ApiOperation("区域场站监测点规模")
@ApiImplicitParam(name = "param", value = "区域场站监测点规模参数", required = true)
public HttpResult<GridDiagramVO> getAreaObjAlarm(@RequestBody StatSubstationBizBaseParam param) {
String methodDescribe = getMethodDescribe("getAreaObjAlarm");
GridDiagramVO subLineGiveAnAlarm = irMpTargetWarnDService.getAreaObjAlarm(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, subLineGiveAnAlarm, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON) @OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getPollutionAlarmData") @PostMapping("/getPollutionAlarmData")
@ApiOperation("变电站污染告警占比") @ApiOperation("变电站污染告警占比")

View File

@@ -64,7 +64,7 @@ public class PowerStatisticsController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON) @OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getTargetByTime") @PostMapping("/getTargetByTime")
@ApiOperation("点击越限列表时间查询指标的详细数据") @ApiOperation("点击越限列表时间查询指标的详细数据")
public HttpResult<List<ThdDataVO>> getTargetByTime(@RequestBody @Validated PowerStatisticsParam powerStatisticsParam) { public HttpResult<List<ThdDataVO>> getTargetByTime(@RequestBody PowerStatisticsParam powerStatisticsParam) {
String methodDescribe = getMethodDescribe("getTargetByTime"); String methodDescribe = getMethodDescribe("getTargetByTime");
List<ThdDataVO> targetByTime = powerStatisticsService.getTargetByTimeDetail(powerStatisticsParam); List<ThdDataVO> targetByTime = powerStatisticsService.getTargetByTimeDetail(powerStatisticsParam);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, targetByTime, methodDescribe); return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, targetByTime, methodDescribe);
@@ -73,14 +73,14 @@ public class PowerStatisticsController extends BaseController {
@ResponseBody @ResponseBody
@ApiOperation("导出区间数据") @ApiOperation("导出区间数据")
@PostMapping(value = "exportExcelRangTemplate") @PostMapping(value = "exportExcelRangTemplate")
public void exportExcelRangTemplate(@RequestBody @Validated PowerStatisticsParam powerStatisticsParam,HttpServletResponse response) { public void exportExcelRangTemplate(@RequestBody PowerStatisticsParam powerStatisticsParam,HttpServletResponse response) {
powerStatisticsService.exportExcelRangTemplate(powerStatisticsParam,response); powerStatisticsService.exportExcelRangTemplate(powerStatisticsParam,response);
} }
@ResponseBody @ResponseBody
@ApiOperation("导出指标越限列表数据") @ApiOperation("导出指标越限列表数据")
@PostMapping(value = "exportExcelListTemplate") @PostMapping(value = "exportExcelListTemplate")
public void exportExcelListTemplate(@RequestBody @Validated PowerStatisticsParam powerStatisticsParam,HttpServletResponse response) { public void exportExcelListTemplate(@RequestBody PowerStatisticsParam powerStatisticsParam,HttpServletResponse response) {
powerStatisticsService.exportExcelListTemplate(powerStatisticsParam,response); powerStatisticsService.exportExcelListTemplate(powerStatisticsParam,response);
} }

View File

@@ -20,4 +20,6 @@ public interface IRMpTargetWarnDService extends IService<RMpTargetWarnDPO> {
GridDiagramVO getSubLineGiveAnAlarm(StatSubstationBizBaseParam param); GridDiagramVO getSubLineGiveAnAlarm(StatSubstationBizBaseParam param);
GridDiagramVO getAreaObjAlarm(StatSubstationBizBaseParam param);
} }

View File

@@ -11,6 +11,8 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.njcn.common.config.GeneralInfo; import com.njcn.common.config.GeneralInfo;
import com.njcn.device.biz.commApi.CommLineClient;
import com.njcn.device.biz.pojo.dto.LineALLInfoDTO;
import com.njcn.device.pq.api.GeneralDeviceInfoClient; import com.njcn.device.pq.api.GeneralDeviceInfoClient;
import com.njcn.device.pq.api.LineFeignClient; import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.api.UserLedgerFeignClient; import com.njcn.device.pq.api.UserLedgerFeignClient;
@@ -48,6 +50,7 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.File; import java.io.File;
import java.math.BigDecimal; import java.math.BigDecimal;
@@ -83,7 +86,7 @@ public class AnalyzeServiceImpl implements IAnalyzeService {
private final EventDetailFeignClient eventDetailFeignClient; private final EventDetailFeignClient eventDetailFeignClient;
private final DicDataFeignClient dicDataFeignClient; private final DicDataFeignClient dicDataFeignClient;
private final UserLedgerFeignClient userLedgerFeignClient; private final UserLedgerFeignClient userLedgerFeignClient;
private final CommLineClient commLineClient;
@Override @Override
public Page<OverAreaLimitVO> getAreaData(OverAreaVO param) { public Page<OverAreaLimitVO> getAreaData(OverAreaVO param) {
Page<OverAreaLimitVO> page = new Page<>(); Page<OverAreaLimitVO> page = new Page<>();
@@ -301,8 +304,31 @@ public class AnalyzeServiceImpl implements IAnalyzeService {
lineList.addAll(item.getLineIndexes()); lineList.addAll(item.getLineIndexes());
}); });
} }
List<String> filterLineList = new ArrayList<>();
if(CollectionUtil.isNotEmpty(lineList)){ if(CollectionUtil.isNotEmpty(lineList)){
page = targetMapper.getSumLimitTargetPage(page, lineList, DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())), //根据searchvalue过滤
String searchvalue=param.getSearchValue();
List<LineALLInfoDTO> data = commLineClient.getLineAllDetailList(lineList).getData();
filterLineList= data.stream()
.filter(dto -> {
LineALLInfoDTO.LineLineDTO lineDTO = dto.getLineLineDTO();
String linename = lineDTO != null ? lineDTO.getLinename() : null;
String objName2 = lineDTO != null ? lineDTO.getObjName2() : null;
LineALLInfoDTO.LineSubStationDTO subStationDTO = dto.getLineSubStationDTO();
String subStationName = subStationDTO != null ? subStationDTO.getSubStationName() : null;
// 大小写敏感的模糊匹配(相当于 MySQL 的 LIKE '%keyword%'
return (linename != null && linename.contains(searchvalue))
|| (objName2 != null && objName2.contains(searchvalue))
|| (subStationName != null && subStationName.contains(searchvalue));
}).map(dto -> dto.getLineLineDTO() != null ? dto.getLineLineDTO().getLineId() : null)
.collect(Collectors.toList());
}
if (CollectionUtil.isNotEmpty(filterLineList)) {
page = targetMapper.getSumLimitTargetPage(page, filterLineList, DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())),
DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()))); DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())));
List<MonitorOverLimitVO> pageRecords = page.getRecords(); List<MonitorOverLimitVO> pageRecords = page.getRecords();
if (CollectionUtils.isEmpty(pageRecords)) { if (CollectionUtils.isEmpty(pageRecords)) {
@@ -509,6 +535,7 @@ public class AnalyzeServiceImpl implements IAnalyzeService {
Set<String> flickerMonitorList = new HashSet<>(); Set<String> flickerMonitorList = new HashSet<>();
Set<String> harmonicVoltageMonitorList = new HashSet<>(); Set<String> harmonicVoltageMonitorList = new HashSet<>();
Set<String> harmonicCurrentMonitorList = new HashSet<>(); Set<String> harmonicCurrentMonitorList = new HashSet<>();
Set<String> harmonicInHarmonciVMonitorList = new HashSet<>();
int threeV = 0, fiveV = 0, sevenV = 0, elevenV = 0, otherV = 0; int threeV = 0, fiveV = 0, sevenV = 0, elevenV = 0, otherV = 0;
Set<String> threeVList = new HashSet<>(), fiveVList = new HashSet<>(), sevenVList = new HashSet<>(), elevenVList = new HashSet<>(), otherVList = new HashSet<>(); Set<String> threeVList = new HashSet<>(), fiveVList = new HashSet<>(), sevenVList = new HashSet<>(), elevenVList = new HashSet<>(), otherVList = new HashSet<>();
@@ -553,6 +580,8 @@ public class AnalyzeServiceImpl implements IAnalyzeService {
inuharmCount++; inuharmCount++;
} }
//区域报告 //区域报告
if (Objects.nonNull(param.getAreaReportFlag()) && param.getAreaReportFlag() == 1) { if (Objects.nonNull(param.getAreaReportFlag()) && param.getAreaReportFlag() == 1) {
if (item.getFreqDevOvertime() > 0) { if (item.getFreqDevOvertime() > 0) {
@@ -576,7 +605,9 @@ public class AnalyzeServiceImpl implements IAnalyzeService {
} }
if (inHarmFlag(item)) {
harmonicInHarmonciVMonitorList.add(item.getLineId());
}
if (item.getUharm3Overtime() > 0) { if (item.getUharm3Overtime() > 0) {
threeV++; threeV++;
@@ -620,6 +651,7 @@ public class AnalyzeServiceImpl implements IAnalyzeService {
otherI++; otherI++;
otherIList.add(item.getLineId()); otherIList.add(item.getLineId());
} }
} }
} }
@@ -660,6 +692,8 @@ public class AnalyzeServiceImpl implements IAnalyzeService {
//间谐波电压 //间谐波电压
overAreaLimitVO.setInterHarmonicMonitorNumber(inuharmCount); overAreaLimitVO.setInterHarmonicMonitorNumber(inuharmCount);
overAreaLimitVO.setInterHarmonicBiLi(BigDecimal.valueOf(inuharmCount * 1.0 / data.size() * 100).setScale(2, RoundingMode.HALF_UP).doubleValue()); overAreaLimitVO.setInterHarmonicBiLi(BigDecimal.valueOf(inuharmCount * 1.0 / data.size() * 100).setScale(2, RoundingMode.HALF_UP).doubleValue());
overAreaLimitVO.setInHarmonicVMonitorList(new ArrayList<>(harmonicInHarmonciVMonitorList));
} }
@@ -912,6 +946,16 @@ public class AnalyzeServiceImpl implements IAnalyzeService {
return count > 0; return count > 0;
} }
private boolean inHarmVFlag(RStatLimitTargetDPO rStatLimitRateDPO) {
int count = rStatLimitRateDPO.getInuharm1Overtime() + rStatLimitRateDPO.getInuharm2Overtime() + rStatLimitRateDPO.getInuharm3Overtime() +
rStatLimitRateDPO.getInuharm4Overtime() + rStatLimitRateDPO.getInuharm5Overtime() + rStatLimitRateDPO.getInuharm6Overtime() +
rStatLimitRateDPO.getInuharm7Overtime() + rStatLimitRateDPO.getInuharm8Overtime() +
rStatLimitRateDPO.getInuharm9Overtime() + rStatLimitRateDPO.getInuharm10Overtime() + rStatLimitRateDPO.getInuharm11Overtime()+
rStatLimitRateDPO.getInuharm12Overtime() + rStatLimitRateDPO.getInuharm13Overtime() + rStatLimitRateDPO.getInuharm14Overtime()+
rStatLimitRateDPO.getInuharm15Overtime() + rStatLimitRateDPO.getInuharm16Overtime();
return count > 0;
}
private boolean inHarmFlag(RStatLimitTargetDPO t) { private boolean inHarmFlag(RStatLimitTargetDPO t) {
int count = t.getInuharm1Overtime() + t.getInuharm2Overtime() + t.getInuharm3Overtime() + t.getInuharm4Overtime() + t.getInuharm5Overtime() + t.getInuharm6Overtime() + t.getInuharm7Overtime() + t.getInuharm8Overtime() + t.getInuharm9Overtime() + t.getInuharm10Overtime() + t.getInuharm11Overtime() + t.getInuharm12Overtime() + t.getInuharm13Overtime() + t.getInuharm14Overtime() + t.getInuharm15Overtime() + t.getInuharm16Overtime(); int count = t.getInuharm1Overtime() + t.getInuharm2Overtime() + t.getInuharm3Overtime() + t.getInuharm4Overtime() + t.getInuharm5Overtime() + t.getInuharm6Overtime() + t.getInuharm7Overtime() + t.getInuharm8Overtime() + t.getInuharm9Overtime() + t.getInuharm10Overtime() + t.getInuharm11Overtime() + t.getInuharm12Overtime() + t.getInuharm13Overtime() + t.getInuharm14Overtime() + t.getInuharm15Overtime() + t.getInuharm16Overtime();
return count > 0; return count > 0;

View File

@@ -1,12 +1,20 @@
package com.njcn.harmonic.service.impl; package com.njcn.harmonic.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.utils.HarmonicTimesUtil; import com.njcn.common.utils.HarmonicTimesUtil;
import com.njcn.common.utils.PubUtils; import com.njcn.common.utils.PubUtils;
import com.njcn.device.pq.api.LineFeignClient; import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.biz.pojo.po.Overlimit; import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.harmonic.common.mapper.RStatDataHarmRateVDMapper;
import com.njcn.harmonic.common.mapper.RStatDataIDMapper;
import com.njcn.harmonic.constant.Param; import com.njcn.harmonic.constant.Param;
import com.njcn.harmonic.mapper.RStatDataHarmRateIDMapper;
import com.njcn.harmonic.pojo.param.HarmInHarmParam; import com.njcn.harmonic.pojo.param.HarmInHarmParam;
import com.njcn.harmonic.pojo.po.day.RStatDataHarmrateIDPO;
import com.njcn.harmonic.pojo.po.day.RStatDataHarmrateVDPO;
import com.njcn.harmonic.pojo.po.day.RStatDataIDPO;
import com.njcn.harmonic.pojo.vo.HarmInHarmVO; import com.njcn.harmonic.pojo.vo.HarmInHarmVO;
import com.njcn.harmonic.service.HarmInHarmService; import com.njcn.harmonic.service.HarmInHarmService;
import com.njcn.influx.pojo.constant.InfluxDBTableConstant; import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
@@ -21,6 +29,7 @@ import org.springframework.stereotype.Service;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -41,7 +50,8 @@ public class HarmInHarmServiceImpl implements HarmInHarmService {
private final IDataIService dataIService; private final IDataIService dataIService;
private final RStatDataHarmRateVDMapper dataHarmRateVDMapper;
private final RStatDataIDMapper dataIDMapper;
@Override @Override
public HarmInHarmVO getHarmInHarmData(HarmInHarmParam harmInHarmParam) { public HarmInHarmVO getHarmInHarmData(HarmInHarmParam harmInHarmParam) {
HarmInHarmVO harmInHarmVO = new HarmInHarmVO(); HarmInHarmVO harmInHarmVO = new HarmInHarmVO();
@@ -77,33 +87,70 @@ public class HarmInHarmServiceImpl implements HarmInHarmService {
List<Float> floatList = new ArrayList<>(); List<Float> floatList = new ArrayList<>();
if (StrUtil.isNotBlank(lineId)) { if (StrUtil.isNotBlank(lineId)) {
if (harmState == 0) { if (harmState == 0) {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateV.class); // InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateV.class);
influxQueryWrapper.meanSamePrefixAndSuffix("v_", "", HarmonicTimesUtil.harmonicTimesList(2, 50, 1)) // influxQueryWrapper.meanSamePrefixAndSuffix("v_", "", HarmonicTimesUtil.harmonicTimesList(2, 50, 1))
.between(DataHarmRateV::getTime, startTime, endTime) // .between(DataHarmRateV::getTime, startTime, endTime)
.eq(DataHarmRateV::getLineId, lineId) // .eq(DataHarmRateV::getLineId, lineId)
.eq(DataHarmRateV::getValueType, InfluxDBTableConstant.CP95) // .eq(DataHarmRateV::getValueType, InfluxDBTableConstant.CP95)
.ne(DataHarmRateV::getPhaseType, InfluxDBTableConstant.PHASE_TYPE_T); // .ne(DataHarmRateV::getPhaseType, InfluxDBTableConstant.PHASE_TYPE_T);
DataHarmRateV dataHarmRateV = dataHarmRateVService.getMeanAllTimesData(influxQueryWrapper); // DataHarmRateV dataHarmRateV = dataHarmRateVService.getMeanAllTimesData(influxQueryWrapper);
if (Objects.nonNull(dataHarmRateV)) { // if (Objects.nonNull(dataHarmRateV)) {
// for (int i = 2; i < 51; i++) {
// floatList.add(PubUtils.getValueByMethodDouble(dataHarmRateV, "getV", i).floatValue());
// }
// }else {
// for (int i = 2; i < 51; i++) {
// floatList.add(null);
// }
// }
//转换成查mysql统计数据分钟数据没有值
List<RStatDataHarmrateVDPO> harmV = dataHarmRateVDMapper.selectList(new LambdaQueryWrapper<RStatDataHarmrateVDPO>()
.eq(RStatDataHarmrateVDPO::getLineId, lineId)
.eq(RStatDataHarmrateVDPO::getValueType,"CP95")
.in(RStatDataHarmrateVDPO::getPhaseType, Arrays.asList("A","B","C"))
.ge(RStatDataHarmrateVDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
.le(RStatDataHarmrateVDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
);
if (Objects.nonNull(harmV)) {
for (int i = 2; i < 51; i++) { for (int i = 2; i < 51; i++) {
floatList.add(PubUtils.getValueByMethodDouble(dataHarmRateV, "getV", i).floatValue()); floatList.add(PubUtils.getValueByMethodDouble(harmV,RStatDataHarmrateVDPO.class, "getV", i).floatValue());
} }
}else { }else {
for (int i = 2; i < 51; i++) { for (int i = 2; i < 51; i++) {
floatList.add(null); floatList.add(null);
} }
} }
} else { } else {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class); // InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class);
influxQueryWrapper.meanSamePrefixAndSuffix("i_", "", HarmonicTimesUtil.harmonicTimesList(2, 50, 1)) // influxQueryWrapper.meanSamePrefixAndSuffix("i_", "", HarmonicTimesUtil.harmonicTimesList(2, 50, 1))
.between(DataHarmRateV::getTime, startTime, endTime) // .between(DataHarmRateV::getTime, startTime, endTime)
.eq(DataHarmRateV::getLineId, lineId) // .eq(DataHarmRateV::getLineId, lineId)
.eq(DataHarmRateV::getValueType, InfluxDBTableConstant.CP95) // .eq(DataHarmRateV::getValueType, InfluxDBTableConstant.CP95)
.ne(DataHarmRateV::getPhaseType, InfluxDBTableConstant.PHASE_TYPE_T); // .ne(DataHarmRateV::getPhaseType, InfluxDBTableConstant.PHASE_TYPE_T);
DataI dataI = dataIService.getMeanAllTimesData(influxQueryWrapper); // DataI dataI = dataIService.getMeanAllTimesData(influxQueryWrapper);
if (Objects.nonNull(dataI)) { // if (Objects.nonNull(dataI)) {
// for (int i = 2; i < 51; i++) {
// floatList.add(PubUtils.getValueByMethodDouble(dataI, "getI", i).floatValue());
// }
// }else {
// for (int i = 2; i < 51; i++) {
// floatList.add(null);
// }
// }
//转换成查mysql统计数据分钟数据没有值
List<RStatDataIDPO> harmI = dataIDMapper.selectList(new LambdaQueryWrapper<RStatDataIDPO>()
.eq(RStatDataIDPO::getLineId, lineId)
.eq(RStatDataIDPO::getValueType,"CP95")
.in(RStatDataIDPO::getPhaseType, Arrays.asList("A","B","C"))
.ge(RStatDataIDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
.le(RStatDataIDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
);
if (Objects.nonNull(harmI)) {
for (int i = 2; i < 51; i++) { for (int i = 2; i < 51; i++) {
floatList.add(PubUtils.getValueByMethodDouble(dataI, "getI", i).floatValue()); floatList.add(PubUtils.getValueByMethodDouble(harmI,RStatDataIDPO.class, "getI", i).floatValue());
} }
}else { }else {
for (int i = 2; i < 51; i++) { for (int i = 2; i < 51; i++) {

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