221 Commits

Author SHA1 Message Date
wr
39cfffbf7e Merge remote-tracking branch 'origin/main' 2026-04-02 10:45:08 +08:00
wr
1aad1aa86b 1.解决冀北阿里云Nacos版本兼容问题
2.解决配置bootstrap.yml兼容问题
2026-04-02 10:40:11 +08:00
xy
fa500ca600 1、报表、报告新增物联方法
2、公共方法添加
2026-04-01 20:25:08 +08:00
xy
7b9fb1628b App稳态、暂态报告功能支持 2026-03-25 13:28:46 +08:00
fcddc064f6 清除不必要的代码 2026-03-24 19:57:03 +08:00
cdf
37c5e9cbf8 暂降hdr文件生成上传oss 2026-03-24 13:06:23 +08:00
cdf
a08c7db24d 暂降hdr文件生成上传oss 2026-03-24 13:05:38 +08:00
cdf
9225e82edb 区域报告模板bug修改 2026-03-23 13:03:32 +08:00
cdf
e8cd6da8a0 通用台账查询接口调整 2026-03-23 09:19:03 +08:00
cdf
559620ab66 所有模块开启nacos鉴权 2026-03-21 14:31:59 +08:00
cdf
f0b3b81e65 所有模块开启nacos鉴权 2026-03-21 14:27:37 +08:00
cdf
475ca820c8 设备秘钥bug 2026-03-18 17:55:46 +08:00
wr
c0db2cf961 微调 2026-03-05 19:42:57 +08:00
wr
4e95159e01 技术监督用户信息迁移 2026-03-05 19:32:43 +08:00
wr
eec2560fd2 技术监督用户信息迁移 2026-03-05 19:32:03 +08:00
wr
94037d588b 暂态事件报告功能下载 2026-02-28 15:30:35 +08:00
01a77fa92d 1.暂降事件报告 2026-02-27 09:40:12 +08:00
9d9150e418 Merge remote-tracking branch 'origin/main' 2026-02-27 09:35:44 +08:00
ee1ca85a5d 1.暂降事件报告 2026-02-27 09:35:38 +08:00
wr
2c3c716607 河北算法调整 2026-02-26 15:41:16 +08:00
wr
e1d17c63a2 微调 2026-02-26 08:38:03 +08:00
hzj
6234ac8ce9 系统配置合并 2026-02-11 14:34:33 +08:00
6c91774200 1.报告模板bug 2026-02-11 13:31:06 +08:00
fc951e913c 1.微调 2026-02-10 16:32:34 +08:00
d138d4353f 1.用户对象管理业务迁移 2026-02-10 14:48:04 +08:00
aecee4de49 1.用户对象管理业务迁移 2026-02-10 14:36:12 +08:00
hzj
fd04c21997 修改驾驶舱bug 2026-02-10 09:22:04 +08:00
08d8b5b488 Merge remote-tracking branch 'origin/main' 2026-02-09 16:14:05 +08:00
82457bc9c2 1.解决修改台账bug 2026-02-09 16:13:53 +08:00
hzj
63330a04a6 电能质量污区图bug 2026-02-09 16:11:14 +08:00
hzj
ad45661c3c 稳态合格率报告bug 2026-02-09 14:47:27 +08:00
wr
23de6313a6 Merge remote-tracking branch 'origin/main' 2026-02-06 15:09:30 +08:00
wr
7a5ef040bb 冀北数据周报 2026-02-06 15:09:17 +08:00
xy
140ed85108 报表优化 2026-02-06 09:57:15 +08:00
hzj
99ab77dcf0 暂降原因暂降类型那边没兼容大小写后缀 2026-02-03 13:42:28 +08:00
hzj
c772c9cd81 修改定版bug 2026-02-02 16:36:30 +08:00
cdf
996ec87ea8 适配达梦 2026-02-01 13:53:43 +08:00
hzj
b6eaff3b1e 修改定版bug 2026-01-30 14:58:15 +08:00
hzj
56bf5bb7c9 修改bug 2026-01-30 10:17:13 +08:00
wr
7410d32241 Merge remote-tracking branch 'origin/main' 2026-01-29 14:15:18 +08:00
wr
41ba37b723 河北数据中台业务参数调整 2026-01-29 10:30:13 +08:00
wr
3f77d30cfd 1.监测点异常统计报表调整 2026-01-28 11:26:52 +08:00
cdf
f71f87ced4 一键分配装置前置进程 2026-01-28 10:39:18 +08:00
xy
32295f60c0 报表添加接线方式、一二次值判断 2026-01-28 08:43:04 +08:00
hzj
d2945b0fb2 bug修改 2026-01-27 15:33:15 +08:00
hzj
133766a2c7 bug修改 2026-01-27 13:47:35 +08:00
xy
2a5a5087ad 微调 2026-01-26 19:30:33 +08:00
xy
4edb27d20b Merge remote-tracking branch 'origin/main' 2026-01-26 19:28:47 +08:00
xy
71d6636be0 物联短信发送调整 2026-01-26 19:28:37 +08:00
hzj
8ccdb84ea9 Merge remote-tracking branch 'origin/main' 2026-01-26 15:04:32 +08:00
hzj
5389903ed7 暂态模块bug修改 2026-01-26 15:02:25 +08:00
wr
0684bdf503 Merge remote-tracking branch 'origin/main' 2026-01-26 15:00:34 +08:00
wr
d0b4a1ec71 1.监测点异常统计报表 2026-01-23 10:19:55 +08:00
cdf
764ca4a12a 暂降模块调整 2026-01-22 21:54:52 +08:00
hzj
ca992cadbc Merge remote-tracking branch 'origin/main' 2026-01-21 15:02:56 +08:00
hzj
ed166cf1e0 终端删除后,终端日志记录名称修改 2026-01-21 15:02:47 +08:00
cdf
598fa803a1 谐波模块切换动态数据源 2026-01-20 20:43:35 +08:00
cdf
10050ce418 动态数据源 2026-01-19 22:26:43 +08:00
cdf
cb688ad7ad 动态数据源 2026-01-19 20:48:25 +08:00
xy
f6c4d050da 新建物联mapper文件 2026-01-19 14:02:14 +08:00
hzj
fd6ec7bdf2 word报表bug修改 2026-01-19 13:36:36 +08:00
hzj
ca7f1010b0 ITIC曲线画图区间问题 2026-01-19 09:35:26 +08:00
cdf
97ddd133f0 微调 2026-01-18 12:36:33 +08:00
cdf
735c99e8ac 微调 2026-01-18 12:35:42 +08:00
cdf
9a53399ec9 微调 2026-01-18 10:48:33 +08:00
cdf
f27276624a 微调 2026-01-18 10:47:31 +08:00
cdf
df149a3cc2 微调 2026-01-17 20:56:30 +08:00
cdf
7ca23b9431 暂降监测点报告抽取公共方法 2026-01-17 20:25:03 +08:00
cdf
b27f049c9f 监测点报告抽取公共方法 2026-01-17 13:43:24 +08:00
23c4a78383 日志记录改造由mqtt异步改造为redis list实现,TPS满足:150-200条/秒 2026-01-16 15:14:16 +08:00
hzj
c9301d1f8f 修改暂态报告里持续时间单位 2026-01-16 14:43:58 +08:00
hzj
977a0e7a35 暂降区域统计修改暂态事件统计类型:暂降改成不是录波 2026-01-16 11:19:48 +08:00
hzj
9143ff5b80 暂降统计添加中断类型 2026-01-16 09:17:29 +08:00
xy
0502dc7508 基于云平台系统功能调整 2026-01-14 20:31:58 +08:00
cdf
eb689c9852 bug调整 2026-01-14 11:04:12 +08:00
wr
c576bd3bf7 1.阿里云oss中间件 2026-01-13 16:21:33 +08:00
27bac7288c 1.报告微调 2026-01-12 16:49:42 +08:00
a7c69f7c43 1.暂降报告微调 2026-01-12 10:26:41 +08:00
33ab825497 1.微调 2026-01-12 10:12:37 +08:00
22c8ff3b22 1.稳态监测点报告bug修改 2026-01-09 16:00:57 +08:00
hzj
875d114733 Merge remote-tracking branch 'origin/main' 2026-01-09 15:14:22 +08:00
hzj
bd1fe68060 修复污区图空指针bug 2026-01-09 15:13:55 +08:00
c1d933467e 曲靖表格数据提供 2026-01-09 11:42:17 +08:00
wr
e7daf05670 Merge remote-tracking branch 'origin/main' 2026-01-09 09:39:30 +08:00
wr
e251fc6a1a 1.异常数据界面业务调整
2.解决全景监测点详情跳转台账数据不准确稳
2026-01-09 09:37:14 +08:00
0e7cc360f7 1.稳态区域报告功能微调 2026-01-08 16:51:56 +08:00
e2d3394669 1.稳态区域报告功能微调 2026-01-08 16:36:36 +08:00
b3ab5d2587 1.新增稳态区域报告功能 2026-01-08 13:52:09 +08:00
hzj
ed029139d3 稳态word报告,基波电流基波电压错误,长闪短闪错乱,2-25电压含有率,电流幅值错乱修改 2026-01-08 09:51:35 +08:00
xy
02578546f2 基于云平台系统功能调整 2026-01-07 19:21:21 +08:00
hzj
09e2f329b7 海南bug修改提交 2026-01-07 11:32:03 +08:00
hzj
ee2fae105b 海南bug修改提交 2026-01-07 10:10:59 +08:00
82efce189a 曲靖3层树特殊处理 2026-01-07 08:50:51 +08:00
hzj
be8c14625f 海南bug修改提交 2026-01-05 20:33:45 +08:00
95a571d3c3 Merge remote-tracking branch 'origin/main' 2026-01-05 16:55:53 +08:00
322001150a 1.监测点稳态报表bug修改 2026-01-05 16:55:47 +08:00
hzj
b805bda25b 海南bug修改提交 2026-01-05 11:20:23 +08:00
f592f2b580 1.监测点稳态报告cp95值逻辑调整 2026-01-05 10:45:26 +08:00
wr
184b2b8fad Merge remote-tracking branch 'origin/main' 2026-01-04 14:54:04 +08:00
wr
fe029fcb95 1.异常数据界面业务调整
2.技术监督增加仿真治理方案
2026-01-04 14:50:03 +08:00
hzj
9143466ce7 海南bug修改提交 2025-12-29 15:29:51 +08:00
hzj
9409d57243 海南bug修改提交 2025-12-29 14:26:30 +08:00
63603dee08 海南数据不一致问题处理 2025-12-29 10:34:38 +08:00
wr
e35bbd9b34 Merge remote-tracking branch 'origin/main' 2025-12-29 09:27:20 +08:00
wr
ea2173fff4 增加二级评估用户绑定 2025-12-29 09:27:03 +08:00
faac7953d3 海南数据不一致问题处理 2025-12-26 15:29:33 +08:00
xy
c3cc39973e Merge remote-tracking branch 'origin/main' 2025-12-26 11:24:40 +08:00
xy
6d8bfacd0a 在线监测算法每日更新导致告警单丢失问题 2025-12-26 11:24:22 +08:00
wr
ab5d28e3cb 变电站台账数据调整 2025-12-26 11:23:47 +08:00
wr
2dccb22cf8 Merge remote-tracking branch 'origin/main' 2025-12-26 11:22:51 +08:00
xy
6b0bad6047 微调 2025-12-25 20:44:52 +08:00
9ffbdbdf57 驾驶舱全局处理 2025-12-25 20:39:28 +08:00
wr
778f689b3e 优化异常数据和稳态告警接口信息 2025-12-25 15:32:21 +08:00
hzj
917e3fb2d5 海南bug修改提交 2025-12-23 11:40:18 +08:00
cdf
e0f1e314a4 组件管理加排序 2025-12-23 09:33:18 +08:00
cdf
2f2ed06a35 组件管理加排序 2025-12-22 19:59:25 +08:00
xy
277400670d 微调 2025-12-22 14:11:16 +08:00
xy
a1031109c4 微调 2025-12-22 10:09:15 +08:00
cdf
eeb27c519b sql适配大梦数据库 2025-12-19 16:15:55 +08:00
wr
670eaf7d38 微调 2025-12-19 10:19:59 +08:00
xy
2b79cefad6 微调 2025-12-19 10:18:13 +08:00
xy
212db18835 新增异常数据问题 2025-12-18 22:24:03 +08:00
wr
e9a1c34160 调整异常数据界面业务 2025-12-18 22:22:36 +08:00
wr
fb7a2b7084 调整异常数据界面业务 2025-12-17 19:25:08 +08:00
wr
4b3ec39a11 Merge remote-tracking branch 'origin/main' 2025-12-16 18:25:33 +08:00
wr
2d255a5dd3 微调 2025-12-16 18:23:43 +08:00
hzj
614647d36d Merge remote-tracking branch 'origin/main' 2025-12-16 16:23:57 +08:00
hzj
a899614c89 添加注释 2025-12-16 16:22:53 +08:00
wr
2543f87dd2 Merge remote-tracking branch 'origin/main' 2025-12-16 15:37:53 +08:00
wr
c5074df93d 1.调整台账管理变电站搜索
2.解决优化部分台账信息
2025-12-16 13:57:04 +08:00
24e4c4de37 调整bug 2025-12-16 13:48:59 +08:00
wr
4f70566c65 微调 2025-12-15 19:14:23 +08:00
wr
dc11d34add 微调 2025-12-15 18:20:42 +08:00
xy
9f3bb52d9a 微调 2025-12-15 16:41:23 +08:00
wr
567ba2f56e 微调 2025-12-15 14:33:48 +08:00
wr
371d4efb29 微调 2025-12-15 13:56:14 +08:00
wr
47b08d4797 1.调整全景稳态统计超标监测点占比
2.优化稳态word报告
2025-12-15 13:32:38 +08:00
xy
65805e4f50 微调 2025-12-15 13:25:12 +08:00
xy
41d555121c 添加电网标识字段 2025-12-14 22:28:10 +08:00
wr
4d48b42c98 完善全景详情监测点超标信息 2025-12-14 16:43:17 +08:00
wr
f5e1fac55d 微调 2025-12-14 15:42:55 +08:00
wr
cebda9323e 增加暂态信息搜索,调整全景区域污染值逻辑 2025-12-14 14:24:15 +08:00
xy
d09f1472a9 代码优化 2025-12-14 00:55:49 +08:00
xy
b9696e957d 代码优化 2025-12-13 23:59:26 +08:00
xy
12cfecac7e 敏感用户污染值统计 2025-12-13 20:33:08 +08:00
xy
3a97f01383 地市合格率报错 2025-12-13 11:11:50 +08:00
wr
10273dd2b0 调整全景监测点详情里,监测点超标为只为谐波电压超标 2025-12-13 11:09:23 +08:00
wr
5e8e03cbb1 微调 2025-12-12 17:53:21 +08:00
wr
b103141a54 1.技术监督修改 2025-12-12 17:33:04 +08:00
wr
a6d2d6ed47 1.全景增加技术监督计划调整
2.增加暂态列表信息和监测点评估信息
2025-12-12 15:01:29 +08:00
xy
601a78246e 代码优化 2025-12-12 14:58:35 +08:00
xy
5e7b973d5f 1.稳态告警查询优化 2.在线监测数据异常排查 2025-12-11 15:04:31 +08:00
wr
e89c6a2888 1.全景增加暂态信息和调整告警条件
2.增加暂态列表信息和冀北树污染值条件
2025-12-11 15:02:52 +08:00
xy
2166529b4d Merge remote-tracking branch 'origin/main' 2025-12-10 16:25:57 +08:00
xy
2117e16b61 1.修改全景稳态告警数据不一致问题 2.初步修改在线监测功能 2025-12-10 16:25:38 +08:00
wr
054d5534a8 微调 2025-12-10 16:25:04 +08:00
wr
c03a516931 Merge remote-tracking branch 'origin/main' 2025-12-10 16:22:42 +08:00
wr
0fdc3edb89 1.解决变电站数量不统一问题
2.替换最新污染值
3.解决终端数量不一致问题
2025-12-10 16:19:35 +08:00
a730ad61b1 调整白名单 2025-12-10 15:32:32 +08:00
9b758dc7c9 增加swagger配置 2025-12-10 14:56:01 +08:00
a74dd460d1 Merge remote-tracking branch 'origin/main' 2025-12-10 14:55:48 +08:00
2708aa8b81 增加swagger配置 2025-12-10 14:55:31 +08:00
wr
6d833678a6 微调 2025-12-08 15:08:21 +08:00
xy
be264acd79 功能优化 2025-12-08 15:07:48 +08:00
wr
186d46752c Merge remote-tracking branch 'origin/main' 2025-12-05 15:34:12 +08:00
wr
e03478eeec 终端运行评价,异常数据率 2025-12-05 15:25:10 +08:00
贾同学
0c1bb606d6 feat(user): 支持组件时间标识集合字段 2025-12-03 15:16:31 +08:00
wr
42b619fa56 微调 2025-12-02 16:42:46 +08:00
wr
f0894ca0ed 微调 2025-12-02 16:05:13 +08:00
wr
8a958fa34c Merge remote-tracking branch 'origin/main' 2025-12-02 12:32:21 +08:00
贾同学
770fb09223 refactor(harmonic): 优化数据源配置并移除冗余依赖
- 为 RStatLimitRateDetailDServiceImpl 和 RStatLimitRateDServiceImpl 添加 @DS 注解以支持多数据源切换
- 在 harmonic-common 模块中引入 dynamic-datasource-spring-boot-starter 依赖
- 移除 harmonic-boot 模块中对 harmonic-common 的冗余依赖声明
- 调整 AlarmClientFallbackFactory 组件名称以避免命名冲突
2025-12-02 08:44:01 +08:00
wr
b4e5d0c638 微调 2025-12-01 09:12:29 +08:00
wr
eb334cc7c7 Merge remote-tracking branch 'origin/main' 2025-11-28 10:58:11 +08:00
wr
404d11526a 冀北终端评价列表信息增加 2025-11-28 10:47:50 +08:00
xy
7bac805988 微调 2025-11-27 15:27:31 +08:00
wr
e4e04fc5db 冀北终端评价列表 2025-11-27 14:27:45 +08:00
f588a0ffc8 1.暂降高级类型原因调用dll报错问题 2025-11-26 15:13:34 +08:00
xy
f8ffe767dc 冀北完整性功能重新开发 2025-11-26 11:09:11 +08:00
wr
68cbad2fdb 冀北终端在线率代码提交 2025-11-27 11:03:59 +08:00
wr
9b9d75e463 冀北终端在线率代码提交 2025-11-27 11:01:24 +08:00
wr
62c3c09a6b 1.冀北终端在线率代码提交 2025-11-26 16:08:20 +08:00
wr
b523a24e5b Merge remote-tracking branch 'origin/main' 2025-11-26 16:04:33 +08:00
wr
075dfc19d6 1.异常数据统计增加暂态信息 2025-11-26 09:58:49 +08:00
wr
279c5c7642 1.增加稳态告警统计限值 2025-11-25 17:00:22 +08:00
hzj
ff1351b107 添加海量数据库驱动 2025-11-25 13:57:51 +08:00
贾同学
2dd67f9e3a feat(rstatlimitrate): 新增电网侧指标越限统计数据和列表接口 2025-11-20 08:50:13 +08:00
wr
b0ef851479 1.解决解决全景和台账管理,终端数量不一致问题 2025-11-19 14:58:37 +08:00
贾同学
be899a262b feat(rstatlimitrate): 新增越限概率分布统计功能
- 添加越限程度概率分布接口及实现
- 添加越限时间概率分布接口及实现
2025-11-19 14:07:04 +08:00
xy
4339a37268 物联用户权限分配 2025-11-17 09:38:19 +08:00
贾同学
9659aa257a feat(rstatlimitrate): 添加越限程度、日趋势图和日历数据查询接口 2025-11-14 16:30:17 +08:00
xy
9d32ca05df 物联用户权限分配 2025-11-14 10:00:24 +08:00
贾同学
d48cf09119 feat(harmonic): 新增获取主要监测点列表、监测点指标越限详情、总体指标越限统计数据、总体指标越限统计列表、每日越限占比统计接口 2025-11-13 09:03:30 +08:00
wr
c38b07ec07 Merge remote-tracking branch 'origin/main' 2025-11-11 15:12:33 +08:00
wr
87f05c6278 1.提交场站评估代码 2025-11-11 14:53:51 +08:00
e9ac024f73 1.趋势图查询添加多线程处理
2.变压器策略调整
2025-11-11 14:33:16 +08:00
xy
b7e3bb9796 驾驶舱功能调整 2025-11-11 11:39:59 +08:00
4bebf28b76 抽取公共代码提供给物联项目使用 2025-11-06 16:10:00 +08:00
wr
20ec9bc0b4 1.根据专责要求调整冀北台账树 2025-11-04 17:10:46 +08:00
xy
5e93eb3691 驾驶舱功能调整 2025-10-24 16:14:54 +08:00
xy
b63fab9085 云前置改造-暂态数据补召功能新增topic 2025-10-15 20:50:47 +08:00
hzj
aba66aaf4a Merge branch 'main' of http://192.168.1.22:3000/Microservice/pqs 2025-10-15 11:46:05 +08:00
hzj
1c7c514691 报表bug修改 2025-10-15 11:42:56 +08:00
04fe9bdbbd Merge pull request 'liaoning' (#1) from liaoning into main
Reviewed-on: #1
2025-10-15 10:39:21 +08:00
hzj
b41347c596 Merge remote-tracking branch 'origin/main' into liaoning 2025-10-15 10:38:02 +08:00
hzj
4f75deac43 报表bug修改 2025-10-15 10:33:51 +08:00
2c68646fc9 本地文件bug修改 2025-10-14 20:35:36 +08:00
02599eeb81 bug修改 2025-10-14 18:06:22 +08:00
xy
0cec471ce2 云前置改造-新增mq信息 2025-10-14 11:40:44 +08:00
wr
102bab7430 调整终端运行部分代码 2025-10-11 10:56:12 +08:00
28378dcfa1 测试 2025-10-11 10:50:53 +08:00
1692799f0b 波形解析bug 2025-10-11 10:00:24 +08:00
90471c368d 波形解析bug 2025-09-22 10:08:06 +08:00
08ec8591f1 波形解析bug 2025-09-19 08:36:18 +08:00
xy
d038dfe655 ln分支-新增mq信息 2025-09-16 18:27:52 +08:00
c1bf8d79ce 波形解析代码移植 2025-09-15 09:54:46 +08:00
74420e7107 谐波责任量化java版本重构,需测试,单体已经测试没有问题 2025-09-14 00:12:34 +08:00
wr
6815e1df4b 微调 2025-09-11 15:31:50 +08:00
wr
c1dca815e7 微调 2025-09-11 09:38:27 +08:00
wr
5c3baf4e57 微调 2025-09-11 09:29:39 +08:00
wr
28f7e038ce 模板库 2025-09-11 09:18:47 +08:00
fe1195b7b5 本地文件存储修改 2025-09-10 19:25:54 +08:00
654 changed files with 43044 additions and 14458 deletions

17
pom.xml
View File

@@ -39,11 +39,12 @@
</snapshotRepository>
</distributionManagement>
<properties>
<spring.profiles.active>sjzx</spring.profiles.active>
<!--中间件目标地址-->
<!-- <middle.server.url>10.95.53.49</middle.server.url>-->
<middle.server.url>192.168.1.22</middle.server.url>
<middle.server.url>192.168.1.103</middle.server.url>
<!--微服务模块发布地址-->
<service.server.url>192.168.1.127</service.server.url>
<service.server.url>192.168.2.130</service.server.url>
<!--docker仓库地址-->
<docker.server.url>192.168.1.22</docker.server.url>
<!--nacos的ip:port-->
@@ -51,11 +52,11 @@
<!--nacos开启鉴权后的用户名-->
<nacos.username>nacos</nacos.username>
<!--nacos的ip:port-->
<nacos.password>nacos</nacos.password>
<nacos.password>njcnpqs</nacos.password>
<!--服务器发布内容为空-->
<!-- <nacos.namespace></nacos.namespace>-->
<nacos.namespace>hswbpm</nacos.namespace>
<!-- <nacos.namespace>30c701c4-2a94-49d9-82e1-76aa9456573f</nacos.namespace>-->
<nacos.namespace>78588706-e06f-4580-b612-b26d72493fcb</nacos.namespace>
<!-- <nacos.namespace>12b467cc-a7e6-411d-8944-090cbfa09dde</nacos.namespace>-->
<!-- <nacos.namespace>910d0d69-2254-481b-b9f7-7ecf9cb881b0</nacos.namespace>-->
<!-- sentinel:port-->
<sentinel.url>${middle.server.url}:8080</sentinel.url>
@@ -81,6 +82,7 @@
<springcloud.alibaba.version>2.2.7.RELEASE</springcloud.alibaba.version>
<hutool.version>5.8.11</hutool.version>
<knife4j.version>3.0.2</knife4j.version>
<postgresql.version>42.3.8</postgresql.version>
<knife4j.aggregation.version>2.0.8</knife4j.aggregation.version>
<lombok.version>1.18.18</lombok.version>
<mybatis.version>2.1.3</mybatis.version>
@@ -171,6 +173,11 @@
<artifactId>knife4j-spring-ui</artifactId>
<version>${knife4j.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-aggregation-spring-boot-starter</artifactId>

View File

@@ -2,8 +2,14 @@ package com.njcn.advance.api;
import com.njcn.advance.api.fallback.EventWaveAnalysisFeignClientFallbackFactory;
import com.njcn.advance.pojo.dto.waveAnalysis.EntityAdvancedData;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@@ -27,4 +33,7 @@ public interface EventWaveAnalysisFeignClient {
*/
@PostMapping("analysis")
HttpResult<EntityAdvancedData> analysis(@RequestParam("eventIndex") String eventIndex);
@PostMapping("analysisWlEvent")
HttpResult<EntityAdvancedData> analysisWlEvent(@RequestParam("eventIndex") String eventIndex);
}

View File

@@ -32,6 +32,12 @@ public class EventWaveAnalysisFeignClientFallbackFactory implements FallbackFact
log.error("{}异常,降级处理,异常为:{}", "波形高级分析", throwable.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<EntityAdvancedData> analysisWlEvent(String eventIndex) {
log.error("{}异常,降级处理,异常为:{}", "物联测点波形高级分析异常", throwable.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -73,4 +73,10 @@ public class EventAnalysisDTO {
* 1 正常计算
*/
private Integer typeFlag = 1;
/**
* 文件全路径
* 适配物联的暂态事件解析 物联那边事件的路径是全路径,不需要拼接,这个参数可为空
*/
private String wlFilePath;
}

View File

@@ -264,7 +264,7 @@ public class AnalyWave {
break;
case 1:// 总点数 //这里的strTemp是一个偏移量
OneRate.nSampleNum = (long) (Float.parseFloat(strTempArray[j]) - nOffset);
nOffset = OneRate.nSampleNum;
nOffset += OneRate.nSampleNum;
break;
}
}

View File

@@ -47,7 +47,7 @@ import java.util.List;
* angle_diff_cn C相相位负跳变
* bph_max_value 不平衡度(单位%
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIgnoreProperties(ignoreUnknown = true,value = {"pointer"})
public class BackData extends Structure {
public int qvvr_cata_cause[] = new int[256];
public int qvvr_phasetype[] = new int[256];

View File

@@ -23,8 +23,13 @@ public class CauseStruct extends Structure {
public static class ByValue extends CauseStruct implements Structure.ByValue {
}
// @Override
// protected List<String> getFieldOrder() { // 返回值填入的顺序
// return Arrays.asList(new String[] { "cause", "no_cal" });
// }
@Override
protected List<String> getFieldOrder() { // 返回值填入的顺序
return Arrays.asList(new String[] { "cause", "no_cal" });
protected List<String> getFieldOrder() {
return Arrays.asList("smp_va", "smp_vb", "smp_vc", "smp_rate", "smp_len", "threshold", "cause", "no_cal");
}
}

View File

@@ -35,8 +35,13 @@ public class Rect extends Structure {
}
// @Override
// protected List<String> getFieldOrder() {
// return Arrays.asList(new String[] { "evt_num","evt_buf" });
// }
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "evt_num","evt_buf" });
return Arrays.asList("smp_va", "smp_vb", "smp_vc", "smp_rate", "smp_len", "evt_num", "evt_buf");
}
}

View File

@@ -83,10 +83,10 @@ public class EventRelevantAnalysisController extends BaseController {
public HttpResult<Page<RmpEventDetailAssPO>> queryEventsAssPage(@RequestBody BaseParam baseParam){
String methodDescribe = getMethodDescribe("queryEventsAssPage");
String searchValue = baseParam.getSearchValue();
Pattern pattern = Pattern.compile(PatternRegex.SPECIAL_REGEX);
if(pattern.matcher(searchValue).find()){
throw new BusinessException(ValidMessage.SPECIAL_REGEX);
}
// Pattern pattern = Pattern.compile(PatternRegex.SPECIAL_REGEX);
// if(pattern.matcher(searchValue).find()){
// throw new BusinessException(ValidMessage.SPECIAL_REGEX);
// }
Page<RmpEventDetailAssPO> page = eventRelevantAnalysisService.queryEventsAssPage(baseParam);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe);
}

View File

@@ -34,7 +34,6 @@ public class EventWaveAnalysisController extends BaseController {
private final EventWaveAnalysisService eventWaveAnalysisService;
@PostMapping("analysis")
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("波形高级分析")
@@ -43,6 +42,15 @@ public class EventWaveAnalysisController extends BaseController {
String methodDescribe = getMethodDescribe("analysis");
EntityAdvancedData entityAdvancedData = eventWaveAnalysisService.analysis(eventIndex);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, entityAdvancedData, methodDescribe);
}
@PostMapping("analysisWlEvent")
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("物联事件波形高级分析")
@ApiImplicitParam(name = "eventIndex", value = "暂降事件id", required = true)
public HttpResult<EntityAdvancedData> analysisWlEvent(@RequestParam("eventIndex") String eventIndex) {
String methodDescribe = getMethodDescribe("analysisWlEvent");
EntityAdvancedData entityAdvancedData = eventWaveAnalysisService.analysisWlEvent(eventIndex);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, entityAdvancedData, methodDescribe);
}
}

View File

@@ -67,7 +67,9 @@ public interface QvvrCauseDLL extends Library {
// 创建临时文件
String tempDir = System.getProperty("java.io.tmpdir");
File tempLibFile = new File(tempDir, "qvvr_" + System.currentTimeMillis() + "_" + libFileName);
File tempLibFile = new File(tempDir, libFileName);
//File tempLibFile = new File(tempDir, "qvvr_" + System.currentTimeMillis() + "_" + libFileName);
// 提取库文件到临时目录
try (FileOutputStream out = new FileOutputStream(tempLibFile)) {

View File

@@ -1,14 +1,14 @@
package com.njcn.advance.event.service.impl;
import cn.hutool.core.util.StrUtil;
import com.njcn.advance.event.cause.core.VoltageSagAnalyzer;
import com.njcn.advance.enums.EnumEvt;
import com.njcn.advance.event.cause.jna.QvvrCauseDLL;
import com.njcn.advance.event.cause.model.AnalysisResult;
import com.njcn.advance.event.cause.model.DataFeature;
import com.njcn.advance.event.cause.model.QvvrDataStruct;
import com.njcn.advance.event.type.jna.*;
import com.njcn.advance.pojo.dto.EventAnalysisDTO;
import com.njcn.advance.event.service.IEventAdvanceService;
import com.njcn.advance.event.type.jna.QvvrDLL;
import com.njcn.advance.pojo.dto.waveAnalysis.Rect;
import com.njcn.advance.utils.Utils;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.event.file.component.WaveFileComponent;
@@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.List;
@@ -47,11 +48,12 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
public EventAnalysisDTO analysisCauseAndType(EventAnalysisDTO eventAnalysis) {
WaveDataDTO waveDataDTO;
String waveName = eventAnalysis.getWaveName();
String wlFilePath = eventAnalysis.getWlFilePath();
String cfgPath, datPath, cfgPath2, datPath2;
String ip = eventAnalysis.getIp();
if (generalInfo.getBusinessWaveFileStorage() == GeneralConstant.LOCAL_DISK) {
cfgPath = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.CFG;
datPath = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.DAT;
cfgPath = Objects.isNull(wlFilePath) ? generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.CFG : wlFilePath + GeneralConstant.CFG;
datPath = Objects.isNull(wlFilePath) ? generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.DAT : wlFilePath + GeneralConstant.DAT;
log.info("本地磁盘波形文件路径----" + cfgPath);
InputStream cfgStream = waveFileComponent.getFileInputStreamByFilePath(cfgPath);
InputStream datStream = waveFileComponent.getFileInputStreamByFilePath(datPath);
@@ -60,11 +62,11 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
}
waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 0);
} else {
cfgPath = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.CFG;
datPath = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.DAT;
cfgPath = Objects.isNull(wlFilePath) ? OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.CFG : wlFilePath + GeneralConstant.CFG;
datPath = Objects.isNull(wlFilePath) ? OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.DAT : wlFilePath + GeneralConstant.DAT;
//适配文件后缀小写
cfgPath2 = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.CFG.toLowerCase();
datPath2 = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.DAT.toLowerCase();
cfgPath2 = Objects.isNull(wlFilePath) ? OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.CFG.toLowerCase() : wlFilePath + GeneralConstant.CFG.toLowerCase();
datPath2 = Objects.isNull(wlFilePath) ? OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.DAT.toLowerCase() : wlFilePath + GeneralConstant.DAT.toLowerCase();
log.info("文件服务器波形文件路径----" + cfgPath);
try (
InputStream cfgStream = fileStorageUtil.getFileStream(cfgPath);
@@ -89,8 +91,70 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
}
}
List<List<Float>> listWaveData = waveDataDTO.getListWaveData();
// 暂降类型
// 创建数据结构
QvvrDLL.QvvrDataStruct typeDataStruct = new QvvrDLL.QvvrDataStruct();
System.out.println("初始化qvvrdll成功-----------");
typeDataStruct.smp_rate = waveDataDTO.getComtradeCfgDTO().getFinalSampleRate();
System.out.println("采样率-----------" + typeDataStruct.smp_rate);
typeDataStruct.smp_len = listWaveData.size();
System.out.println("波形长度-----------" + listWaveData.size());
// 获取ABC三相的瞬时数据
for (int i = 0; i < listWaveData.size(); i++) {
typeDataStruct.smp_va[i] = listWaveData.get(i).get(1);
typeDataStruct.smp_vb[i] = listWaveData.get(i).get(2);
typeDataStruct.smp_vc[i] = listWaveData.get(i).get(3);
}
// 执行算法分析 - 直接调用C DLL
try {
QvvrDLL.INSTANCE.qvvr_fun(typeDataStruct);
System.out.println("调用qvvrdll成功-----------");
if (typeDataStruct.evt_num > 0) {
// 全局比较找出最小三相电压特征值
float globalMinVoltage = Float.MAX_VALUE;
int globalFaultType = 10;
for (int i = 0; i < typeDataStruct.evt_num; i++) {
QvvrDLL.EventBuffer evt = typeDataStruct.evt_buf[i];
for (int j = 0; j < evt.u_min_num; j++) {
float u3min = evt.u3_min[j];
if (u3min < globalMinVoltage) {
globalMinVoltage = u3min;
globalFaultType = evt.qvvr_cata_type[j];
}
}
}
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
eventAnalysis.setType(globalFaultType);
} else {
eventAnalysis.setType(DataFeature.TYPE10);
}
System.out.println("结束qvvrdll方法调用-----------");
} catch (Exception e) {
eventAnalysis.setType(DataFeature.TYPE10);
eventAnalysis.setTypeFlag(0);
}
// 暂降原因JNA的方式
com.njcn.advance.event.cause.jna.QvvrCauseDLL.QvvrDataStruct causeDataStruct = new com.njcn.advance.event.cause.jna.QvvrCauseDLL.QvvrDataStruct();
QvvrCauseDLL.QvvrDataStruct causeDataStruct = new QvvrCauseDLL.QvvrDataStruct();
causeDataStruct.smp_rate = waveDataDTO.getComtradeCfgDTO().getFinalSampleRate();
causeDataStruct.smp_len = listWaveData.size();
// 获取ABC三相的瞬时数据
@@ -112,45 +176,308 @@ public class EventAdvanceServiceImpl implements IEventAdvanceService {
}
System.out.println("暂降原因分析完毕===============");
System.out.println("cause:" + eventAnalysis);
// 暂降类型
// 创建数据结构
// com.njcn.advance.event.type.jna.QvvrDLL.QvvrDataStruct typeDataStruct = new com.njcn.advance.event.type.jna.QvvrDLL.QvvrDataStruct();
// typeDataStruct.smp_rate = waveDataDTO.getComtradeCfgDTO().getFinalSampleRate();
// typeDataStruct.smp_len = listWaveData.size();
// // 获取ABC三相的瞬时数据
// for (int i = 0; i < listWaveData.size(); i++) {
// typeDataStruct.smp_va[i] = listWaveData.get(i).get(1);
// typeDataStruct.smp_vb[i] = listWaveData.get(i).get(2);
// typeDataStruct.smp_vc[i] = listWaveData.get(i).get(3);
// }
// // 执行算法分析 - 直接调用C DLL
// try {
// QvvrDLL.INSTANCE.qvvr_fun(typeDataStruct);
// if (typeDataStruct.evt_num > 0) {
// // 全局比较找出最小三相电压特征值
// float globalMinVoltage = Float.MAX_VALUE;
// int globalFaultType = 10;
// for (int i = 0; i < typeDataStruct.evt_num; i++) {
// QvvrDLL.EventBuffer evt = typeDataStruct.evt_buf[i];
// for (int j = 0; j < evt.u_min_num; j++) {
// float u3min = evt.u3_min[j];
// if (u3min < globalMinVoltage) {
// globalMinVoltage = u3min;
// globalFaultType = evt.qvvr_cata_type[j];
// }
// }
// }
// eventAnalysis.setType(globalFaultType);
// } else {
// eventAnalysis.setType(DataFeature.TYPE10);
// }
// } catch (Exception e) {
// eventAnalysis.setType(DataFeature.TYPE10);
// eventAnalysis.setTypeFlag(0);
// }
return eventAnalysis;
}
public String WriteData2File(QvvrDLL.QvvrDataStruct rect) throws Exception {
StringBuilder stringBuilder = new StringBuilder("{" + EnumEvt.NEWLINE.getProperty());
/**
* @写入返回事件总数
*/
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.EVT_NUM.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.int2String(rect.evt_num), 1));
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.EVT_BUF.getProperty()) + "[");
/**
* @写入返回事件参数
*/
for (int i = 0; i < rect.evt_num; i++) {
stringBuilder.append(EnumEvt.setNewLine() + EnumEvt.setTab(2));
/**
* @波形起始点
*/
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.POW_A.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(rect.evt_buf[i].POW_a), 3));
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.POW_B.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(rect.evt_buf[i].POW_b), 3));
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.POW_C.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(rect.evt_buf[i].POW_c), 3));
/**
* @跳变段电压变化率
*/
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.VOLTAGECHANGE_VA.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(rect.evt_buf[i].Voltagechange_Va), 3));
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.VOLTAGECHANGE_VB.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(rect.evt_buf[i].Voltagechange_Vb), 3));
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.VOLTAGECHANGE_VC.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(rect.evt_buf[i].Voltagechange_Vc), 3));
/**
* @持续时间
*/
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.HOLD_TIME_RMS.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(rect.evt_buf[i].hold_time_rms), 3));
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.HOLD_TIME_DQ.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(rect.evt_buf[i].hold_time_dq), 3));
/**
* @分段数目
*/
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.SEG_T_NUM.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.int2String(rect.evt_buf[i].SEG_T_num), 3));
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.SEG_T_IDX.getProperty()));
stringBuilder.append(EnumEvt.setNewLine() + EnumEvt.setTab(3));
for (int j = 0; j < rect.evt_buf[i].SEG_T_num; j++) {
stringBuilder.append(EnumEvt.setEvtProperty(Utils.int2String(j)));
if (rect.evt_buf[i].SEG_T_num - 1 == j) {
stringBuilder.append(Utils.int2String(rect.evt_buf[i].SEG_T_idx[j]));
} else {
stringBuilder.append(EnumEvt.setEnter(Utils.int2String(rect.evt_buf[i].SEG_T_idx[j]), 4));
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @特征幅值
*/
stringBuilder.append(EnumEvt.setEvtProperty(EnumEvt.U_MIN_NUM.getProperty()));
stringBuilder.append(EnumEvt.setEnter(Utils.int2String(rect.evt_buf[i].u_min_num), 3));
/**
* @最小值位置
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.ORDER_MIN_IDX.getProperty(), null,
rect.evt_buf[i].order_min_idx[k]);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @A相电压特征值
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.UA_MIN.getProperty(), rect.evt_buf[i].ua_min[k], null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @B相电压特征值
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.UB_MIN.getProperty(), rect.evt_buf[i].ub_min[k], null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @C相电压特征值
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.UC_MIN.getProperty(), rect.evt_buf[i].uc_min[k], null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @三相电压特征值
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.U3_MIN.getProperty(), rect.evt_buf[i].u3_min[k], null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @A相相位正跳变
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.ANGLE_DIFF_AP.getProperty(), rect.evt_buf[i].angle_diff_ap[k],
null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @B相相位正跳变
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.ANGLE_DIFF_BP.getProperty(), rect.evt_buf[i].angle_diff_bp[k],
null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @C相相位正跳变
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.ANGLE_DIFF_CP.getProperty(), rect.evt_buf[i].angle_diff_cp[k],
null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @A相相位负跳变
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.ANGLE_DIFF_AN.getProperty(), rect.evt_buf[i].angle_diff_an[k],
null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @B相相位负跳变
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.ANGLE_DIFF_BN.getProperty(), rect.evt_buf[i].angle_diff_bn[k],
null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @C相相位负跳变
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.ANGLE_DIFF_CN.getProperty(), rect.evt_buf[i].angle_diff_cn[k],
null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @不平衡度
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.BPH_MAX_VALUE.getProperty(), rect.evt_buf[i].bph_max_value[k],
null);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @暂降原因
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.QVVR_CATA_CAUSE.getProperty(), null,
rect.evt_buf[i].qvvr_cata_cause[k]);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @暂降类型
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.QVVR_CATA_TYPE.getProperty(), null,
rect.evt_buf[i].qvvr_cata_type[k]);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(3), 3));
/**
* @暂降相别
*/
for (int k = 0; k < rect.evt_buf[i].u_min_num; k++) {
setEigenVlaue(k, stringBuilder, EnumEvt.QVVR_PHASETYPE.getProperty(), null,
rect.evt_buf[i].qvvr_phasetype[k]);
if (rect.evt_buf[i].u_min_num - 1 == k) {
stringBuilder.delete(stringBuilder.lastIndexOf(","), stringBuilder.length() - 1);
}
}
stringBuilder.append(EnumEvt.setClose(3));
if (rect.evt_num - 1 == i) {
stringBuilder.append(EnumEvt.setClose(2));
stringBuilder.append("]" + EnumEvt.ENTER.getProperty());
} else {
stringBuilder.append(EnumEvt.setEnter(EnumEvt.setClose(2), 2));
}
}
stringBuilder.append("}");
return stringBuilder.toString();
}
/**
* @特征值处理
*/
public void setEigenVlaue(int len, StringBuilder stringBuilder, String string, Float f, Integer integer) {
if (0 == len) {
stringBuilder.append(EnumEvt.setEvtProperty(string));
stringBuilder.append(EnumEvt.setNewLine() + EnumEvt.setTab(3));
}
stringBuilder.append(EnumEvt.setEvtProperty(Integer.toString(len)));
if (null == f) {
stringBuilder.append(EnumEvt.setEnter(Utils.int2String(integer.intValue()), 4));
} else {
stringBuilder.append(EnumEvt.setEnter(Utils.float2String(f.floatValue()), 4));
}
}
}

View File

@@ -52,7 +52,7 @@ public interface QvvrDLL extends Library {
);
}
}
/**
* 从jar中提取库文件到临时目录
*/
@@ -62,11 +62,13 @@ public interface QvvrDLL extends Library {
if (libStream == null) {
throw new FileNotFoundException("在jar中找不到库文件: " + resourcePath);
}
// 创建临时文件
String tempDir = System.getProperty("java.io.tmpdir");
File tempLibFile = new File(tempDir, "qvvr_" + System.currentTimeMillis() + "_" + libFileName);
File tempLibFile = new File(tempDir, libFileName);
// File tempLibFile = new File(tempDir, "qvvr_" + System.currentTimeMillis() + "_" + libFileName);
// 提取库文件到临时目录
try (FileOutputStream out = new FileOutputStream(tempLibFile)) {
byte[] buffer = new byte[8192];
@@ -77,45 +79,47 @@ public interface QvvrDLL extends Library {
} finally {
libStream.close();
}
// 设置为可执行
tempLibFile.setExecutable(true);
tempLibFile.setReadable(true);
// JVM退出时删除临时文件
tempLibFile.deleteOnExit();
System.out.println("已提取库文件到: " + tempLibFile.getAbsolutePath());
return tempLibFile;
}
/**
* 直接调用C DLL的qvvr_fun函数
* void __stdcall qvvr_fun(void *data)
*/
void qvvr_fun(QvvrDataStruct data);
void ping();
/**
* 对应C语言的qvvr_data_struct结构体
*/
public static class QvvrDataStruct extends Structure {
// 输入数据
public float[] smp_va = new float[128 * 50 * 120]; // A相电压
public float[] smp_vb = new float[128 * 50 * 120]; // B相电压
public float[] smp_vb = new float[128 * 50 * 120]; // B相电压
public float[] smp_vc = new float[128 * 50 * 120]; // C相电压
public int smp_rate; // 采样频率
public int smp_len; // 数据长度
// 输出结果
public int evt_num; // 事件数量
public EventBuffer[] evt_buf = new EventBuffer[32]; // 事件缓冲区
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("smp_va", "smp_vb", "smp_vc", "smp_rate", "smp_len", "evt_num", "evt_buf");
}
public QvvrDataStruct() {
super();
// 初始化事件缓冲区
@@ -124,49 +128,49 @@ public interface QvvrDLL extends Library {
}
}
}
/**
* 事件缓冲区结构
*/
public static class EventBuffer extends Structure {
public int[] qvvr_cata_cause = new int[256];
public int[] qvvr_phasetype = new int[256];
public int[] qvvr_phasetype = new int[256];
public int[] qvvr_cata_type = new int[256];
public float hold_time_rms;
public float hold_time_dq;
public float POW_a;
public float POW_b;
public float POW_c;
public float Voltagechange_Va;
public float Voltagechange_Vb;
public float Voltagechange_Vc;
public int SEG_T_num;
public int[] SEG_T0_idx = new int[256];
public int[] SEG_T_idx = new int[256];
public int SEG_RMS_T_num;
public int[] SEG_RMS_T_idx = new int[256];
public int u_min_num;
public float[] ua_min = new float[256];
public float[] ub_min = new float[256];
public float[] ub_min = new float[256];
public float[] uc_min = new float[256];
public float[] u3_min = new float[256];
public int[] order_min_idx = new int[256];
public float[] angle_diff_ap = new float[256];
public float[] angle_diff_bp = new float[256];
public float[] angle_diff_cp = new float[256];
public float[] angle_diff_an = new float[256];
public float[] angle_diff_bn = new float[256];
public float[] angle_diff_cn = new float[256];
public float[] bph_max_value = new float[256];
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(

View File

@@ -0,0 +1,381 @@
package com.njcn.advance.responsibility.analysis;
import com.njcn.advance.responsibility.constant.HarmonicConstants;
import com.njcn.advance.responsibility.utils.MathUtils;
import org.apache.commons.math3.linear.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 典则相关分析类
* 实现典则相关系数的计算
*
* @author hongawen
* @version 1.0
*/
public class CanonicalCorrelationAnalysis {
private static final Logger logger = LoggerFactory.getLogger(CanonicalCorrelationAnalysis.class);
/**
* 计算典则相关系数
* 对应C代码中的TransCancor函数
*
* @param powerData 功率数据矩阵 [时间][节点]
* @param harmonicData 谐波数据向量
* @param windowSize 窗口大小
* @param nodeCount 节点数量
* @return 典则相关系数
*/
public static float computeCanonicalCorrelation(float[][] powerData, float[] harmonicData,
int windowSize, int nodeCount) {
logger.info("===== 开始典型相关分析 =====");
logger.info("输入参数: windowSize={}, nodeCount={}", windowSize, nodeCount);
try {
// 提取窗口数据
double[][] x = new double[windowSize][nodeCount];
double[] y = new double[windowSize];
// ===== 数据质量统计(只统计,不影响计算) =====
int nanCountPower = 0, infiniteCountPower = 0, zeroCountPower = 0;
int nanCountHarmonic = 0, infiniteCountHarmonic = 0, zeroCountHarmonic = 0;
double powerSum = 0, harmonicSum = 0;
double powerMin = Double.MAX_VALUE, powerMax = -Double.MAX_VALUE;
double harmonicMin = Double.MAX_VALUE, harmonicMax = -Double.MAX_VALUE;
for (int i = 0; i < windowSize; i++) {
for (int j = 0; j < nodeCount; j++) {
float val = powerData[i][j];
x[i][j] = val;
// 仅统计,不改变原逻辑
if (Float.isNaN(val)) {
nanCountPower++;
} else if (Float.isInfinite(val)) {
infiniteCountPower++;
} else if (val == 0.0f) {
zeroCountPower++;
} else {
powerSum += val;
powerMin = Math.min(powerMin, val);
powerMax = Math.max(powerMax, val);
}
}
float harmonicVal = harmonicData[i];
y[i] = harmonicVal;
// 仅统计,不改变原逻辑
if (Float.isNaN(harmonicVal)) {
nanCountHarmonic++;
} else if (Float.isInfinite(harmonicVal)) {
infiniteCountHarmonic++;
} else if (harmonicVal == 0.0f) {
zeroCountHarmonic++;
} else {
harmonicSum += harmonicVal;
harmonicMin = Math.min(harmonicMin, harmonicVal);
harmonicMax = Math.max(harmonicMax, harmonicVal);
}
}
// ===== 数据质量报告(只记录日志) =====
int totalPowerCount = windowSize * nodeCount;
int totalHarmonicCount = windowSize;
logger.info("功率数据质量分析:");
logger.info(" 总数据点: {}", totalPowerCount);
logger.info(" NaN数量: {} ({:.2f}%)", nanCountPower, nanCountPower * 100.0 / totalPowerCount);
logger.info(" 无穷大数量: {} ({:.2f}%)", infiniteCountPower, infiniteCountPower * 100.0 / totalPowerCount);
logger.info(" 零值数量: {} ({:.2f}%)", zeroCountPower, zeroCountPower * 100.0 / totalPowerCount);
logger.info(" 有效数据范围: [{}, {}]", powerMin == Double.MAX_VALUE ? "N/A" : powerMin,
powerMax == -Double.MAX_VALUE ? "N/A" : powerMax);
logger.info("谐波数据质量分析:");
logger.info(" 总数据点: {}", totalHarmonicCount);
logger.info(" NaN数量: {} ({:.2f}%)", nanCountHarmonic, nanCountHarmonic * 100.0 / totalHarmonicCount);
logger.info(" 无穷大数量: {} ({:.2f}%)", infiniteCountHarmonic, infiniteCountHarmonic * 100.0 / totalHarmonicCount);
logger.info(" 零值数量: {} ({:.2f}%)", zeroCountHarmonic, zeroCountHarmonic * 100.0 / totalHarmonicCount);
logger.info(" 有效数据范围: [{}, {}]", harmonicMin == Double.MAX_VALUE ? "N/A" : harmonicMin,
harmonicMax == -Double.MAX_VALUE ? "N/A" : harmonicMax);
// 只记录警告,不停止计算
if (nanCountPower > 0 || infiniteCountPower > 0) {
logger.warn("功率数据包含异常值NaN: {}, Infinite: {}", nanCountPower, infiniteCountPower);
}
if (nanCountHarmonic > 0 || infiniteCountHarmonic > 0) {
logger.warn("谐波数据包含异常值NaN: {}, Infinite: {}", nanCountHarmonic, infiniteCountHarmonic);
}
// 计算协方差矩阵 SXX
logger.info("===== 开始协方差计算 =====");
double[][] sxxMatrix = MathUtils.covarianceMatrix(x, windowSize, nodeCount);
// ===== SXX矩阵诊断只记录日志=====
double sxxTrace = 0;
double sxxFrobeniusNorm = 0;
boolean sxxHasNaN = false, sxxHasInfinite = false;
for (int i = 0; i < nodeCount; i++) {
sxxTrace += sxxMatrix[i][i];
for (int j = 0; j < nodeCount; j++) {
double val = sxxMatrix[i][j];
if (Double.isNaN(val)) {
sxxHasNaN = true;
}
if (Double.isInfinite(val)) {
sxxHasInfinite = true;
}
sxxFrobeniusNorm += val * val;
}
}
sxxFrobeniusNorm = Math.sqrt(sxxFrobeniusNorm);
logger.info("SXX矩阵诊断:");
logger.info(" 维度: {}x{}", nodeCount, nodeCount);
logger.info(" 迹(trace): {}", sxxTrace);
logger.info(" Frobenius范数: {}", sxxFrobeniusNorm);
logger.info(" 包含NaN: {}", sxxHasNaN);
logger.info(" 包含无穷大: {}", sxxHasInfinite);
logger.info(" 对角线元素: {}", java.util.Arrays.toString(
java.util.stream.IntStream.range(0, nodeCount)
.mapToDouble(i -> sxxMatrix[i][i])
.toArray()));
// 计算协方差 SYY
double syyMatrix = MathUtils.covariance(y, y, windowSize);
logger.info("SYY协方差: {}", syyMatrix);
if (Math.abs(syyMatrix) < HarmonicConstants.MIN_COVARIANCE) {
logger.warn("SYY过小 ({}), 调整为最小值: {}", syyMatrix, HarmonicConstants.MIN_COVARIANCE);
syyMatrix = HarmonicConstants.MIN_COVARIANCE;
}
// 计算协方差向量 SXY
double[] sxyVector = MathUtils.covarianceVector(x, y, windowSize, nodeCount);
// ===== SXY向量诊断只记录日志=====
double sxyNorm = 0;
boolean sxyHasNaN = false, sxyHasInfinite = false;
for (double val : sxyVector) {
if (Double.isNaN(val)) {
sxyHasNaN = true;
}
if (Double.isInfinite(val)) {
sxyHasInfinite = true;
}
sxyNorm += val * val;
}
sxyNorm = Math.sqrt(sxyNorm);
logger.info("SXY向量诊断:");
logger.info(" 长度: {}", sxyVector.length);
logger.info(" L2范数: {}", sxyNorm);
logger.info(" 包含NaN: {}", sxyHasNaN);
logger.info(" 包含无穷大: {}", sxyHasInfinite);
logger.info(" 向量值: {}", java.util.Arrays.toString(sxyVector));
// 使用Apache Commons Math进行矩阵运算
logger.info("===== 开始矩阵分解 =====");
RealMatrix sxx = new Array2DRowRealMatrix(sxxMatrix);
RealVector sxy = new ArrayRealVector(sxyVector);
// 计算 SXX^(-1)
logger.info("准备计算SXX逆矩阵...");
DecompositionSolver solver = new LUDecomposition(sxx).getSolver();
RealMatrix invSxx;
// 检查矩阵奇异性
double sxxDet = new LUDecomposition(sxx).getDeterminant();
logger.info("SXX矩阵行列式: {}", sxxDet);
if (Math.abs(sxxDet) < 1e-15) {
logger.warn("SXX矩阵几乎奇异 (det={})", sxxDet);
}
if (!solver.isNonSingular()) {
// 如果矩阵奇异,使用伪逆
logger.warn("SXX matrix is singular, using pseudo-inverse");
try {
SingularValueDecomposition svd = new SingularValueDecomposition(sxx);
invSxx = svd.getSolver().getInverse();
} catch (Exception svdException) {
logger.error("SVD pseudo-inverse failed, using regularized inverse", svdException);
// 添加正则化项
RealMatrix identity = MatrixUtils.createRealIdentityMatrix(sxx.getRowDimension());
RealMatrix regularized = sxx.add(identity.scalarMultiply(1e-10));
invSxx = new LUDecomposition(regularized).getSolver().getInverse();
}
} else {
invSxx = solver.getInverse();
}
// 计算 U = SXX^(-1) * SXY * (1/SYY) * SXY'
RealVector temp = invSxx.operate(sxy);
double scale = 1.0 / syyMatrix;
RealMatrix uMatrix = temp.outerProduct(sxy).scalarMultiply(scale);
// 计算特征值 - 添加数值稳定性处理
double maxEigenvalue = 0.0;
try {
// 首先检查矩阵是否有效
double[][] uMatrixData = uMatrix.getData();
boolean hasNaN = false;
boolean hasInfinite = false;
for (int i = 0; i < uMatrixData.length; i++) {
for (int j = 0; j < uMatrixData[i].length; j++) {
if (Double.isNaN(uMatrixData[i][j])) {
hasNaN = true;
}
if (Double.isInfinite(uMatrixData[i][j])) {
hasInfinite = true;
}
}
}
if (hasNaN || hasInfinite) {
logger.warn("U matrix contains NaN or Infinite values, returning 0");
return 0.0f;
}
// 检查矩阵条件数
SingularValueDecomposition svdCheck = new SingularValueDecomposition(uMatrix);
double conditionNumber = svdCheck.getConditionNumber();
if (conditionNumber > 1e12) {
logger.warn("U matrix is ill-conditioned (condition number: {}), using SVD approach", conditionNumber);
// 使用SVD方法获取最大奇异值的平方作为最大特征值
double[] singularValues = svdCheck.getSingularValues();
if (singularValues.length > 0) {
maxEigenvalue = singularValues[0] * singularValues[0];
}
} else {
// 正常的特征值分解
EigenDecomposition eigenDecomposition = new EigenDecomposition(uMatrix);
double[] eigenvalues = eigenDecomposition.getRealEigenvalues();
// 找最大特征值
for (double eigenvalue : eigenvalues) {
maxEigenvalue = Math.max(maxEigenvalue, Math.abs(eigenvalue));
}
}
} catch (Exception eigenException) {
logger.warn("EigenDecomposition failed, trying alternative approach: {}", eigenException.getMessage());
// 备用方案使用SVD方法
try {
SingularValueDecomposition svd = new SingularValueDecomposition(uMatrix);
double[] singularValues = svd.getSingularValues();
if (singularValues.length > 0) {
maxEigenvalue = singularValues[0] * singularValues[0];
}
} catch (Exception svdException) {
logger.error("Both EigenDecomposition and SVD failed, returning 0", svdException);
return 0.0f;
}
}
// 典则相关系数是最大特征值的平方根
double canonicalCorr = Math.sqrt(Math.abs(maxEigenvalue));
// 限制在[0,1]范围内
if (canonicalCorr > 1.0) {
canonicalCorr = 1.0;
}
logger.info("===== 典型相关分析计算完成 =====");
logger.info("最大特征值: {}", maxEigenvalue);
logger.info("典型相关系数: {}", canonicalCorr);
logger.info("是否被截断到1.0: {}", canonicalCorr >= 1.0);
return (float) canonicalCorr;
} catch (Exception e) {
logger.error("Error computing canonical correlation", e);
logger.error("异常详情: {}", e.getMessage());
logger.error("异常类型: {}", e.getClass().getSimpleName());
return 0.0f;
}
}
/**
* 滑动窗口计算典则相关系数序列
* 对应C代码中的SlideCanCor函数
*
* @param powerData 功率数据矩阵 [时间][节点]
* @param harmonicData 谐波数据向量
* @param windowSize 窗口大小
* @param nodeCount 节点数量
* @param dataLength 数据总长度
* @return 典则相关系数序列
*/
public static float[] slidingCanonicalCorrelation(float[][] powerData, float[] harmonicData,
int windowSize, int nodeCount, int dataLength) {
int slideLength = dataLength - windowSize;
if (slideLength <= 0) {
throw new IllegalArgumentException("Data length must be greater than window size");
}
float[] slideCanCor = new float[slideLength];
logger.info("Starting sliding canonical correlation analysis, slide length: {}", slideLength);
for (int i = 0; i < slideLength; i++) {
// 提取窗口数据
float[][] windowPower = new float[windowSize][nodeCount];
float[] windowHarmonic = new float[windowSize];
for (int j = 0; j < windowSize; j++) {
System.arraycopy(powerData[i + j], 0, windowPower[j], 0, nodeCount);
windowHarmonic[j] = harmonicData[i + j];
}
// 计算当前窗口的典则相关系数
slideCanCor[i] = computeCanonicalCorrelation(windowPower, windowHarmonic,
windowSize, nodeCount);
if (i % 10 == 0) {
logger.debug("Processed window {}/{}", i, slideLength);
}
}
logger.info("Sliding canonical correlation analysis completed");
return slideCanCor;
}
/**
* 计算包含/不包含背景的动态相关系数
* 对应C代码中的SlideCor函数
*
* @param powerData 功率数据(单个节点)
* @param harmonicData 谐波数据
* @param slideCanCor 滑动典则相关系数
* @param windowSize 窗口大小
* @return 动态相关系数序列
*/
public static float[] slidingCorrelation(float[] powerData, float[] harmonicData,
float[] slideCanCor, int windowSize) {
int slideLength = slideCanCor.length;
float[] slideCor = new float[slideLength];
for (int i = 0; i < slideLength; i++) {
float[] tempPower = new float[windowSize];
float[] tempHarmonic = new float[windowSize];
for (int j = 0; j < windowSize; j++) {
tempPower[j] = powerData[i + j];
tempHarmonic[j] = harmonicData[i + j] * slideCanCor[i];
}
slideCor[i] = MathUtils.pearsonCorrelation(tempHarmonic, tempPower, windowSize);
}
return slideCor;
}
}

View File

@@ -0,0 +1,424 @@
package com.njcn.advance.responsibility.calculator;
import com.njcn.advance.responsibility.analysis.CanonicalCorrelationAnalysis;
import com.njcn.advance.responsibility.constant.CalculationMode;
import com.njcn.advance.responsibility.constant.CalculationStatus;
import com.njcn.advance.responsibility.constant.HarmonicConstants;
import com.njcn.advance.responsibility.model.HarmonicData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 谐波责任计算主引擎
* 严格对应C代码中的harm_res系列函数
*
* @author hongawen
* @version 2.0 - 修复版本严格对照C代码实现
*/
public class HarmonicCalculationEngine {
private static final Logger logger = LoggerFactory.getLogger(HarmonicCalculationEngine.class);
// 对应C代码中的全局变量
private int P; // 节点数 p_node
private int TL; // 功率数据长度 p_num
private int LL; // 谐波数据长度 harm_num
private int JIANGE; // 数据间隔比例
private int width; // 窗口大小
private float XIANE; // 谐波门槛
/**
* 主计算入口
* 对应C代码中的harm_res函数
*
* @param data 谐波数据对象
* @return 计算是否成功
*/
public boolean calculate(HarmonicData data) {
logger.info("Starting harmonic calculation, mode: {}", data.getCalculationMode());
try {
if (data.getCalculationMode() == CalculationMode.FULL_CALCULATION) {
return fullCalculation(data);
} else {
return partialCalculation(data);
}
} catch (Exception e) {
logger.error("Calculation failed with exception: " + e.getMessage(), e);
e.printStackTrace();
data.setCalculationStatus(CalculationStatus.FAILED);
return false;
}
}
/**
* 完整计算模式
* 严格对应C代码中的harm_res_all函数
*
* @param data 谐波数据对象
* @return 计算是否成功
*/
private boolean fullCalculation(HarmonicData data) {
logger.info("Executing full calculation mode");
// 1. 数据初始化 - 对应 data_init_all()
if (!initializeFullCalculationData(data)) {
logger.error("Data initialization failed");
data.setCalculationStatus(CalculationStatus.FAILED);
return false;
}
// 2. 创建工作数组 - 对应C代码行536-540
float[][] a = new float[TL][P]; // 功率数据副本
float[] b = new float[LL]; // 谐波数据副本
float[] u = new float[TL]; // 对齐后的谐波数据
// 3. 复制数据 - 对应C代码行542-552
for (int i = 0; i < TL; i++) {
for (int j = 0; j < P; j++) {
a[i][j] = data.getPowerData()[i][j];
}
}
for (int i = 0; i < LL; i++) {
b[i] = data.getHarmonicData()[i];
}
// 4. 数据对齐处理 - 严格对应C代码行554-562
// 注意C代码是原地修改数组b
for (int i = 0; i < LL; i += JIANGE) {
float tempt = 0.0f;
for (int j = 0; j < JIANGE; j++) {
tempt += b[i + j];
}
b[i] = tempt / JIANGE; // 覆盖原位置
}
// 5. 构建Udata - 严格对应C代码行570-580
// 注意:使用 i*JIANGE 索引
for (int i = 0; i < TL; i++) {
u[i] = b[i * JIANGE]; // 关键:使用 i*JIANGE 索引
}
int slcorlength = TL - width;
// 6. 计算滑动典则相关系数 - 对应C代码行584
logger.info("Computing sliding canonical correlation");
float[] cancorrelation = CanonicalCorrelationAnalysis.slidingCanonicalCorrelation(
a, u, width, P, TL
);
// 7. 保存典则相关系数 - 对应C代码行592-601
float[] Core = new float[slcorlength];
float[] BjCore = new float[slcorlength];
for (int i = 0; i < slcorlength; i++) {
Core[i] = cancorrelation[i];
BjCore[i] = 1 - cancorrelation[i];
}
data.setCanonicalCorrelation(Core);
data.setBackgroundCanonicalCorr(BjCore);
// 8. 计算动态相关系数矩阵 - 对应C代码行605-635
logger.info("Computing correlation matrix");
float[][] simCor = new float[slcorlength][P];
// 对应C代码行618-632对每个节点计算动态相关系数
for (int i = 0; i < P; i++) {
// 提取第i个节点的功率数据
float[] xe = new float[TL];
for (int m = 0; m < TL; m++) {
xe[m] = a[m][i]; // 对应 Pdata.block(0, i, TL, 1)
}
// 计算该节点的滑动相关系数
float[] slidecor = CanonicalCorrelationAnalysis.slidingCorrelation(
xe, u, cancorrelation, width
);
// 存储结果
for (int j = 0; j < slcorlength; j++) {
simCor[j][i] = slidecor[j];
}
}
data.setCorrelationData(simCor);
// 9. 计算EK值 - 对应C代码行642-654
logger.info("Computing EK values");
float[][] EKdata = ResponsibilityCalculator.computeEK(
simCor, a, width, P, TL
);
// 10. 计算FK值 - 对应C代码行660-673
logger.info("Computing FK values");
float[][] FKdata = ResponsibilityCalculator.computeFK(
EKdata, width, P, TL
);
data.setFkData(FKdata);
// 11. 计算HK值 - 对应C代码行678-691
logger.info("Computing HK values");
float[][] HKdata = ResponsibilityCalculator.computeHK(
BjCore, EKdata, width, P, TL
);
data.setHkData(HKdata);
// 12. 设置结果数量 - 对应C代码行693
data.setResponsibilityDataCount(slcorlength);
// 13. 统计超限时段的责任 - 对应C代码行696-724
logger.info("Computing responsibility sums");
// 重要修正C代码的SumHK函数中虽然Udata长度是TL但是循环只遍历前slg(=TL-width)个元素
// 所以我们需要传入完整的u数组长度TL让sumResponsibility内部处理
// 对应C代码VectorXd Udata(TL); 以及 SumHK函数调用
// 统计HK责任包含背景- 对应C代码行698-710
// 注意传入完整的u数组TL长度而不是截取的数组
float[] sumHK = ResponsibilityCalculator.sumResponsibility(
HKdata, u, XIANE, width, P + 1, TL
);
data.setSumHKData(sumHK);
// 统计FK责任不包含背景- 对应C代码行712-724
// 同样传入完整的u数组和TL参数
float[] sumFK = ResponsibilityCalculator.sumResponsibility(
FKdata, u, XIANE, width, P, TL
);
data.setSumFKData(sumFK);
// 14. 标记计算成功 - 对应C代码行739
data.setCalculationStatus(CalculationStatus.CALCULATED);
logger.info("Full calculation completed successfully");
return true;
}
/**
* 初始化完整计算数据
* 对应C代码中的data_init_all函数
*/
private boolean initializeFullCalculationData(HarmonicData data) {
// 设置全局变量 - 对应C代码行478-483
P = data.getPowerNodeCount();
TL = data.getPowerCount();
LL = data.getHarmonicCount();
// 对应C代码第481行JIANGE = pq_buf.harm_num/pq_buf.p_num;
// 重要修正JIANGE应该是 谐波数量/功率点数,不是谐波数量/节点数
JIANGE = LL / TL; // 这个是正确的harm_num / p_num (其中p_num是功率点数)
width = data.getWindowSize();
XIANE = data.getHarmonicThreshold();
// 验证数据 - 对应C代码行485-504
if (JIANGE * TL != LL || JIANGE < 1) {
logger.error("Data length mismatch: JIANGE({}) * TL({}) != LL({})",
JIANGE, TL, LL);
return false;
}
if (width < HarmonicConstants.MIN_WIN_LEN || width > HarmonicConstants.MAX_WIN_LEN) {
logger.error("Invalid window size: {}", width);
return false;
}
if (TL < 2 * width) {
logger.error("Power data length {} is too short for window size {}", TL, width);
return false;
}
if (P > HarmonicConstants.MAX_P_NODE || TL > HarmonicConstants.MAX_P_NUM ||
LL > HarmonicConstants.MAX_HARM_NUM) {
logger.error("Data size exceeds limits");
return false;
}
return true;
}
/**
* 部分重算模式
* 对应C代码中的harm_res_part函数
*
* @param data 谐波数据对象
* @return 计算是否成功
*/
private boolean partialCalculation(HarmonicData data) {
logger.info("Executing partial calculation mode");
// 1. 数据初始化 - 对应 data_init_part()
if (!initializePartialCalculationData(data)) {
logger.error("Data initialization failed for partial calculation");
data.setCalculationStatus(CalculationStatus.FAILED);
return false;
}
// 2. 准备Udata - 对应C代码行816-818
// C代码VectorXd Udata(TL); 并从pq_buf.harm_data复制TL个元素
int res_num = data.getResponsibilityDataCount();
// 验证责任数据行数
if (res_num != TL - width) {
logger.warn("责任数据行数({})与期望值(TL-width={})不匹配", res_num, TL - width);
res_num = TL - width; // 使用正确的值
}
// 重要修正与C代码保持一致Udata长度应该是TL而不是res_num
// C代码VectorXd Udata(TL);
float[] Udata = new float[TL];
// 从harm_data复制TL个元素到Udata
// C代码for (int j = 0; j < TL; j++) Udata[j] = pq_buf.harm_data[j];
if (data.getHarmonicData().length < TL) {
logger.warn("谐波数据长度({})小于TL({}), 将补零",
data.getHarmonicData().length, TL);
System.arraycopy(data.getHarmonicData(), 0, Udata, 0, data.getHarmonicData().length);
// 剩余部分自动补零
} else {
System.arraycopy(data.getHarmonicData(), 0, Udata, 0, TL);
}
logger.debug("准备Udata完成: 长度={} (对应C代码TL), 责任数据行数={}", Udata.length, res_num);
// 3. 统计HK责任 - 对应C代码行806-830
logger.info("Recalculating HK responsibility sums");
// 对应C代码第808-814行创建新的HKdata矩阵只包含RES_NUM行
// C代码MatrixXd HKdata(RES_NUM, (P + 1));
// 添加数据验证
if (data.getHkData() == null || data.getHkData().length == 0) {
logger.error("HK数据为空或长度为0");
data.setCalculationStatus(CalculationStatus.FAILED);
return false;
}
// 重要C代码创建了新的RES_NUM行的HKdata从原始数据复制前RES_NUM行
// 对应C代码第808-814行
float[][] HKdataForCalc = new float[res_num][P + 1];
int copyRows = Math.min(res_num, data.getHkData().length);
logger.debug("创建用于计算的HK数据矩阵: {}x{}, 从原始数据复制{}行",
res_num, P + 1, copyRows);
for (int i = 0; i < copyRows; i++) {
for (int j = 0; j < P + 1; j++) {
if (j < data.getHkData()[i].length) {
HKdataForCalc[i][j] = data.getHkData()[i][j];
}
}
}
logger.debug("调用HK sumResponsibility参数: HKdata[{}x{}], Udata[{}], TL={}, width={}",
HKdataForCalc.length, HKdataForCalc.length > 0 ? HKdataForCalc[0].length : 0,
Udata.length, TL, width);
try {
// 对应C代码第819行arrHKsum = SumHK(HKdata, Udata, wdith, colK, TL);
float[] sumHK = ResponsibilityCalculator.sumResponsibility(
HKdataForCalc, // 使用新创建的RES_NUM行的HK数据
Udata, // 长度为TL的数组
XIANE,
width,
P + 1,
TL // 传入TL参数
);
data.setSumHKData(sumHK);
logger.debug("HK责任计算完成结果长度: {}", sumHK != null ? sumHK.length : "null");
} catch (Exception e) {
logger.error("HK责任计算失败: " + e.getMessage(), e);
throw e;
}
// 4. 统计FK责任 - 对应C代码行839-851
logger.info("Recalculating FK responsibility sums");
// 对应C代码虽然没有显式创建新的FKdata但逻辑相同
// 添加数据验证
if (data.getFkData() == null || data.getFkData().length == 0) {
logger.error("FK数据为空或长度为0");
data.setCalculationStatus(CalculationStatus.FAILED);
return false;
}
// 创建用于计算的FK数据矩阵RES_NUM行
float[][] FKdataForCalc = new float[res_num][P];
int copyRowsFK = Math.min(res_num, data.getFkData().length);
logger.debug("创建用于计算的FK数据矩阵: {}x{}, 从原始数据复制{}行",
res_num, P, copyRowsFK);
for (int i = 0; i < copyRowsFK; i++) {
for (int j = 0; j < P; j++) {
if (j < data.getFkData()[i].length) {
FKdataForCalc[i][j] = data.getFkData()[i][j];
}
}
}
logger.debug("调用FK sumResponsibility参数: FKdata[{}x{}], Udata[{}], TL={}, width={}",
FKdataForCalc.length, FKdataForCalc.length > 0 ? FKdataForCalc[0].length : 0,
Udata.length, TL, width);
try {
// 对应C代码第840行arrHKsum = SumHK(FKdata, Udata, wdith, colK, TL);
float[] sumFK = ResponsibilityCalculator.sumResponsibility(
FKdataForCalc, // 使用新创建的RES_NUM行的FK数据
Udata, // 使用相同的Udata(长度TL)
XIANE,
width,
P,
TL // 传入TL参数
);
data.setSumFKData(sumFK);
logger.debug("FK责任计算完成结果长度: {}", sumFK != null ? sumFK.length : "null");
} catch (Exception e) {
logger.error("FK责任计算失败: " + e.getMessage(), e);
throw e;
}
// 5. 标记计算成功 - 对应C代码行858
data.setCalculationStatus(CalculationStatus.CALCULATED);
logger.info("Partial calculation completed successfully");
return true;
}
/**
* 初始化部分计算数据
* 对应C代码中的data_init_part函数
*/
private boolean initializePartialCalculationData(HarmonicData data) {
// 设置变量 - 对应C代码行762-766
int RES_NUM = data.getResponsibilityDataCount();
P = data.getPowerNodeCount();
TL = data.getWindowSize() + RES_NUM;
width = data.getWindowSize();
XIANE = data.getHarmonicThreshold();
// 验证数据 - 对应C代码行756-778
if ((RES_NUM + width) != data.getHarmonicCount()) {
logger.error("Data length mismatch: res_num({}) + win({}) != harm_num({})",
RES_NUM, width, data.getHarmonicCount());
return false;
}
if (width < HarmonicConstants.MIN_WIN_LEN || width > HarmonicConstants.MAX_WIN_LEN) {
logger.error("Invalid window size: {}", width);
return false;
}
if (P > HarmonicConstants.MAX_P_NODE || TL > HarmonicConstants.MAX_P_NUM) {
logger.error("Data size exceeds limits");
return false;
}
// 验证FK和HK数据存在
if (data.getFkData() == null || data.getHkData() == null) {
logger.error("FK or HK data is null");
return false;
}
return true;
}
}

View File

@@ -0,0 +1,429 @@
package com.njcn.advance.responsibility.calculator;
import com.njcn.advance.responsibility.analysis.CanonicalCorrelationAnalysis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 责任指标计算类
* 计算谐波责任的各项指标
* 严格对应C代码实现
*
* @author hongawen
* @version 2.0 - 修复版本严格对照C代码实现
*/
public class ResponsibilityCalculator {
private static final Logger logger = LoggerFactory.getLogger(ResponsibilityCalculator.class);
/**
* 计算EK值动态责任指标
* 严格对应C代码中的DyEKCom函数行300-357
*
* @param correlationData 动态相关系数矩阵 [时间][节点]
* @param powerData 功率数据矩阵 [时间][节点]
* @param windowSize 窗口大小
* @param nodeCount 节点数量
* @param dataLength 数据长度
* @return EK值矩阵
*/
public static float[][] computeEK(float[][] correlationData, float[][] powerData,
int windowSize, int nodeCount, int dataLength) {
int slideLength = dataLength - windowSize;
float[][] ekData = new float[slideLength][nodeCount];
float[][] akData = new float[slideLength][nodeCount];
logger.info("Computing EK values, slide length: {}", slideLength);
// 计算AK值 - 对应C代码行307-319
for (int i = 0; i < slideLength; i++) {
float sumPower = 0;
// 计算功率总和 - 对应C代码行309-313
for (int j = 0; j < nodeCount; j++) {
sumPower += powerData[i][j]; // 注意这里用的是powerData[i][j]
}
// 计算AK值 - 对应C代码行314-318
for (int j = 0; j < nodeCount; j++) {
if (sumPower > 0) {
akData[i][j] = correlationData[i][j] * (powerData[i][j] / sumPower);
} else {
akData[i][j] = 0;
}
}
}
// 归一化处理得到EK值 - 对应C代码行320-342
for (int i = 0; i < slideLength; i++) {
// 重要C代码初始化为0而不是Float.MIN_VALUE/MAX_VALUE
// 对应C代码行322-323
float maxValue = 0;
float minValue = 0;
// 找最大最小值 - 对应C代码行322-334
for (int j = 0; j < nodeCount; j++) {
if (akData[i][j] > maxValue) {
maxValue = akData[i][j];
}
if (akData[i][j] < minValue) {
minValue = akData[i][j];
}
}
float range = maxValue - minValue;
// 归一化 - 对应C代码行338-341
for (int j = 0; j < nodeCount; j++) {
if (Math.abs(range) > 1e-10) {
ekData[i][j] = (akData[i][j] - minValue) / range;
} else {
ekData[i][j] = 0;
}
}
}
logger.info("EK computation completed");
return ekData;
}
/**
* 计算FK值不包含背景的责任指标
* 严格对应C代码中的DyFKCom函数行358-389
*
* @param ekData EK值矩阵
* @param windowSize 窗口大小
* @param nodeCount 节点数量
* @param dataLength 数据长度
* @return FK值矩阵
*/
public static float[][] computeFK(float[][] ekData, int windowSize,
int nodeCount, int dataLength) {
int slideLength = dataLength - windowSize;
float[][] fkData = new float[slideLength][nodeCount];
logger.info("Computing FK values");
// 对应C代码行364-376
for (int i = 0; i < slideLength; i++) {
float sumEK = 0;
// 计算EK总和 - 对应C代码行366-370
for (int j = 0; j < nodeCount; j++) {
sumEK += ekData[i][j];
}
// 计算FK值归一化- 对应C代码行372-375
for (int j = 0; j < nodeCount; j++) {
if (sumEK > 0) {
fkData[i][j] = ekData[i][j] / sumEK;
} else {
fkData[i][j] = 0;
}
}
}
logger.info("FK computation completed");
return fkData;
}
/**
* 计算HK值包含背景的责任指标
* 严格对应C代码中的DyHKCom函数行390-429
*
* @param backgroundCanCor 背景典则相关系数1-典则相关系数)
* @param ekData EK值矩阵
* @param windowSize 窗口大小
* @param nodeCount 节点数量
* @param dataLength 数据长度
* @return HK值矩阵
*/
public static float[][] computeHK(float[] backgroundCanCor, float[][] ekData,
int windowSize, int nodeCount, int dataLength) {
int slideLength = dataLength - windowSize;
float[][] hkData = new float[slideLength][nodeCount + 1];
float[][] newEK = new float[slideLength][nodeCount + 1];
logger.info("Computing HK values");
// 构建包含背景的EK矩阵 - 对应C代码行396-403
for (int i = 0; i < slideLength; i++) {
// 复制原有EK值
for (int j = 0; j < nodeCount; j++) {
newEK[i][j] = ekData[i][j];
}
// 添加背景值
newEK[i][nodeCount] = backgroundCanCor[i];
}
// 计算HK值 - 对应C代码行405-416
for (int i = 0; i < slideLength; i++) {
float sumEK = 0;
// 计算总和 - 对应C代码行407-411
for (int j = 0; j < nodeCount + 1; j++) {
sumEK += newEK[i][j];
}
// 归一化得到HK值 - 对应C代码行412-415
for (int j = 0; j < nodeCount + 1; j++) {
if (sumEK > 0) {
hkData[i][j] = newEK[i][j] / sumEK;
} else {
hkData[i][j] = 0;
}
}
}
logger.info("HK computation completed");
return hkData;
}
/**
* 计算超限时段的责任总和
* 严格对应C代码中的SumHK函数行431-461
*
* @param responsibilityData 责任数据矩阵FK或HK[时间][节点]
* @param harmonicData 谐波数据Udata - 长度为TL
* @param threshold 谐波门槛XIANE
* @param windowSize 窗口大小
* @param columnCount 列数(节点数或节点数+1
* @param tl_num 对应C代码的TL参数总数据点数
* @return 各节点的责任总和百分比
*/
public static float[] sumResponsibility(float[][] responsibilityData, float[] harmonicData,
float threshold, int windowSize, int columnCount, int tl_num) {
// 对应C代码int slg = tl_num - width;
int slideLength = tl_num - windowSize; // 使用传入的tl_num计算而不是从responsibilityData.length推断
float[] sumData = new float[columnCount]; // 对应C代码中的 arrHKsum
double[] HKSum = new double[columnCount]; // 对应C代码中的 VectorXd HKSum - 使用double精度
int exceedCount = 0; // 对应C代码中的 coutt
// ===== 添加详细调试日志 =====
logger.info("======= 开始 sumResponsibility 计算 =======");
logger.info("输入参数:");
logger.info(" threshold(阈值): {}", threshold);
logger.info(" windowSize(窗口大小): {}", windowSize);
logger.info(" columnCount(列数): {}", columnCount);
logger.info(" tl_num(总数据长度): {}", tl_num);
logger.info(" slideLength(滑动长度): {}", slideLength);
logger.info(" responsibilityData维度: {}x{}",
responsibilityData != null ? responsibilityData.length : "null",
responsibilityData != null && responsibilityData.length > 0 ? responsibilityData[0].length : "null");
logger.info(" harmonicData长度: {}", harmonicData != null ? harmonicData.length : "null");
// 数据验证
if (harmonicData == null) {
logger.error("错误: harmonicData为null!");
throw new NullPointerException("harmonicData不能为null");
}
if (responsibilityData == null) {
logger.error("错误: responsibilityData为null!");
throw new NullPointerException("responsibilityData不能为null");
}
// 关键验证:检查数组长度是否充足
// C代码中Udata长度是TL循环遍历slg=TL-width个元素
logger.info("数据验证: slideLength={}, harmonicData.length={}, responsibilityData.length={}",
slideLength, harmonicData.length, responsibilityData.length);
if (harmonicData.length < slideLength) {
logger.error("!!!谐波数据长度不足!!!");
logger.error("需要访问harmonicData[0]到harmonicData[{}], 但数组长度只有{}",
slideLength - 1, harmonicData.length);
throw new IllegalArgumentException(
String.format("谐波数据长度不足: 需要%d, 实际%d", slideLength, harmonicData.length));
}
if (responsibilityData.length < slideLength) {
logger.error("!!!责任数据行数不足!!!");
logger.error("需要访问responsibilityData[0]到responsibilityData[{}], 但数组长度只有{}",
slideLength - 1, responsibilityData.length);
throw new IllegalArgumentException(
String.format("责任数据行数不足: 需要%d, 实际%d", slideLength, responsibilityData.length));
}
// ===== 添加数据分布统计 =====
logger.info("谐波数据分析:");
float harmonicMin = Float.MAX_VALUE, harmonicMax = Float.MIN_VALUE;
double harmonicSum = 0;
int preliminaryExceedCount = 0;
for (int i = 0; i < Math.min(slideLength, harmonicData.length); i++) {
float val = harmonicData[i];
harmonicMin = Math.min(harmonicMin, val);
harmonicMax = Math.max(harmonicMax, val);
harmonicSum += val;
if (val > threshold) {
preliminaryExceedCount++;
}
}
double harmonicAvg = harmonicSum / Math.min(slideLength, harmonicData.length);
logger.info(" 谐波数据范围: [{}, {}]", harmonicMin, harmonicMax);
logger.info(" 谐波数据平均值: {}", harmonicAvg);
logger.info(" 设定阈值: {}", threshold);
logger.info(" 初步统计超限个数: {}/{} ({:.2f}%)",
preliminaryExceedCount, Math.min(slideLength, harmonicData.length),
preliminaryExceedCount * 100.0 / Math.min(slideLength, harmonicData.length));
// ===== 责任数据分析 =====
logger.info("责任数据分析(检查前5行的归一化情况):");
for (int i = 0; i < Math.min(5, responsibilityData.length); i++) {
float rowSum = 0;
for (int j = 0; j < responsibilityData[i].length; j++) {
rowSum += responsibilityData[i][j];
}
logger.info(" 第{}行和: {} (期望值: 1.0, 偏差: {})", i, rowSum, Math.abs(rowSum - 1.0f));
}
// 统计超限时段的责任 - 对应C代码行437-449
// 重要C代码中有一个设计缺陷coutt在每个j循环中被重置
// 但最后计算百分比时使用的是最后一次j循环的coutt值
// 为了严格保持一致,我们也要复现这个逻辑
logger.info("===== 开始循环计算每列的累加值 =====");
int[] exceedCountPerColumn = new int[columnCount]; // 记录每列的超限次数,用于调试
for (int j = 0; j < columnCount; j++) {
HKSum[j] = 0;
exceedCount = 0; // 对应C代码行440: coutt = 0;
logger.info("开始计算第{}列 (共{}列)", j, columnCount);
double columnSum = 0; // 用于调试
int columnExceedCount = 0; // 用于调试
for (int i = 0; i < slideLength; i++) {
// 添加越界检查
if (i >= harmonicData.length) {
logger.error("!!!数组越界!!! 尝试访问harmonicData[{}], 但数组长度只有{}",
i, harmonicData.length);
logger.error("发生在: j={}, i={}", j, i);
throw new ArrayIndexOutOfBoundsException(
String.format("访问harmonicData[%d]越界, 数组长度=%d", i, harmonicData.length));
}
// 对应C代码行443-447
if (harmonicData[i] > threshold) {
double currentResponsibility = responsibilityData[i][j];
HKSum[j] += currentResponsibility; // 对应C代码行445
exceedCount++; // 对应C代码行446
columnSum += currentResponsibility;
columnExceedCount++;
// 只打印前几个超限情况的详细信息
if (columnExceedCount <= 3) {
logger.info(" 时刻i={}: 谐波值={} > 阈值={}, 责任值={}, 累加到{}",
i, harmonicData[i], threshold, currentResponsibility, HKSum[j]);
}
}
}
exceedCountPerColumn[j] = columnExceedCount;
logger.info("第{}列计算完成: 累加值={}, 超限次数={}", j, HKSum[j], columnExceedCount);
}
// 注意这里exceedCount保留的是最后一列j=columnCount-1的超限次数
// 这与C代码的行为一致
logger.info("===== 循环计算完成 =====");
logger.info("最终exceedCount={} (来自最后一列的计算)", exceedCount);
logger.info("各列超限次数对比: {}", java.util.Arrays.toString(exceedCountPerColumn));
logger.info("各列累加值: {}", java.util.Arrays.toString(HKSum));
// 计算平均责任百分比 - 对应C代码行453-459
logger.info("===== 开始计算最终百分比 =====");
for (int i = 0; i < columnCount; i++) {
sumData[i] = 0; // 对应C代码行454
}
double totalPercentage = 0; // 用于统计总和
for (int i = 0; i < columnCount; i++) {
if (exceedCount > 0) {
// 对应C代码行458: arrHKsum[i] = 100 * (HKSum(i)/coutt);
// 使用double进行计算然后转换为float
double percentage = 100.0 * (HKSum[i] / (double)exceedCount);
sumData[i] = (float)percentage;
totalPercentage += percentage;
logger.info("节点{}: 累加值={}, 除以超限次数={}, 百分比={}%",
i, HKSum[i], exceedCount, percentage);
} else {
logger.warn("节点{}: 超限次数为0百分比设为0", i);
}
}
logger.info("===== 计算结果汇总 =====");
logger.info("使用的超限次数(分母): {}", exceedCount);
logger.info("各节点百分比: {}", java.util.Arrays.toString(sumData));
logger.info("百分比总和: {}% (期望100%)", totalPercentage);
logger.info("偏差: {}%", Math.abs(totalPercentage - 100.0));
if (Math.abs(totalPercentage - 100.0) > 1.0) {
logger.warn("!!!注意!!! 百分比总和偏离100%超过1%,可能存在问题");
}
logger.info("======= sumResponsibility 计算完成 =======");
return sumData;
}
/**
* 计算超限时段的责任总和(兼容版本)
* 为了向后兼容保留不带tl_num参数的版本
*
* @param responsibilityData 责任数据矩阵FK或HK[时间][节点]
* @param harmonicData 谐波数据Udata
* @param threshold 谐波门槛XIANE
* @param windowSize 窗口大小
* @param columnCount 列数(节点数或节点数+1
* @return 各节点的责任总和百分比
*/
public static float[] sumResponsibility(float[][] responsibilityData, float[] harmonicData,
float threshold, int windowSize, int columnCount) {
// 如果没有提供tl_num从数据推断
int tl_num = responsibilityData.length + windowSize;
return sumResponsibility(responsibilityData, harmonicData, threshold, windowSize, columnCount, tl_num);
}
/**
* 计算所有节点的动态相关系数矩阵
* 这个函数在主引擎中已经内联实现,这里保留作为辅助方法
*
* @param powerData 功率数据矩阵
* @param harmonicData 谐波数据
* @param canonicalCorr 典则相关系数序列
* @param windowSize 窗口大小
* @param nodeCount 节点数量
* @return 动态相关系数矩阵
*/
public static float[][] computeCorrelationMatrix(float[][] powerData, float[] harmonicData,
float[] canonicalCorr, int windowSize,
int nodeCount) {
int slideLength = canonicalCorr.length;
float[][] correlationMatrix = new float[slideLength][nodeCount];
logger.info("Computing correlation matrix for all nodes");
for (int nodeIdx = 0; nodeIdx < nodeCount; nodeIdx++) {
// 提取单个节点的功率数据
float[] nodePower = new float[powerData.length];
for (int i = 0; i < powerData.length; i++) {
nodePower[i] = powerData[i][nodeIdx];
}
// 计算该节点的动态相关系数
float[] nodeCorr = CanonicalCorrelationAnalysis
.slidingCorrelation(nodePower, harmonicData, canonicalCorr, windowSize);
// 存储结果
for (int i = 0; i < slideLength; i++) {
correlationMatrix[i][nodeIdx] = nodeCorr[i];
}
}
logger.info("Correlation matrix computation completed");
return correlationMatrix;
}
}

View File

@@ -0,0 +1,46 @@
package com.njcn.advance.responsibility.constant;
/**
* 计算模式枚举
*
* @author hongawen
* @version 1.0
*/
public enum CalculationMode {
/**
* 完整计算模式
* 使用电压和功率数据计算相关系数和责任
*/
FULL_CALCULATION(0, "完整计算模式"),
/**
* 部分重算模式
* 使用已有的动态相关系数计算责任
*/
PARTIAL_RECALCULATION(1, "部分重算模式");
private final int code;
private final String description;
CalculationMode(int code, String description) {
this.code = code;
this.description = description;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public static CalculationMode fromCode(int code) {
for (CalculationMode mode : values()) {
if (mode.code == code) {
return mode;
}
}
throw new IllegalArgumentException("Invalid calculation mode code: " + code);
}
}

View File

@@ -0,0 +1,49 @@
package com.njcn.advance.responsibility.constant;
/**
* 计算状态枚举
*
* @author hongawen
* @version 1.0
*/
public enum CalculationStatus {
/**
* 未计算
*/
NOT_CALCULATED(0, "未计算"),
/**
* 计算完成
*/
CALCULATED(1, "计算完成"),
/**
* 计算失败
*/
FAILED(-1, "计算失败");
private final int code;
private final String description;
CalculationStatus(int code, String description) {
this.code = code;
this.description = description;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public static CalculationStatus fromCode(int code) {
for (CalculationStatus status : values()) {
if (status.code == code) {
return status;
}
}
return NOT_CALCULATED;
}
}

View File

@@ -0,0 +1,60 @@
package com.njcn.advance.responsibility.constant;
/**
* 谐波责任量化系统常量定义
*
* @author hongawen
* @version 1.0
*/
public final class HarmonicConstants {
private HarmonicConstants() {
// 防止实例化
}
/**
* 最大谐波数据个数 (1440*100)
* 按一分钟间隔100天处理
*/
public static final int MAX_HARM_NUM = 144000;
/**
* 最大功率数据个数 (96*100)
* 按15分钟间隔100天处理
*/
public static final int MAX_P_NUM = 9600;
/**
* 最大功率节点个数
* 按200个限制
*/
public static final int MAX_P_NODE = 200;
/**
* 最大数据窗长度 (96*10)
* 按15分钟算10天
*/
public static final int MAX_WIN_LEN = 960;
/**
* 最小数据窗长度
* 按15分钟算一小时
*/
public static final int MIN_WIN_LEN = 4;
/**
* 默认数据窗大小
* 一天的数据量15分钟间隔
*/
public static final int DEFAULT_WINDOW_SIZE = 96;
/**
* 数值计算精度阈值
*/
public static final double EPSILON = 1e-10;
/**
* 协方差计算最小值(避免除零)
*/
public static final double MIN_COVARIANCE = 1e-5;
}

View File

@@ -0,0 +1,286 @@
package com.njcn.advance.responsibility.model;
import com.njcn.advance.responsibility.constant.CalculationMode;
import com.njcn.advance.responsibility.constant.CalculationStatus;
import com.njcn.advance.responsibility.constant.HarmonicConstants;
/**
* 谐波数据结构类
* 对应C语言中的harm_data_struct结构体
*
* @author hongawen
* @version 1.0
*/
public class HarmonicData {
// 输入参数
private CalculationMode calculationMode; // 计算标志
private int harmonicCount; // 谐波数据个数
private int powerCount; // 功率数据个数
private int powerNodeCount; // 功率负荷节点数
private int windowSize; // 数据窗大小
private int responsibilityDataCount; // 代入的责任数据个数
private float harmonicThreshold; // 谐波电压门槛
// 数据数组
private float[] harmonicData; // 谐波数据序列
private float[][] powerData; // 功率数据序列
// 输入输出数据
private float[][] correlationData; // 动态相关系数数据序列
private float[][] fkData; // 不包含背景动态谐波责任数据序列
private float[][] hkData; // 包含背景动态谐波责任数据序列
private float[] canonicalCorrelation; // 典则相关系数
private float[] backgroundCanonicalCorr; // 包含背景典则相关系数
// 输出结果
private CalculationStatus calculationStatus; // 计算状态
private float[] sumFKData; // 不包含背景谐波责任
private float[] sumHKData; // 包含背景谐波责任
/**
* 默认构造函数
*/
public HarmonicData() {
this.calculationMode = CalculationMode.FULL_CALCULATION;
this.calculationStatus = CalculationStatus.NOT_CALCULATED;
this.windowSize = HarmonicConstants.DEFAULT_WINDOW_SIZE;
}
/**
* Builder模式构造器
*/
public static class Builder {
private HarmonicData data = new HarmonicData();
public Builder calculationMode(CalculationMode mode) {
data.calculationMode = mode;
return this;
}
public Builder harmonicCount(int count) {
data.harmonicCount = count;
return this;
}
public Builder powerCount(int count) {
data.powerCount = count;
return this;
}
public Builder powerNodeCount(int count) {
data.powerNodeCount = count;
return this;
}
public Builder windowSize(int size) {
data.windowSize = size;
return this;
}
public Builder harmonicThreshold(float threshold) {
data.harmonicThreshold = threshold;
return this;
}
public Builder harmonicData(float[] data) {
this.data.harmonicData = data;
return this;
}
public Builder powerData(float[][] data) {
this.data.powerData = data;
return this;
}
public HarmonicData build() {
// 验证数据
validateData();
// 初始化数组
initializeArrays();
return data;
}
private void validateData() {
if (data.harmonicCount <= 0 || data.harmonicCount > HarmonicConstants.MAX_HARM_NUM) {
throw new IllegalArgumentException("Invalid harmonic count: " + data.harmonicCount);
}
if (data.powerCount <= 0 || data.powerCount > HarmonicConstants.MAX_P_NUM) {
throw new IllegalArgumentException("Invalid power count: " + data.powerCount);
}
if (data.powerNodeCount <= 0 || data.powerNodeCount > HarmonicConstants.MAX_P_NODE) {
throw new IllegalArgumentException("Invalid power node count: " + data.powerNodeCount);
}
if (data.windowSize < HarmonicConstants.MIN_WIN_LEN ||
data.windowSize > HarmonicConstants.MAX_WIN_LEN) {
throw new IllegalArgumentException("Invalid window size: " + data.windowSize);
}
// 验证数据对齐
if (data.calculationMode == CalculationMode.FULL_CALCULATION) {
int ratio = data.harmonicCount / data.powerCount;
if (ratio * data.powerCount != data.harmonicCount || ratio < 1) {
throw new IllegalArgumentException("Harmonic data count must be integer multiple of power data count");
}
}
}
private void initializeArrays() {
if (data.harmonicData == null) {
data.harmonicData = new float[data.harmonicCount];
}
if (data.powerData == null) {
data.powerData = new float[data.powerCount][data.powerNodeCount];
}
int resultCount = data.powerCount - data.windowSize;
if (resultCount > 0) {
data.correlationData = new float[resultCount][data.powerNodeCount];
data.fkData = new float[resultCount][data.powerNodeCount];
data.hkData = new float[resultCount][data.powerNodeCount + 1];
data.canonicalCorrelation = new float[resultCount];
data.backgroundCanonicalCorr = new float[resultCount];
}
data.sumFKData = new float[data.powerNodeCount];
data.sumHKData = new float[data.powerNodeCount + 1];
}
}
// Getters and Setters
public CalculationMode getCalculationMode() {
return calculationMode;
}
public void setCalculationMode(CalculationMode calculationMode) {
this.calculationMode = calculationMode;
}
public int getHarmonicCount() {
return harmonicCount;
}
public void setHarmonicCount(int harmonicCount) {
this.harmonicCount = harmonicCount;
}
public int getPowerCount() {
return powerCount;
}
public void setPowerCount(int powerCount) {
this.powerCount = powerCount;
}
public int getPowerNodeCount() {
return powerNodeCount;
}
public void setPowerNodeCount(int powerNodeCount) {
this.powerNodeCount = powerNodeCount;
}
public int getWindowSize() {
return windowSize;
}
public void setWindowSize(int windowSize) {
this.windowSize = windowSize;
}
public int getResponsibilityDataCount() {
return responsibilityDataCount;
}
public void setResponsibilityDataCount(int responsibilityDataCount) {
this.responsibilityDataCount = responsibilityDataCount;
}
public float getHarmonicThreshold() {
return harmonicThreshold;
}
public void setHarmonicThreshold(float harmonicThreshold) {
this.harmonicThreshold = harmonicThreshold;
}
public float[] getHarmonicData() {
return harmonicData;
}
public void setHarmonicData(float[] harmonicData) {
this.harmonicData = harmonicData;
}
public float[][] getPowerData() {
return powerData;
}
public void setPowerData(float[][] powerData) {
this.powerData = powerData;
}
public float[][] getCorrelationData() {
return correlationData;
}
public void setCorrelationData(float[][] correlationData) {
this.correlationData = correlationData;
}
public float[][] getFkData() {
return fkData;
}
public void setFkData(float[][] fkData) {
this.fkData = fkData;
}
public float[][] getHkData() {
return hkData;
}
public void setHkData(float[][] hkData) {
this.hkData = hkData;
}
public float[] getCanonicalCorrelation() {
return canonicalCorrelation;
}
public void setCanonicalCorrelation(float[] canonicalCorrelation) {
this.canonicalCorrelation = canonicalCorrelation;
}
public float[] getBackgroundCanonicalCorr() {
return backgroundCanonicalCorr;
}
public void setBackgroundCanonicalCorr(float[] backgroundCanonicalCorr) {
this.backgroundCanonicalCorr = backgroundCanonicalCorr;
}
public CalculationStatus getCalculationStatus() {
return calculationStatus;
}
public void setCalculationStatus(CalculationStatus calculationStatus) {
this.calculationStatus = calculationStatus;
}
public float[] getSumFKData() {
return sumFKData;
}
public void setSumFKData(float[] sumFKData) {
this.sumFKData = sumFKData;
}
public float[] getSumHKData() {
return sumHKData;
}
public void setSumHKData(float[] sumHKData) {
this.sumHKData = sumHKData;
}
}

View File

@@ -0,0 +1,61 @@
package com.njcn.advance.responsibility.service;
import com.njcn.advance.responsibility.model.HarmonicData;
/**
* 谐波责任计算服务接口
*
* @author hongawen
* @version 1.0
*/
public interface IHarmonicResponsibilityService {
/**
* 执行谐波责任计算
*
* @param data 输入的谐波数据
* @return 计算是否成功
*/
boolean calculate(HarmonicData data);
/**
* 执行完整计算
*
* @param harmonicData 谐波数据数组
* @param powerData 功率数据矩阵
* @param harmonicCount 谐波数据个数
* @param powerCount 功率数据个数
* @param nodeCount 节点数量
* @param windowSize 窗口大小
* @param threshold 谐波门槛
* @return 计算结果
*/
HarmonicData fullCalculation(float[] harmonicData, float[][] powerData,
int harmonicCount, int powerCount, int nodeCount,
int windowSize, float threshold);
/**
* 执行部分重算
*
* @param harmonicData 谐波数据数组
* @param fkData FK数据矩阵
* @param hkData HK数据矩阵
* @param harmonicCount 谐波数据个数
* @param nodeCount 节点数量
* @param windowSize 窗口大小
* @param responsibilityCount 责任数据个数
* @param threshold 谐波门槛
* @return 计算结果
*/
HarmonicData partialCalculation(float[] harmonicData, float[][] fkData, float[][] hkData,
int harmonicCount, int nodeCount, int windowSize,
int responsibilityCount, float threshold);
/**
* 验证输入数据的有效性
*
* @param data 待验证的数据
* @return 验证结果消息null表示验证通过
*/
String validateData(HarmonicData data);
}

View File

@@ -0,0 +1,162 @@
package com.njcn.advance.responsibility.service.impl;
import com.njcn.advance.responsibility.calculator.HarmonicCalculationEngine;
import com.njcn.advance.responsibility.constant.CalculationMode;
import com.njcn.advance.responsibility.constant.HarmonicConstants;
import com.njcn.advance.responsibility.model.HarmonicData;
import com.njcn.advance.responsibility.service.IHarmonicResponsibilityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
/**
* 谐波责任计算服务实现类
*
* @author hongawen
* @version 1.0
*/
@Service
public class HarmonicResponsibilityServiceImpl implements IHarmonicResponsibilityService {
private static final Logger logger = LoggerFactory.getLogger(HarmonicResponsibilityServiceImpl.class);
private final HarmonicCalculationEngine engine;
public HarmonicResponsibilityServiceImpl() {
this.engine = new HarmonicCalculationEngine();
}
@Override
public boolean calculate(HarmonicData data) {
if (data == null) {
logger.error("Input data is null");
return false;
}
String validationError = validateData(data);
if (validationError != null) {
logger.error("Data validation failed: {}", validationError);
return false;
}
long startTime = System.currentTimeMillis();
boolean result = engine.calculate(data);
long endTime = System.currentTimeMillis();
logger.info("Calculation completed in {} ms, result: {}", (endTime - startTime), result);
return result;
}
@Override
public HarmonicData fullCalculation(float[] harmonicData, float[][] powerData,
int harmonicCount, int powerCount, int nodeCount,
int windowSize, float threshold) {
logger.info("Starting full calculation with harmonicCount={}, powerCount={}, nodeCount={}, windowSize={}",
harmonicCount, powerCount, nodeCount, windowSize);
HarmonicData data = new HarmonicData.Builder()
.calculationMode(CalculationMode.FULL_CALCULATION)
.harmonicCount(harmonicCount)
.powerCount(powerCount)
.powerNodeCount(nodeCount)
.windowSize(windowSize)
.harmonicThreshold(threshold)
.harmonicData(harmonicData)
.powerData(powerData)
.build();
calculate(data);
return data;
}
@Override
public HarmonicData partialCalculation(float[] harmonicData, float[][] fkData, float[][] hkData,
int harmonicCount, int nodeCount, int windowSize,
int responsibilityCount, float threshold) {
logger.info("Starting partial calculation with harmonicCount={}, nodeCount={}, windowSize={}, responsibilityCount={}",
harmonicCount, nodeCount, windowSize, responsibilityCount);
HarmonicData data = new HarmonicData();
data.setCalculationMode(CalculationMode.PARTIAL_RECALCULATION);
data.setHarmonicCount(harmonicCount);
data.setPowerNodeCount(nodeCount);
data.setWindowSize(windowSize);
data.setResponsibilityDataCount(responsibilityCount);
data.setHarmonicThreshold(threshold);
data.setHarmonicData(harmonicData);
data.setFkData(fkData);
data.setHkData(hkData);
// 初始化输出数组
data.setSumFKData(new float[nodeCount]);
data.setSumHKData(new float[nodeCount + 1]);
calculate(data);
return data;
}
@Override
public String validateData(HarmonicData data) {
if (data == null) {
return "Data object is null";
}
// 验证基本参数
if (data.getHarmonicCount() <= 0 || data.getHarmonicCount() > HarmonicConstants.MAX_HARM_NUM) {
return String.format("Invalid harmonic count: %d (should be 1-%d)",
data.getHarmonicCount(), HarmonicConstants.MAX_HARM_NUM);
}
if (data.getCalculationMode() == CalculationMode.FULL_CALCULATION) {
// 完整计算模式验证
if (data.getPowerCount() <= 0 || data.getPowerCount() > HarmonicConstants.MAX_P_NUM) {
return String.format("Invalid power count: %d (should be 1-%d)",
data.getPowerCount(), HarmonicConstants.MAX_P_NUM);
}
if (data.getPowerNodeCount() <= 0 || data.getPowerNodeCount() > HarmonicConstants.MAX_P_NODE) {
return String.format("Invalid power node count: %d (should be 1-%d)",
data.getPowerNodeCount(), HarmonicConstants.MAX_P_NODE);
}
// 验证数据对齐
int ratio = data.getHarmonicCount() / data.getPowerCount();
if (ratio * data.getPowerCount() != data.getHarmonicCount()) {
return String.format("Harmonic count %d is not aligned with power count %d",
data.getHarmonicCount(), data.getPowerCount());
}
// 验证数据数组
if (data.getHarmonicData() == null || data.getHarmonicData().length < data.getHarmonicCount()) {
return "Harmonic data array is null or insufficient";
}
if (data.getPowerData() == null || data.getPowerData().length < data.getPowerCount()) {
return "Power data array is null or insufficient";
}
} else if (data.getCalculationMode() == CalculationMode.PARTIAL_RECALCULATION) {
// 部分计算模式验证
if (data.getResponsibilityDataCount() + data.getWindowSize() != data.getHarmonicCount()) {
return String.format("Data length mismatch: resNum(%d) + winSize(%d) != harmCount(%d)",
data.getResponsibilityDataCount(), data.getWindowSize(), data.getHarmonicCount());
}
if (data.getFkData() == null || data.getHkData() == null) {
return "FK or HK data is null for partial calculation";
}
}
// 验证窗口大小
if (data.getWindowSize() < HarmonicConstants.MIN_WIN_LEN ||
data.getWindowSize() > HarmonicConstants.MAX_WIN_LEN) {
return String.format("Invalid window size: %d (should be %d-%d)",
data.getWindowSize(), HarmonicConstants.MIN_WIN_LEN, HarmonicConstants.MAX_WIN_LEN);
}
return null; // 验证通过
}
}

View File

@@ -0,0 +1,314 @@
package com.njcn.advance.responsibility.utils;
import com.njcn.advance.responsibility.constant.HarmonicConstants;
import org.apache.commons.math3.linear.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 数学工具类
* 提供基础数学计算功能
*
* @author hongawen
* @version 1.0
*/
public class MathUtils {
private static final Logger logger = LoggerFactory.getLogger(MathUtils.class);
/**
* 计算协方差
*
* @param x 数据序列1
* @param y 数据序列2
* @param width 数据窗宽度
* @return 协方差值
*/
public static double covariance(double[] x, double[] y, int width) {
if (x == null || y == null || width <= 0) {
throw new IllegalArgumentException("Invalid input parameters for covariance calculation");
}
if (x.length < width || y.length < width) {
throw new IllegalArgumentException("Data length is less than window width");
}
double meanX = 0.0;
double meanY = 0.0;
// 计算均值
for (int i = 0; i < width; i++) {
meanX += x[i];
meanY += y[i];
}
meanX /= width;
meanY /= width;
// 计算协方差
double cov = 0.0;
for (int i = 0; i < width; i++) {
cov += (x[i] - meanX) * (y[i] - meanY);
}
return cov / (width - 1);
}
/**
* 计算协方差float版本
*/
public static float covariance(float[] x, float[] y, int width) {
double[] dx = new double[x.length];
double[] dy = new double[y.length];
for (int i = 0; i < x.length; i++) dx[i] = x[i];
for (int i = 0; i < y.length; i++) dy[i] = y[i];
return (float) covariance(dx, dy, width);
}
/**
* 计算Pearson相关系数
*
* @param x 数据序列1
* @param y 数据序列2
* @param count 数据长度
* @return Pearson相关系数
*/
public static double pearsonCorrelation(double[] x, double[] y, int count) {
if (x == null || y == null || count <= 0) {
throw new IllegalArgumentException("Invalid input parameters for Pearson correlation");
}
double meanX = 0.0;
double meanY = 0.0;
// 计算均值
for (int i = 0; i < count; i++) {
meanX += x[i];
meanY += y[i];
}
meanX /= count;
meanY /= count;
// 计算相关系数的各个部分
double numerator = 0.0;
double denomX = 0.0;
double denomY = 0.0;
for (int i = 0; i < count; i++) {
double dx = x[i] - meanX;
double dy = y[i] - meanY;
numerator += dx * dy;
denomX += dx * dx;
denomY += dy * dy;
}
double denominator = Math.sqrt(denomX * denomY);
if (Math.abs(denominator) < HarmonicConstants.EPSILON) {
logger.warn("Denominator is too small in Pearson correlation calculation");
return 0.0;
}
return numerator / denominator;
}
/**
* 计算Pearson相关系数float版本
*/
public static float pearsonCorrelation(float[] x, float[] y, int count) {
double[] dx = new double[count];
double[] dy = new double[count];
for (int i = 0; i < count; i++) {
dx[i] = x[i];
dy[i] = y[i];
}
return (float) pearsonCorrelation(dx, dy, count);
}
/**
* 计算协方差矩阵SXX
*
* @param data 数据矩阵 [时间][节点]
* @param width 窗口宽度
* @param nodeCount 节点数
* @return 协方差矩阵
*/
public static double[][] covarianceMatrix(double[][] data, int width, int nodeCount) {
double[][] covMatrix = new double[nodeCount][nodeCount];
for (int i = 0; i < nodeCount; i++) {
for (int j = 0; j < nodeCount; j++) {
double[] col1 = new double[width];
double[] col2 = new double[width];
for (int k = 0; k < width; k++) {
col1[k] = data[k][i];
col2[k] = data[k][j];
}
covMatrix[i][j] = covariance(col1, col2, width);
}
}
return covMatrix;
}
/**
* 计算协方差矩阵float版本
*/
public static float[][] covarianceMatrix(float[][] data, int width, int nodeCount) {
float[][] covMatrix = new float[nodeCount][nodeCount];
for (int i = 0; i < nodeCount; i++) {
for (int j = 0; j < nodeCount; j++) {
float[] col1 = new float[width];
float[] col2 = new float[width];
for (int k = 0; k < width; k++) {
col1[k] = data[k][i];
col2[k] = data[k][j];
}
covMatrix[i][j] = covariance(col1, col2, width);
}
}
return covMatrix;
}
/**
* 计算协方差向量SXY
*
* @param data 数据矩阵 [时间][节点]
* @param y 目标向量
* @param width 窗口宽度
* @param nodeCount 节点数
* @return 协方差向量
*/
public static double[] covarianceVector(double[][] data, double[] y, int width, int nodeCount) {
double[] covVector = new double[nodeCount];
for (int i = 0; i < nodeCount; i++) {
double[] col = new double[width];
for (int k = 0; k < width; k++) {
col[k] = data[k][i];
}
covVector[i] = covariance(col, y, width);
}
return covVector;
}
/**
* 计算协方差向量float版本
*/
public static float[] covarianceVector(float[][] data, float[] y, int width, int nodeCount) {
float[] covVector = new float[nodeCount];
for (int i = 0; i < nodeCount; i++) {
float[] col = new float[width];
for (int k = 0; k < width; k++) {
col[k] = data[k][i];
}
covVector[i] = covariance(col, y, width);
}
return covVector;
}
/**
* 矩阵求逆
* 使用Apache Commons Math库
*
* @param matrix 输入矩阵
* @return 逆矩阵
*/
public static double[][] matrixInverse(double[][] matrix) {
RealMatrix realMatrix = new Array2DRowRealMatrix(matrix);
try {
// 使用LU分解求逆
DecompositionSolver solver = new LUDecomposition(realMatrix).getSolver();
RealMatrix inverseMatrix = solver.getInverse();
return inverseMatrix.getData();
} catch (SingularMatrixException e) {
logger.error("Matrix is singular, cannot compute inverse", e);
throw new RuntimeException("Matrix inversion failed: singular matrix");
}
}
/**
* 计算矩阵的特征值
*
* @param matrix 输入矩阵
* @return 特征值数组
*/
public static double[] eigenvalues(double[][] matrix) {
RealMatrix realMatrix = new Array2DRowRealMatrix(matrix);
EigenDecomposition eigenDecomposition = new EigenDecomposition(realMatrix);
return eigenDecomposition.getRealEigenvalues();
}
/**
* 归一化处理
* 将数据归一化到[0,1]区间
*
* @param data 输入数据
* @return 归一化后的数据
*/
public static double[] normalize(double[] data) {
if (data == null || data.length == 0) {
return data;
}
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
// 找最大最小值
for (double value : data) {
min = Math.min(min, value);
max = Math.max(max, value);
}
double range = max - min;
if (Math.abs(range) < HarmonicConstants.EPSILON) {
return new double[data.length]; // 返回全0数组
}
double[] normalized = new double[data.length];
for (int i = 0; i < data.length; i++) {
normalized[i] = (data[i] - min) / range;
}
return normalized;
}
/**
* 数据对齐处理
* 将不同采样间隔的数据对齐到相同的时间间隔
*
* @param data 原始数据
* @param originalInterval 原始采样间隔
* @param targetInterval 目标采样间隔
* @return 对齐后的数据
*/
public static float[] alignData(float[] data, int originalInterval, int targetInterval) {
if (targetInterval % originalInterval != 0) {
throw new IllegalArgumentException(
"Target interval must be multiple of original interval");
}
int ratio = targetInterval / originalInterval;
int newLength = data.length / ratio;
float[] alignedData = new float[newLength];
for (int i = 0; i < newLength; i++) {
float sum = 0;
for (int j = 0; j < ratio; j++) {
sum += data[i * ratio + j];
}
alignedData[i] = sum / ratio;
}
return alignedData;
}
}

View File

@@ -11,4 +11,6 @@ import com.njcn.advance.pojo.dto.waveAnalysis.EntityAdvancedData;
public interface EventWaveAnalysisService {
EntityAdvancedData analysis(String eventIndex);
EntityAdvancedData analysisWlEvent(String eventIndex);
}

View File

@@ -565,7 +565,7 @@ public class SecondaryEvaluationServiceImpl implements SecondaryEvaluationServic
unblance.add(evaluationResult);
evaluationResult = new AssessResultVO.EvaluationResult();
evaluationResult.setData(result.getApproUnblance().multiply(BigDecimal.valueOf(200)));
evaluationResult.setData(result.getApproUnblance());
evaluationResult.setLimitData(overLimit.getUnblance());
evaluationResult.setIsQualified(NumberUtil.isLess(evaluationResult.getData(), evaluationResult.getLimitData()));
unblance.add(evaluationResult);

View File

@@ -73,6 +73,7 @@ public class GovernSchemeCalcServiceImpl implements IGovernSchemeCalcService {
throw new BusinessException(AdvanceResponseEnum.INCOMING_LINE_DATA_MISS);
}
sgGovernSchemeHistoryAllVO.setInComingLineName(sgIncomingLine.getName());
sgGovernSchemeHistoryAllVO.getQuick().setIncomingLineId(sgIncomingLine.getName());
//时间内的电网接入水平(暂降次数)
String startTime = sgGovernSchemeHistoryParam.getStartTime();
String endTime = sgGovernSchemeHistoryParam.getEndTime();

View File

@@ -322,10 +322,7 @@ public class SgEventServiceImpl extends ServiceImpl<SgEventMapper, SgEvent> impl
@Override
public boolean deleteEventData(List<String> ids) {
return this.lambdaUpdate()
.set(SgEvent::getState, DataStateEnum.DELETED.getCode())
.in(SgEvent::getId, ids)
.update();
return this.removeByIds(ids);
}
@Override

View File

@@ -9,8 +9,10 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.advance.enums.AdvanceResponseEnum;
import com.njcn.advance.mapper.govern.voltage.SgMachineMapper;
import com.njcn.advance.pojo.param.govern.voltage.SgMachineParam;
import com.njcn.advance.pojo.param.govern.voltage.SgUserParam;
import com.njcn.advance.pojo.po.govern.voltage.SgMachine;
import com.njcn.advance.pojo.po.govern.voltage.SgSensitiveUnit;
import com.njcn.advance.pojo.po.govern.voltage.SgUser;
import com.njcn.advance.pojo.vo.govern.voltage.SgMachineVO;
import com.njcn.advance.service.govern.voltage.ISgMachineService;
import com.njcn.advance.service.govern.voltage.ISgSensitiveUnitService;
@@ -56,12 +58,34 @@ public class SgMachineServiceImpl extends ServiceImpl<SgMachineMapper, SgMachine
@Override
public String addMachine(SgMachineParam sgMachineParam) {
SgMachine sgMachine = new SgMachine();
checkMachineName(sgMachineParam, false);
BeanUtil.copyProperties(sgMachineParam, sgMachine);
//默认为正常状态
sgMachine.setState(DataStateEnum.ENABLE.getCode());
this.save(sgMachine);
return sgMachine.getId();
}
/**
* 校验参数,检查是否存在相同名称的业务用户
*/
private void checkMachineName(SgMachineParam sgMachineParam, boolean isExcludeSelf) {
LambdaQueryWrapper<SgMachine> sgUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
sgUserLambdaQueryWrapper
.eq(SgMachine::getName, sgMachineParam.getName())
.eq(SgMachine::getState, DataStateEnum.ENABLE.getCode());
//更新的时候,需排除当前记录
if (isExcludeSelf) {
if (sgMachineParam instanceof SgMachineParam.SgMachineUpdateParam) {
sgUserLambdaQueryWrapper.ne(SgMachine::getId, ((SgMachineParam.SgMachineUpdateParam) sgMachineParam).getId());
}
}
int countByAccount = this.count(sgUserLambdaQueryWrapper);
//大于等于1个则表示重复
if (countByAccount >= 1) {
throw new BusinessException(AdvanceResponseEnum.SG_USER_NAME_REPEAT);
}
}
/**
* 更新设备
@@ -70,6 +94,8 @@ public class SgMachineServiceImpl extends ServiceImpl<SgMachineMapper, SgMachine
@Override
public boolean updateSgMachine(SgMachineParam.SgMachineUpdateParam updateParam) {
SgMachine sgMachine = new SgMachine();
checkMachineName(updateParam, true);
BeanUtil.copyProperties(updateParam, sgMachine);
return this.updateById(sgMachine);
}

View File

@@ -2,12 +2,15 @@ package com.njcn.advance.service.govern.voltage.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.advance.enums.AdvanceResponseEnum;
import com.njcn.advance.mapper.govern.voltage.SgSensitiveUnitMapper;
import com.njcn.advance.pojo.param.govern.voltage.SgMachineParam;
import com.njcn.advance.pojo.param.govern.voltage.SgSensitiveUnitParam;
import com.njcn.advance.pojo.po.govern.voltage.SgMachine;
import com.njcn.advance.pojo.po.govern.voltage.SgSensitiveUnit;
import com.njcn.advance.pojo.vo.govern.voltage.SgSensitiveUnitVO;
import com.njcn.advance.service.govern.voltage.ISgSensitiveUnitService;
@@ -54,12 +57,34 @@ public class SgSensitiveUnitServiceImpl extends ServiceImpl<SgSensitiveUnitMappe
@Override
public String addSensitiveUnit(SgSensitiveUnitParam sgSensitiveUnitParam) {
SgSensitiveUnit sgSensitiveUnit = new SgSensitiveUnit();
checkSensitiveUnitName(sgSensitiveUnitParam, false);
BeanUtil.copyProperties(sgSensitiveUnitParam, sgSensitiveUnit);
//默认为正常状态
sgSensitiveUnit.setState(DataStateEnum.ENABLE.getCode());
this.save(sgSensitiveUnit);
return sgSensitiveUnit.getId();
}
/**
* 校验参数,检查是否存在相同名称的业务用户
*/
private void checkSensitiveUnitName(SgSensitiveUnitParam sgSensitiveUnitParam, boolean isExcludeSelf) {
LambdaQueryWrapper<SgSensitiveUnit> sgUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
sgUserLambdaQueryWrapper
.eq(SgSensitiveUnit::getName, sgSensitiveUnitParam.getName())
.eq(SgSensitiveUnit::getState, DataStateEnum.ENABLE.getCode());
//更新的时候,需排除当前记录
if (isExcludeSelf) {
if (sgSensitiveUnitParam instanceof SgSensitiveUnitParam.SgSensitiveUnitUpdateParam) {
sgUserLambdaQueryWrapper.ne(SgSensitiveUnit::getId, ((SgSensitiveUnitParam.SgSensitiveUnitUpdateParam) sgSensitiveUnitParam).getId());
}
}
int countByAccount = this.count(sgUserLambdaQueryWrapper);
//大于等于1个则表示重复
if (countByAccount >= 1) {
throw new BusinessException(AdvanceResponseEnum.SG_USER_NAME_REPEAT);
}
}
/**
* 更新元器件
@@ -69,6 +94,8 @@ public class SgSensitiveUnitServiceImpl extends ServiceImpl<SgSensitiveUnitMappe
@Override
public boolean updateSgSensitiveUnit(SgSensitiveUnitParam.SgSensitiveUnitUpdateParam updateParam) {
SgSensitiveUnit sgSensitiveUnit = new SgSensitiveUnit();
checkSensitiveUnitName(updateParam, true);
BeanUtil.copyProperties(updateParam, sgSensitiveUnit);
return this.updateById(sgSensitiveUnit);
}

View File

@@ -48,9 +48,11 @@ import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@@ -471,6 +473,8 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
List<AdvanceEventDetailVO> advanceEventDetailVOList = BeanUtil.copyToList(rmpEventDetailPOList, AdvanceEventDetailVO.class);
advanceEventDetailVOList = advanceEventDetailVOList.stream().peek(item -> {
item.setFeatureAmplitude(roundHalfUp(item.getFeatureAmplitude()*100));
if (map.containsKey(item.getLineId())) {
AreaLineInfoVO areaLineInfoVO = map.get(item.getLineId());
item.setGdName(areaLineInfoVO.getGdName());
@@ -489,7 +493,17 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
}
/**
* 四舍五入保留两位小数
*/
private Double roundHalfUp(double num) {
if (num == 3.14159) {
return num;
}
BigDecimal b = new BigDecimal(num);
//保留2位小数
return com.njcn.harmonic.utils.PubUtils.dataLimits(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
}
@Override
public Page<RmpEventDetailAssPO> queryEventsAssPage(BaseParam baseParam) {
List<LocalDateTime> timeV = PubUtils.checkLocalDate(baseParam.getSearchBeginTime(), baseParam.getSearchEndTime());
@@ -498,7 +512,7 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
lambdaQueryWrapper.like(RmpEventDetailAssPO::getContentDes, baseParam.getSearchValue());
}
lambdaQueryWrapper.between(RmpEventDetailAssPO::getTimeId, timeV.get(0), timeV.get(1))
.orderByAsc(RmpEventDetailAssPO::getTimeId);
.orderByDesc(RmpEventDetailAssPO::getTimeId);
return rmpEventDetailAssMapper.selectPage(new Page<>(PageFactory.getPageNum(baseParam), PageFactory.getPageSize(baseParam)), lambdaQueryWrapper);
}
@@ -720,7 +734,7 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
List<AdvanceEventDetailVO> advanceEventDetailVOLsit = querySagEventsAll(startTime, endTime);
advanceEventDetailVOLsit = advanceEventDetailVOLsit.stream().filter(temp-> StringUtils.isNotEmpty(temp.getAdvanceType())).collect(Collectors.toList());
for (AdvanceEventDetailVO advanceEventDetailVO : advanceEventDetailVOLsit) { // 获取监测点线路序号
//母线id
String nodePhysics = advanceEventDetailVO.getVoltageId();
@@ -854,6 +868,21 @@ public class EventRelevantAnalysisServiceImpl extends ServiceImpl<RmpEventAdvanc
/*************************************************************************************
* 获取变压器信息并生成矩阵
*************************************************************************************/
public Map<String, Map<String, Integer>> getNodeBefore(){
Map<String, EntityMtrans> entityMtranMap = new HashMap<>(32);
HandleEvent handleEvent = new HandleEvent();
List<EntityLogic> list = relevantLogMapper.getLogic();
Map<String, Map<String, Integer>> setNodeSort = new HashMap<>();
if (CollectionUtil.isNotEmpty(list)) {
Map<String, List<String>> map = getLogicInfo(list);
setNodeSort = nodeSort(map);
}
return setNodeSort;
}
public Map<String, EntityMtrans> getNodeInfo( ) {
Map<String, EntityMtrans> entityMtranMap = new HashMap<>(32);

View File

@@ -2,13 +2,16 @@ package com.njcn.advance.service.impl;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.njcn.advance.enums.EnumEvt;
import com.njcn.advance.mapper.RmpEventAdvanceMapper;
import com.njcn.advance.pojo.dto.waveAnalysis.*;
import com.njcn.advance.service.EventWaveAnalysisService;
import com.njcn.advance.utils.*;
import com.njcn.advance.utils.JnaCallBalance;
import com.njcn.advance.utils.JnaCallDllOrSo;
import com.njcn.advance.utils.Utils;
import com.njcn.advance.utils.WaveUtils;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.pq.api.LineFeignClient;
@@ -26,7 +29,10 @@ import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@@ -81,7 +87,13 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
inputStreamCfg = fileStorageUtil.getFileStream(OssPath.WAVE_DIR + lineDetailDataVO.getIp() + StrUtil.SLASH + rmpEventDetailPO.getWavePath() + GeneralConstant.CFG);
inputStreamDat = fileStorageUtil.getFileStream(OssPath.WAVE_DIR + lineDetailDataVO.getIp() + StrUtil.SLASH + rmpEventDetailPO.getWavePath() + GeneralConstant.DAT);
} catch (Exception e) {
throw new BusinessException("暂降cfg,dat文件缺失,请联系管理员");
try {
inputStreamCfg = fileStorageUtil.getFileStream(OssPath.WAVE_DIR + lineDetailDataVO.getIp() + StrUtil.SLASH + rmpEventDetailPO.getWavePath() + GeneralConstant.CFG.toLowerCase());
inputStreamDat = fileStorageUtil.getFileStream(OssPath.WAVE_DIR + lineDetailDataVO.getIp() + StrUtil.SLASH + rmpEventDetailPO.getWavePath() + GeneralConstant.DAT.toLowerCase());
} catch (Exception e1) {
throw new BusinessException("暂降cfg,dat文件缺失,请联系管理员");
}
}
//读取
@@ -164,17 +176,13 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
causeStruct.smp_len = pitchList.size();
causeStruct.smp_rate = (int) wavePitchData.getnOneWaveNum();
String hdrStr = waveUtils.getFile(OssPath.WAVE_DIR + lineDetailDataVO.getIp() + StrUtil.SLASH + rmpEventDetailPO.getWavePath() + GeneralConstant.HDR);
JSONObject jsonObject = JSONObject.fromObject(hdrStr);
translateData(jsonObject, rmpEventDetailPO.getStartTime(), entityAdvancedData);
if (rmpEventDetailPO.getDealFlag() != 1) {
//如果存在三个文件但是没有调用dll/so计算
getDataFromDLL(rmpEventDetailPO, waveOriginalData, rect, entityAdvancedData, causeStruct);
}
@@ -208,6 +216,167 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
return entityAdvancedData;
}
@Override
public EntityAdvancedData analysisWlEvent(String eventIndex) {
TimeInterval timeInterval = new TimeInterval();
//调用方法获取暂降事件详情
RmpEventDetailPO rmpEventDetailPO = rmpEventAdvanceMapper.selectById(eventIndex);
EntityAdvancedData entityAdvancedData;
if (rmpEventDetailPO.getFileFlag() == 1) {
//获取所有暂态原因
List<DictData> dicDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()).getData();
Map<Integer, DictData> eventTypeMap = dicDataList.stream().collect(Collectors.toMap(DictData::getAlgoDescribe, Function.identity()));
InputStream inputStreamCfg;
InputStream inputStreamDat;
try {
inputStreamCfg = fileStorageUtil.getFileStream(rmpEventDetailPO.getWavePath()+ GeneralConstant.CFG);
inputStreamDat = fileStorageUtil.getFileStream(rmpEventDetailPO.getWavePath() + GeneralConstant.DAT);
} catch (Exception e) {
try {
inputStreamCfg = fileStorageUtil.getFileStream(rmpEventDetailPO.getWavePath() + GeneralConstant.CFG.toLowerCase());
inputStreamDat = fileStorageUtil.getFileStream(rmpEventDetailPO.getWavePath() + GeneralConstant.DAT.toLowerCase());
} catch (Exception e1) {
throw new BusinessException("暂降cfg,dat文件缺失,请联系管理员");
}
}
//读取
BufferedReader bufferedReader;
InputStreamReader read = null;
String strFileLine;
byte[] array = {};
List<String> temCfgList = new ArrayList<>();
try {
// 判断文件是否存在
array = IoUtil.readBytes(inputStreamDat);
// 考虑到编码格式
read = new InputStreamReader(inputStreamCfg, StandardCharsets.UTF_8);
bufferedReader = new BufferedReader(read);
while ((strFileLine = bufferedReader.readLine()) != null) {
temCfgList.add(strFileLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (read != null) {
read.close();
}
if (inputStreamDat != null) {
inputStreamDat.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//原始波形
WaveData waveOriginalData = getWavedata(rmpEventDetailPO, temCfgList, array, 3);
List<List<Float>> originalList = waveOriginalData.getSunData();
entityAdvancedData = new EntityAdvancedData(originalList.size());
for (int i = 0; i < originalList.size(); i++) {
//坐标轴
entityAdvancedData.smp_x[i] = originalList.get(i).get(0);
entityAdvancedData.smp_a[i] = originalList.get(i).get(1);
entityAdvancedData.smp_b[i] = originalList.get(i).get(2);
entityAdvancedData.smp_c[i] = originalList.get(i).get(3);
}
entityAdvancedData.smp_len = originalList.size();
//抽点方法计算波形
WaveData wavePitchData = getWavedata(rmpEventDetailPO, temCfgList, array, 0);
List<List<Float>> pitchList = wavePitchData.getSunData();
// 将获取到的数据填充到结构体内
Rect rect = new Rect();
CauseStruct causeStruct = new CauseStruct();
for (int i = 0; i < pitchList.size(); i++) {
rect.smp_va[i] = pitchList.get(i).get(1);
causeStruct.smp_va[i] = pitchList.get(i).get(1);
rect.smp_vb[i] = pitchList.get(i).get(2);
causeStruct.smp_vb[i] = pitchList.get(i).get(2);
rect.smp_vc[i] = pitchList.get(i).get(3);
causeStruct.smp_vc[i] = pitchList.get(i).get(3);
}
rect.smp_len = pitchList.size();
//超过60s的波形直接抛异常给上面处理
/*
* 波形最大值计算
*/
int MAX_LENGTH = 128 * 3000;
if (rect.smp_len >= MAX_LENGTH) {
throw new BusinessException("波形超过60S");
}
rect.smp_rate = (int) wavePitchData.getnOneWaveNum();
causeStruct.smp_len = pitchList.size();
causeStruct.smp_rate = (int) wavePitchData.getnOneWaveNum();
if (rmpEventDetailPO.getDealFlag() != 1) {
//如果存在三个文件但是没有调用dll/so计算
getDataFromDLL(rmpEventDetailPO, waveOriginalData, rect, entityAdvancedData, causeStruct);
} else {
//已经处理过了那就根据id获取暂降原因
String reason = rmpEventDetailPO.getAdvanceReason();
List<DictData> reasonList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_REASON.getCode()).getData();
Map<String, DictData> eventReasonMap = reasonList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
if (ObjectUtil.isNotNull(eventReasonMap.get(reason))) {
entityAdvancedData.sagReason[0] = eventReasonMap.get(reason).getName();
}
}
String hdrStr = null;
try {
hdrStr = waveUtils.getFile(rmpEventDetailPO.getWavePath() + GeneralConstant.HDR.toLowerCase());
} catch (Exception e) {
log.error("读取文件服务器波形数据异常:{}",e.getMessage());
}
if (hdrStr != null) {
JSONObject jsonObject = JSONObject.fromObject(hdrStr);
translateData(jsonObject, rmpEventDetailPO.getStartTime(), entityAdvancedData);
}
// if (rmpEventDetailPO.getDealFlag() != 1) {
// //如果存在三个文件但是没有调用dll/so计算
// getDataFromDLL(rmpEventDetailPO, waveOriginalData, rect, entityAdvancedData, causeStruct);
// }
/****************************************************************
* 根据返回的结果计算,获取暂降类型描述
****************************************************************/
if (entityAdvancedData.backNumber > 0) {
for (int i = 0; i < entityAdvancedData.backNumber; i++) {
entityAdvancedData.sagType[i] = eventTypeMap.get(entityAdvancedData.evt_buf[i].qvvr_cata_type[0]).getName();
switch (entityAdvancedData.evt_buf[i].qvvr_phasetype[0]) {
case 1:
entityAdvancedData.sagPhaseType[i] = "单相";
break;
case 2:
entityAdvancedData.sagPhaseType[i] = "两相";
break;
case 3:
entityAdvancedData.sagPhaseType[i] = "三相";
break;
default:
break;
}
}
}
} else {
throw new BusinessException("暂降cfg,dat文件缺失,请联系管理员");
}
log.info("高级算法波形计算" + timeInterval.interval());
return entityAdvancedData;
}
/**
* 事件未进行高级算法处理系统调用dll处理并保存结果
@@ -352,7 +521,7 @@ public class EventWaveAnalysisServiceImpl implements EventWaveAnalysisService {
if (StrUtil.isBlank(rmpEventDetailPOQuery.getAdvanceReason())) {
//暂降原因计算
JnaCallDllOrSo jnaCallDllReason = new JnaCallBalance("qvvr_dll_cause");
JnaCallDllOrSo jnaCallDllReason = new JnaCallBalance("qvvr_cause_dll");
jnaCallDllReason.setPath();
JnaCallBalance.Balancelibrary CAUSE = JnaCallBalance.Balancelibrary.INSTANTCE;

View File

@@ -21,8 +21,12 @@ import java.util.List;
*/
public interface IRespDataService extends IService<RespData> {
ResponsibilityResult getDynamicDataOld(ResponsibilityCalculateParam responsibilityCalculateParam);
ResponsibilityResult getDynamicData(ResponsibilityCalculateParam responsibilityCalculateParam);
ResponsibilityResult getResponsibilityDataOld(ResponsibilitySecondCalParam responsibilitySecondCalParam);
ResponsibilityResult getResponsibilityData(ResponsibilitySecondCalParam responsibilitySecondCalParam);
Page<RespDataDTO> responsibilityList(BaseParam queryParam);

View File

@@ -27,6 +27,9 @@ import com.njcn.advance.pojo.param.ResponsibilityCalculateParam;
import com.njcn.advance.pojo.param.ResponsibilitySecondCalParam;
import com.njcn.advance.pojo.po.responsibility.RespData;
import com.njcn.advance.pojo.po.responsibility.RespDataResult;
import com.njcn.advance.responsibility.constant.CalculationStatus;
import com.njcn.advance.responsibility.model.HarmonicData;
import com.njcn.advance.responsibility.service.IHarmonicResponsibilityService;
import com.njcn.advance.service.responsibility.IRespDataResultService;
import com.njcn.advance.service.responsibility.IRespDataService;
import com.njcn.advance.service.responsibility.IRespUserDataService;
@@ -91,6 +94,8 @@ public class RespDataServiceImpl extends ServiceImpl<RespDataMapper, RespData> i
private final CommTerminalGeneralClient commTerminalGeneralClient;
private final IHarmonicResponsibilityService harmonicResponsibilityService;
public final static int SORT_10 = 10;
public final static int INTERVAL_TIME_1 = 1;
public final static int INTERVAL_TIME_3 = 3;
@@ -161,7 +166,8 @@ public class RespDataServiceImpl extends ServiceImpl<RespDataMapper, RespData> i
@Override
public ResponsibilityResult getDynamicData(ResponsibilityCalculateParam responsibilityCalculateParam) {
@Deprecated
public ResponsibilityResult getDynamicDataOld(ResponsibilityCalculateParam responsibilityCalculateParam) {
ResponsibilityResult result = new ResponsibilityResult();
//调用c++依赖需要待初始化的参数
int pNode, pNum, win, harmNum;
@@ -419,7 +425,268 @@ public class RespDataServiceImpl extends ServiceImpl<RespDataMapper, RespData> i
}
@Override
public ResponsibilityResult getResponsibilityData(ResponsibilitySecondCalParam responsibilitySecondCalParam) {
public ResponsibilityResult getDynamicData(ResponsibilityCalculateParam responsibilityCalculateParam) {
ResponsibilityResult result = new ResponsibilityResult();
//调用c++依赖需要待初始化的参数
int pNode, pNum, win, harmNum;
float harmMk;
List<UserDataExcel> userDataExcels = respUserDataService.getUserDataExcelList(responsibilityCalculateParam.getUserDataId());
//开始处理,根据接口参数需求,需要节点数(用户数,用户名+监测点号为一个用户),时间范围内功率数据
DealDataResult dealDataResult = RespUserDataServiceImpl.getStanderData(userDataExcels, 1);
List<String> dateStr = PubUtils.getTimes(DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN), DateUtil.parse(responsibilityCalculateParam.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN));
Map<String/*户号@监测点号@户名*/, Map<String/*yyyy-MM-dd天日期*/, List<UserDataExcel>>> finalData = getFinalUserData(dealDataResult, dateStr);
//至此finalData便是我们最终获得的用于计算责任数据,第一个参数节点数值pNode获取到
//第一个参数pNode
pNode = finalData.size();
if (pNode < 1) {
//没有合理的用采数据直接返回
throw new BusinessException(AdvanceResponseEnum.USER_DATA_P_NODE_PARAMETER_ERROR);
}
//第二个参数pNum根据起始时间和截止时间以及监测点测量间隔计算数量
RespCommon pNumAndInterval = getPNumAndInterval(finalData, responsibilityCalculateParam.getLineId(), dateStr);
pNum = pNumAndInterval.getPNum();
int userIntervalTime = pNumAndInterval.getUserIntervalTime();
int lineInterval = pNumAndInterval.getLineInterval();
//第三个参数win,根据起始时间和截止时间的间隔
if (dateStr.size() > 1) {
if (userIntervalTime == INTERVAL_TIME_15) {
win = WINDOW_96;
} else {
win = WINDOW_48;
}
} else {
win = WINDOW_4;
}
//第四个参数harmMk默认为0f
harmMk = 0f;
//第五个参数harmNum与功率数据保持一致
harmNum = pNum;
//至此基础数据组装完毕,开始组装功率数据和谐波数据
//先做谐波数据理论上到这步的时候谐波数据是满足完整性并已经补充完整性到100%,此处需要将谐波数据与功率数据长度匹配上
RespHarmData respHarmData = getRespHarmData(responsibilityCalculateParam, lineInterval);
//harmData填充完毕后开始组装功率数据
//首先获取当前时间内的各个用户的数据
Map<String/*用户名*/, List<UserDataExcel>> originalPData = new HashMap<>(16);
List<String> names = new ArrayList<>();
Set<String> userNamesFinal = finalData.keySet();
for (String userName : userNamesFinal) {
List<UserDataExcel> tempData = new ArrayList<>();
//根据日期将日期数据全部获取出来z
Map<String, List<UserDataExcel>> tempResult = finalData.get(userName);
for (String date : dateStr) {
tempData.addAll(tempResult.get(date));
}
//按日期排序
Collections.sort(tempData);
originalPData.put(userName, tempData);
names.add(userName);
}
//然后开始组装数据
float[][] pData = new float[QvvrDataEntity.MAX_P_NUM][QvvrDataEntity.MAX_P_NODE];
for (int i = 0; i < names.size(); i++) {
//当前某用户测量节点的所有数据
List<UserDataExcel> userDataExcelBodies1 = originalPData.get(names.get(i));
for (int k = 0; k < userDataExcelBodies1.size(); k++) {
float[] pDataStruct = pData[k];
if (pDataStruct == null) {
pDataStruct = new float[QvvrDataEntity.MAX_P_NODE];
}
float[] p = pDataStruct;
p[i] = userDataExcelBodies1.get(k).getWork().floatValue();
pData[k] = pDataStruct;
}
}
//至此功率数据也组装完毕,调用友谊提供的接口
// QvvrDataEntity qvvrDataEntity = new QvvrDataEntity();
// qvvrDataEntity.calFlag = 0;
// qvvrDataEntity.pNode = pNode;
// qvvrDataEntity.pNum = pNum;
// qvvrDataEntity.win = win;
// qvvrDataEntity.harmNum = harmNum;
// qvvrDataEntity.harmMk = harmMk;
// qvvrDataEntity.pData = pData;
// qvvrDataEntity.harmData = respHarmData.getHarmData();
// ResponsibilityAlgorithm responsibilityAlgorithm = new ResponsibilityAlgorithm();
// qvvrDataEntity = responsibilityAlgorithm.getResponsibilityResult(qvvrDataEntity);
HarmonicData harmonicData = harmonicResponsibilityService.fullCalculation(respHarmData.getHarmData(), pData, harmNum, pNum, pNode, win, harmMk);
//至此接口调用结束,开始组装动态责任数据和用户责任量化结果
//首先判断cal_ok的标识位是否为1为0表示程序没有计算出结果
if (harmonicData.getCalculationStatus() == CalculationStatus.FAILED) {
throw new BusinessException(AdvanceResponseEnum.RESPONSIBILITY_PARAMETER_ERROR);
}
//没问题后,先玩动态责任数据
CustomerData[] customerDatas = new CustomerData[harmonicData.getPowerNodeCount()];
float[][] fKdata/*无背景的动态责任数据*/ = harmonicData.getFkData();
//第一个时间节点是起始时间+win窗口得到的时间
Date sTime = DateUtil.parse(dateStr.get(0).concat(" 00:00:00"), DatePattern.NORM_DATETIME_PATTERN);
Calendar calendar = Calendar.getInstance();
calendar.setTime(sTime);
calendar.add(Calendar.MINUTE, (win - 1) * userIntervalTime);
List<Long> timeDatas = new ArrayList<>();
for (int i = 0; i < harmonicData.getPowerCount() - harmonicData.getWindowSize(); i++) {
calendar.add(Calendar.MINUTE, userIntervalTime);
//一个时间点所有的用户数据
float[] fKdatum = fKdata[i];
for (int k = 0; k < harmonicData.getPowerNodeCount(); k++) {
CustomerData customerData = customerDatas[k];
if (null == customerData) {
customerData = new CustomerData();
customerData.setCustomerName(names.get(k));
}
List<Float> valueDatas = customerData.getValueDatas();
Float valueTemp = fKdatum[k];
if (valueTemp.isNaN()) {
valueTemp = 0.0f;
}
valueDatas.add(valueTemp);
customerData.setValueDatas(valueDatas);
customerDatas[k] = customerData;
}
timeDatas.add(calendar.getTimeInMillis());
}
//OK拿到所有测量点的数据了现在就是看如何将相同户号的动态数据进行算术和求值之前的用户name为户号@测量点号@用户名
Map<String/*用户名(户号)*/, List<CustomerData>> customerDataTemp = new HashMap<>(16);
for (CustomerData data : customerDatas) {
String customerName = data.getCustomerName();
String[] customerInfo = customerName.split("@");
String name = customerInfo[2] + "(" + customerInfo[0] + ")";
List<CustomerData> customerData = customerDataTemp.get(name);
CustomerData temp = data;
temp.setCustomerName(name);
if (CollectionUtils.isEmpty(customerData)) {
customerData = new ArrayList<>();
}
customerData.add(temp);
customerDataTemp.put(name, customerData);
}
//动态数据组装完成后,开始组装责任数据
List<CustomerResponsibility> customerResponsibilities = getCustomerResponsibilityData(names, harmonicData.getSumFKData(), harmonicData.getPowerNodeCount());
//根据前十的用户数据,获取这些用户的动态责任数据
List<CustomerData> customerData = new ArrayList<>();
for (CustomerResponsibility customerResponsibility : customerResponsibilities) {
String cusName = customerResponsibility.getCustomerName();
List<CustomerData> customerData1 = customerDataTemp.get(cusName);
if (CollectionUtils.isEmpty(customerData1)) {
continue;
}
if (customerData1.size() == 1) {
//表示用户唯一的
customerData.add(customerData1.get(0));
} else {
// 表示用户可能包含多个监测点号,需要进行数据累加
CustomerData customerDataT = new CustomerData();
customerDataT.setCustomerName(cusName);
//进行数值累加
List<Float> valueDatas = new ArrayList<>();
for (int i = 0; i < customerData1.get(0).getValueDatas().size(); i++) {
float original = 0.0f;
for (CustomerData data : customerData1) {
original = original + data.getValueDatas().get(i);
}
valueDatas.add(original);
}
customerDataT.setValueDatas(valueDatas);
customerData.add(customerDataT);
}
}
result.setDatas(customerData);
result.setTimeDatas(timeDatas);
result.setResponsibilities(customerResponsibilities);
//此次的操作进行入库操作responsibilityData表数据
//根据监测点名称+谐波框选的时间来查询,是否做过责任量化
String timeWin = responsibilityCalculateParam.getSearchBeginTime().replaceAll(StrPool.DASHED, "").concat(StrPool.DASHED).concat(responsibilityCalculateParam.getSearchEndTime().replaceAll(StrPool.DASHED, ""));
String type = responsibilityCalculateParam.getType() == 0 ? "谐波电流" : "谐波电压";
//为了避免有监测点名称重复的,最终还是选择使用监测点索引来判断唯一性
LambdaQueryWrapper<RespData> respDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
respDataLambdaQueryWrapper.eq(RespData::getLineId, responsibilityCalculateParam.getLineId())
.eq(RespData::getUserDataId, responsibilityCalculateParam.getUserDataId())
.eq(RespData::getTimeWindow, timeWin)
.eq(RespData::getDataType, type)
.eq(RespData::getState, DataStateEnum.ENABLE.getCode());
List<RespData> responsibilityDataTemp = this.baseMapper.selectList(respDataLambdaQueryWrapper);
RespData responsibilityData;
if (CollectionUtils.isEmpty(responsibilityDataTemp)) {
responsibilityData = new RespData();
//库中没有记录则可以新建数据进行插入
responsibilityData.setLineId(responsibilityCalculateParam.getLineId());
responsibilityData.setUserDataId(responsibilityCalculateParam.getUserDataId());
responsibilityData.setDataType(type);
responsibilityData.setDataTimes(responsibilityCalculateParam.getTime().toString());
responsibilityData.setTimeWindow(timeWin);
responsibilityData.setState(DataStateEnum.ENABLE.getCode());
//进行插入操作
this.baseMapper.insert(responsibilityData);
} else {
//库中存在记录只需要判断次数进行数据更新
responsibilityData = responsibilityDataTemp.get(0);
String times = responsibilityData.getDataTimes();
List<String> timesList = Stream.of(times.split(StrPool.COMMA)).collect(Collectors.toList());
Integer time = responsibilityCalculateParam.getTime();
if (!timesList.contains(time.toString())) {
timesList.add(time.toString());
timesList = timesList.stream().sorted().collect(Collectors.toList());
responsibilityData.setDataTimes(String.join(StrPool.COMMA, timesList));
}
//执行更新操作
this.baseMapper.updateById(responsibilityData);
}
//入库完毕之后,需要将必要数据进行序列化存储,方便后期的重复利用
/*
* 需要序列化三种数据结构 1 cal_flag置为1时需要的一些列参数的CacheQvvrData 2 cal_flag为0时的动态结果。3 用户责任量化结果
* 其中1/2都只需要一个文件即可
* 3因为用户限值的变化调整可能存在很多个文件具体根据用户的选择而定
*
* 路径的结构为temPath+userData+excelName+type+timeWin+lineIndex+time+文件名
* 用户责任量化结果,需要再细化到限值
*/
//首先判断有没有存储记录,没有则存储,有就略过 指定测点、时间窗口、谐波类型、谐波次数判断唯一性
LambdaQueryWrapper<RespDataResult> respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>();
respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, responsibilityData.getId())
.eq(RespDataResult::getTime, responsibilityCalculateParam.getTime())
.eq(RespDataResult::getStartTime, DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime() + " 00:00:00", DatePattern.NORM_DATETIME_PATTERN))
.eq(RespDataResult::getEndTime, DateUtil.parse(responsibilityCalculateParam.getSearchEndTime() + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN))
.eq(RespDataResult::getLimitValue, respHarmData.getOverLimit());
RespDataResult respDataResult = respDataResultService.getOne(respDataResultLambdaQueryWrapper);
if (Objects.isNull(respDataResult)) {
respDataResult = new RespDataResult();
respDataResult.setResDataId(responsibilityData.getId());
respDataResult.setTime(responsibilityCalculateParam.getTime());
respDataResult.setStartTime(DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime() + " 00:00:00", DatePattern.NORM_DATETIME_PATTERN));
respDataResult.setEndTime(DateUtil.parse(responsibilityCalculateParam.getSearchEndTime() + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN));
respDataResult.setLimitValue(respHarmData.getOverLimit());
//时间横轴数据 timeDatas
JSONArray timeDataJson = JSONArray.parseArray(JSON.toJSONString(timeDatas));
InputStream timeDataStream = IoUtil.toUtf8Stream(timeDataJson.toString());
String timeDataPath = fileStorageUtil.uploadStream(timeDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json"));
respDataResult.setTimeData(timeDataPath);
//用户每时刻对应的责任数据
JSONArray customerDataJson = JSONArray.parseArray(JSON.toJSONString(customerData));
InputStream customerStream = IoUtil.toUtf8Stream(customerDataJson.toString());
String customerPath = fileStorageUtil.uploadStream(customerStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json"));
respDataResult.setUserDetailData(customerPath);
//调用qvvr生成的中间数据
CacheQvvrData cacheQvvrData = new CacheQvvrData(harmonicData.getPowerNodeCount(), harmonicData.getHarmonicCount(), harmonicData.getHarmonicData(), harmonicData.getFkData(), harmonicData.getHkData(), names, userIntervalTime, harmonicData.getWindowSize(), userIntervalTime, respHarmData.getHarmTime());
String cacheJson = PubUtils.obj2json(cacheQvvrData);
InputStream cacheQvvrDataStream = IoUtil.toUtf8Stream(cacheJson);
String cacheQvvrDataPath = fileStorageUtil.uploadStream(cacheQvvrDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json"));
respDataResult.setQvvrData(cacheQvvrDataPath);
//用户前10数据存储
JSONArray customerResJson = JSONArray.parseArray(JSON.toJSONString(customerResponsibilities));
InputStream customerResStream = IoUtil.toUtf8Stream(customerResJson.toString());
String customerResPath = fileStorageUtil.uploadStream(customerResStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json"));
respDataResult.setUserResponsibility(customerResPath);
respDataResultService.save(respDataResult);
}
//防止过程中创建了大量的对象主动调用下GC处理
System.gc();
result.setResponsibilityDataIndex(responsibilityData.getId());
return result;
}
@Override
@Deprecated
public ResponsibilityResult getResponsibilityDataOld(ResponsibilitySecondCalParam responsibilitySecondCalParam) {
ResponsibilityResult result = new ResponsibilityResult();
//根据时间天数,获取理论上多少次用采数据
RespData responsibilityData = this.baseMapper.selectById(responsibilitySecondCalParam.getResDataId());
@@ -664,6 +931,258 @@ public class RespDataServiceImpl extends ServiceImpl<RespDataMapper, RespData> i
return result;
}
@Override
public ResponsibilityResult getResponsibilityData(ResponsibilitySecondCalParam responsibilitySecondCalParam) {
ResponsibilityResult result = new ResponsibilityResult();
//根据时间天数,获取理论上多少次用采数据
RespData responsibilityData = this.baseMapper.selectById(responsibilitySecondCalParam.getResDataId());
if (Objects.isNull(responsibilityData)) {
throw new BusinessException(AdvanceResponseEnum.RESP_DATA_NOT_FOUND);
}
Overlimit overlimit = lineFeignClient.getOverLimitData(responsibilityData.getLineId()).getData();
//获取总数据
LambdaQueryWrapper<RespDataResult> respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>();
respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, responsibilityData.getId())
.eq(RespDataResult::getTime, responsibilitySecondCalParam.getTime());
if (responsibilitySecondCalParam.getType() == 0) {
respDataResultLambdaQueryWrapper.eq(RespDataResult::getLimitValue, PubUtils.getValueByMethod(overlimit, "getIharm", responsibilitySecondCalParam.getTime()));
} else {
respDataResultLambdaQueryWrapper.eq(RespDataResult::getLimitValue, PubUtils.getValueByMethod(overlimit, "getUharm", responsibilitySecondCalParam.getTime()));
}
RespDataResult respDataResultTemp = respDataResultService.getOne(respDataResultLambdaQueryWrapper);
if (Objects.isNull(respDataResultTemp)) {
throw new BusinessException(AdvanceResponseEnum.RESP_DATA_NOT_FOUND);
}
CacheQvvrData cacheQvvrData;
try {
InputStream fileStream = fileStorageUtil.getFileStream(respDataResultTemp.getQvvrData());
String qvvrDataStr = IoUtil.readUtf8(fileStream);
cacheQvvrData = PubUtils.json2obj(qvvrDataStr, CacheQvvrData.class);
} catch (Exception exception) {
throw new BusinessException(AdvanceResponseEnum.RESP_RESULT_DATA_NOT_FOUND);
}
//获取成功后,延长该缓存的生命周期为初始生命时长
int win = cacheQvvrData.getWin();
//不管窗口为4或者96都需要考虑最小公倍数
//最小公倍数根据监测点测量间隔来获取,可以考虑也由第一步操作缓存起来
int minMultiple = cacheQvvrData.getMinMultiple();
//谐波横轴所有的时间
List<Long> times = cacheQvvrData.getTimes();
//首先根据窗口判断限值时间范围是否满足最小窗口
Long limitSL = DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN).getTime();
Long limitEL = DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN).getTime();
List<Integer> temp = getTimes(times, limitSL, limitEL);
//在动态责任数据中,时间的起始索引位置和截止索引位置
Integer timeStartIndex = temp.get(0);
Integer timeEndIndex = temp.get(1);
//间隔中的时间长度
int minus = timeEndIndex - timeStartIndex + 1;
//组装参数
QvvrDataEntity qvvrDataEntity = new QvvrDataEntity();
qvvrDataEntity.calFlag = 1;
qvvrDataEntity.pNode = cacheQvvrData.getPNode();
qvvrDataEntity.harmMk = responsibilitySecondCalParam.getLimitValue();
qvvrDataEntity.win = win;
int resNum;
float[][] FKdata = new float[9600][QvvrDataEntity.MAX_P_NODE];
float[][] HKdata = new float[9600][QvvrDataEntity.MAX_P_NODE + 1];
float[] harmData = new float[1440 * 100];
float[][] fKdataOriginal = cacheQvvrData.getFKData();
float[][] hKdataOriginal = cacheQvvrData.getHKData();
float[] harmDataOriginal = cacheQvvrData.getHarmData();
//如果起始索引与截止索引的差值等于时间轴的长度,则说明用户没有选择限值时间,直接带入全部的原始数据,参与计算即可
if (minus == times.size()) {
qvvrDataEntity.harmNum = cacheQvvrData.getHarmNum();
qvvrDataEntity.resNum = cacheQvvrData.getHarmNum() - cacheQvvrData.getWin();
qvvrDataEntity.setFKData(cacheQvvrData.getFKData());
qvvrDataEntity.setHKData(cacheQvvrData.getHKData());
qvvrDataEntity.harmData = cacheQvvrData.getHarmData();
} else {
if (win == WINDOW_4) {
//当窗口为4时,两个时间限制范围在最小公倍数为15时最起码有5个有效时间点在最小公倍数为30时最起码有3个有效时间点
if (minMultiple == INTERVAL_TIME_15) {
if (minus < MINUS_5) {
throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR);
}
resNum = minus - MINUS_4;
} else if (minMultiple == INTERVAL_TIME_30) {
if (minus < MINUS_3) {
throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR);
}
resNum = minus - MINUS_2;
} else {
throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR);
}
} else if (win == WINDOW_96) {
//当窗口为96时,两个时间限值范围在最小公倍数为15时最起码有97个有效时间点在最小公倍数为30时最起码有49个有效时间点
if (minMultiple == INTERVAL_TIME_15) {
if (minus <= WINDOW_96) {
throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR);
}
resNum = minus - WINDOW_96;
} else if (minMultiple == INTERVAL_TIME_30) {
if (minus <= WINDOW_48) {
throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR);
}
resNum = minus - WINDOW_48;
} else {
throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR);
}
} else {
throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR);
}
qvvrDataEntity.resNum = resNum;
qvvrDataEntity.harmNum = minus;
//因为限值时间实际是含头含尾的所以harmNum需要索引差值+1
for (int i = timeStartIndex; i <= timeEndIndex; i++) {
harmData[i - timeStartIndex] = harmDataOriginal[i];
}
qvvrDataEntity.harmData = harmData;
//FKData与HKData的值则等于resNum
for (int i = timeStartIndex; i < timeStartIndex + resNum; i++) {
FKdata[i - timeStartIndex] = fKdataOriginal[i];
HKdata[i - timeStartIndex] = hKdataOriginal[i];
}
qvvrDataEntity.setFKData(FKdata);
qvvrDataEntity.setHKData(HKdata);
}
// ResponsibilityAlgorithm responsibilityAlgorithm = new ResponsibilityAlgorithm();
// qvvrDataEntity = responsibilityAlgorithm.getResponsibilityResult(qvvrDataEntity);
//
// if (qvvrDataEntity.calOk == 0) {
// throw new BusinessException(AdvanceResponseEnum.RESPONSIBILITY_PARAMETER_ERROR);
// }
HarmonicData harmonicData = harmonicResponsibilityService.partialCalculation(
qvvrDataEntity.getHarmData(), qvvrDataEntity.getFKData(), qvvrDataEntity.getHKData(), qvvrDataEntity.getHarmNum(), qvvrDataEntity.getPNode(), qvvrDataEntity.getWin(), qvvrDataEntity.getResNum(), qvvrDataEntity.getHarmMk());
if (harmonicData.getCalculationStatus() == CalculationStatus.FAILED) {
throw new BusinessException(AdvanceResponseEnum.RESPONSIBILITY_PARAMETER_ERROR);
}
//没问题后,先玩动态责任数据
List<String> names = cacheQvvrData.getNames();
CustomerData[] customerDatas = new CustomerData[harmonicData.getPowerNodeCount()];
float[][] fKdata/*无背景的动态责任数据*/ = harmonicData.getFkData();
//第一个时间节点是起始时间+win窗口得到的时间
Date sTime = new Date();
sTime.setTime(times.get(timeStartIndex));
Calendar calendar = Calendar.getInstance();
calendar.setTime(sTime);
calendar.add(Calendar.MINUTE, (win - 1) * minMultiple);
List<Long> timeDatas = new ArrayList<>();
for (int i = 0; i < harmonicData.getHarmonicCount() - harmonicData.getWindowSize(); i++) {
calendar.add(Calendar.MINUTE, minMultiple);
//一个时间点所有的用户数据
float[] fKdatum = fKdata[i];
for (int k = 0; k < harmonicData.getPowerNodeCount(); k++) {
CustomerData customerData = customerDatas[k];
if (null == customerData) {
customerData = new CustomerData();
customerData.setCustomerName(names.get(k));
}
List<Float> valueDatas = customerData.getValueDatas();
Float valueTemp = fKdatum[k];
if (valueTemp.isNaN()) {
valueTemp = 0.0f;
}
valueDatas.add(valueTemp);
customerData.setValueDatas(valueDatas);
customerDatas[k] = customerData;
}
timeDatas.add(calendar.getTimeInMillis());
}
//OK拿到所有测量点的数据了现在就是看如何将相同户号的动态数据进行算术和求值之前的用户name为户号@测量点号@用户名
Map<String/*用户名(户号)*/, List<CustomerData>> customerDataTemp = new HashMap<>(32);
for (CustomerData data : customerDatas) {
String customerName = data.getCustomerName();
String[] customerInfo = customerName.split("@");
String name = customerInfo[2] + "(" + customerInfo[0] + ")";
List<CustomerData> customerData = customerDataTemp.get(name);
CustomerData customerTemp = data;
customerTemp.setCustomerName(name);
if (CollectionUtils.isEmpty(customerData)) {
customerData = new ArrayList<>();
}
customerData.add(customerTemp);
customerDataTemp.put(name, customerData);
}
//调用程序接口后,首先组装责任量化结果
float[] sumFKdata = harmonicData.getSumFKData();
List<CustomerResponsibility> customerResponsibilities = getCustomerResponsibilityData(names, sumFKdata, harmonicData.getPowerNodeCount());
//根据前十的用户数据,获取这些用户的动态责任数据
List<CustomerData> customerData = new ArrayList<>();
for (CustomerResponsibility customerResponsibility : customerResponsibilities) {
String cusName = customerResponsibility.getCustomerName();
List<CustomerData> customerData1 = customerDataTemp.get(cusName);
if (CollectionUtils.isEmpty(customerData1)) {
continue;
}
if (customerData1.size() == 1) {
//表示用户唯一的
customerData.add(customerData1.get(0));
} else {
// 表示用户可能包含多个监测点号,需要进行数据累加
CustomerData customerDataT = new CustomerData();
customerDataT.setCustomerName(cusName);
//进行数值累加
List<Float> valueDatas = new ArrayList<>();
for (int i = 0; i < customerData1.get(0).getValueDatas().size(); i++) {
float original = 0.0f;
for (CustomerData data : customerData1) {
original = original + data.getValueDatas().get(i);
}
valueDatas.add(original);
}
customerDataT.setValueDatas(valueDatas);
customerData.add(customerDataT);
}
}
//接着组装动态数据结果
result.setResponsibilities(customerResponsibilities);
result.setDatas(customerData);
result.setTimeDatas(timeDatas);
//首先判断有没有存储记录,没有则存储,有就略过 指定测点、时间窗口、谐波类型、谐波次数判断唯一性
LambdaQueryWrapper<RespDataResult> respDataResultLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
respDataResultLambdaQueryWrapper1.eq(RespDataResult::getResDataId, responsibilityData.getId())
.eq(RespDataResult::getTime, responsibilitySecondCalParam.getTime())
.eq(RespDataResult::getStartTime, DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN))
.eq(RespDataResult::getEndTime, DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN))
.eq(RespDataResult::getLimitValue, responsibilitySecondCalParam.getLimitValue());
RespDataResult respDataResult = respDataResultService.getOne(respDataResultLambdaQueryWrapper1);
if (Objects.isNull(respDataResult)) {
respDataResult = new RespDataResult();
respDataResult.setResDataId(responsibilityData.getId());
respDataResult.setTime(responsibilitySecondCalParam.getTime());
respDataResult.setStartTime(DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN));
respDataResult.setEndTime(DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN));
respDataResult.setLimitValue(responsibilitySecondCalParam.getLimitValue());
//时间横轴数据 timeDatas
JSONArray timeDataJson = JSONArray.parseArray(JSON.toJSONString(timeDatas));
InputStream timeDataStream = IoUtil.toUtf8Stream(timeDataJson.toString());
String timeDataPath = fileStorageUtil.uploadStream(timeDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json"));
respDataResult.setTimeData(timeDataPath);
//用户每时刻对应的责任数据
JSONArray customerDataJson = JSONArray.parseArray(JSON.toJSONString(customerData));
InputStream customerStream = IoUtil.toUtf8Stream(customerDataJson.toString());
String customerPath = fileStorageUtil.uploadStream(customerStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json"));
respDataResult.setUserDetailData(customerPath);
//用户前10数据存储
JSONArray customerResJson = JSONArray.parseArray(JSON.toJSONString(customerResponsibilities));
InputStream customerResStream = IoUtil.toUtf8Stream(customerResJson.toString());
String customerResPath = fileStorageUtil.uploadStream(customerResStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json"));
respDataResult.setUserResponsibility(customerResPath);
respDataResultService.save(respDataResult);
}
//防止过程中创建了大量的对象主动调用下GC处理
System.gc();
result.setResponsibilityDataIndex(responsibilityData.getId());
return result;
}
/**
* 监测点测量间隔获取最后用于计算的功率数据

View File

@@ -0,0 +1,56 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10211
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
server-addr: @nacos.url@
namespace: @nacos.namespace@
config:
username: @nacos.username@
password: @nacos.password@
server-addr: @nacos.url@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-id: share-config-datasource-db.yaml
refresh: true
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
main:
allow-bean-definition-overriding: true
#项目日志的配置
logging:
config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.advance.pojo

View File

@@ -0,0 +1,61 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10211
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
ip: @service.server.url@
server-addr: @nacos.url@
username: @nacos.username@
password: @nacos.password@
namespace: @nacos.namespace@
config:
server-addr: @nacos.url@
username: @nacos.username@
password: @nacos.password@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-id: share-config-datasource-db.yaml
refresh: true
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
main:
allow-bean-definition-overriding: true
#项目日志的配置
logging:
#config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.advance.pojo
mqtt:
client-id: @artifactId@${random.value}

View File

@@ -1,57 +1,3 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10211
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
ip: @service.server.url@
server-addr: @nacos.url@
namespace: @nacos.namespace@
config:
server-addr: @nacos.url@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-Id: share-config-datasource-db.yaml
refresh: true
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
main:
allow-bean-definition-overriding: true
#项目日志的配置
logging:
config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.advance.pojo
mqtt:
client-id: @artifactId@${random.value}
profiles:
active: sjzx

View File

@@ -0,0 +1,52 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10214
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
server-addr: @nacos.url@
namespace: @nacos.namespace@
config:
username: @nacos.username@
password: @nacos.password@
server-addr: @nacos.url@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-id: share-config-datasource-db.yaml
refresh: true
main:
allow-bean-definition-overriding: true
#项目日志的配置
logging:
config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.user.pojo

View File

@@ -0,0 +1,57 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10214
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
ip: @service.server.url@
server-addr: @nacos.url@
username: @nacos.username@
password: @nacos.password@
namespace: @nacos.namespace@
config:
server-addr: @nacos.url@
username: @nacos.username@
password: @nacos.password@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-id: share-config-datasource-db.yaml
refresh: true
main:
allow-bean-definition-overriding: true
#项目日志的配置
logging:
#config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.user.pojo
mqtt:
client-id: @artifactId@${random.value}

View File

@@ -1,53 +1,3 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10214
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
ip: @service.server.url@
server-addr: @nacos.url@
namespace: @nacos.namespace@
config:
server-addr: @nacos.url@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-Id: share-config-datasource-db.yaml
refresh: true
main:
allow-bean-definition-overriding: true
#项目日志的配置
logging:
config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.user.pojo
mqtt:
client-id: @artifactId@${random.value}
profiles:
active: @spring.profiles.active@

View File

@@ -88,7 +88,7 @@ public class BpmSignParam extends BaseEntity implements Serializable {
private String name;
@ApiModelProperty("标识key")
private String key;
private String signKey;
}

View File

@@ -14,7 +14,6 @@ import org.springframework.context.annotation.DependsOn;
* @date 2022/11/10
*/
@Slf4j
@DependsOn("proxyMapperRegister")
@MapperScan("com.njcn.**.mapper")
@EnableFeignClients(basePackages = "com.njcn")
@SpringBootApplication(scanBasePackages = "com.njcn")

View File

@@ -67,8 +67,8 @@ public class BpmCategoryServiceImpl extends ServiceImpl<BpmCategoryMapper, BpmCa
@Override
public Page<BpmCategoryVO> getCategoryPage(BpmCategoryParam.BpmCategoryQueryParam bpmCategoryQueryParam) {
QueryWrapper<BpmCategoryVO> categoryVOQueryWrapper = new QueryWrapper<>();
if (StrUtil.isNotBlank(bpmCategoryQueryParam.getName())) {
categoryVOQueryWrapper.like("bpm_category.name", bpmCategoryQueryParam.getName());
if (StrUtil.isNotBlank(bpmCategoryQueryParam.getSearchValue())) {
categoryVOQueryWrapper.like("bpm_category.name", bpmCategoryQueryParam.getSearchValue());
}
if (StrUtil.isNotBlank(bpmCategoryQueryParam.getCode())) {

View File

@@ -106,8 +106,8 @@ public class BpmSignServiceImpl extends ServiceImpl<BpmSignMapper, BpmSign> impl
bpmSignVOQueryWrapper.like("bpm_sign.name", bpmSignQueryParam.getName());
}
if (StrUtil.isNotBlank(bpmSignQueryParam.getKey())) {
bpmSignVOQueryWrapper.like("bpm_sign.signKey", bpmSignQueryParam.getKey());
if (StrUtil.isNotBlank(bpmSignQueryParam.getSignKey())) {
bpmSignVOQueryWrapper.like("bpm_sign.sign_key", bpmSignQueryParam.getSignKey());
}
bpmSignVOQueryWrapper.eq("bpm_sign.state", DataStateEnum.ENABLE.getCode());
bpmSignVOQueryWrapper.orderByAsc("bpm_sign.sort");

View File

@@ -0,0 +1,71 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10321
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Shanghai
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
server-addr: @nacos.url@
namespace: @nacos.namespace@
config:
username: @nacos.username@
password: @nacos.password@
server-addr: @nacos.url@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-id: share-config-datasource-db.yaml
refresh: true
main:
allow-bean-definition-overriding: true
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
flowable:
database-schema-update: false
db-history-used: true # flowable6 默认 true 生成信息表,无需手动设置
check-process-definitions: false # 设置为 false禁用 /resources/processes 自动部署 BPMN XML 流程
history-level: full # full保存历史数据的最高级别可保存全部流程相关细节包括流程流转各节点参数
async-executor-activate: false
#项目日志的配置
logging:
config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
type-aliases-package: com.njcn.bpm.pojo
gw:
url: dwzyywzt-pms3-proxy.com
code: 13B9B47F1E483324E05338297A0A0595

View File

@@ -0,0 +1,76 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10321
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Shanghai
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
ip: @service.server.url@
server-addr: @nacos.url@
username: @nacos.username@
password: @nacos.password@
namespace: @nacos.namespace@
config:
server-addr: @nacos.url@
namespace: @nacos.namespace@
username: @nacos.username@
password: @nacos.password@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-id: bpm-config.yaml
refresh: true
main:
allow-bean-definition-overriding: true
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
flowable:
database-schema-update: false
db-history-used: true # flowable6 默认 true 生成信息表,无需手动设置
check-process-definitions: false # 设置为 false禁用 /resources/processes 自动部署 BPMN XML 流程
history-level: full # full保存历史数据的最高级别可保存全部流程相关细节包括流程流转各节点参数
async-executor-activate: false
#项目日志的配置
logging:
#config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
type-aliases-package: com.njcn.bpm.pojo
gw:
url: dwzyywzt-pms3-proxy.com
code: 13B9B47F1E483324E05338297A0A0595
mqtt:
client-id: @artifactId@${random.value}

View File

@@ -1,72 +1,3 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10321
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Shanghai
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
ip: @service.server.url@
server-addr: @nacos.url@
namespace: @nacos.namespace@
config:
server-addr: @nacos.url@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-Id: bpm-config.yaml
refresh: true
main:
allow-bean-definition-overriding: true
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
flowable:
database-schema-update: false
db-history-used: true # flowable6 默认 true 生成信息表,无需手动设置
check-process-definitions: false # 设置为 false禁用 /resources/processes 自动部署 BPMN XML 流程
history-level: full # full保存历史数据的最高级别可保存全部流程相关细节包括流程流转各节点参数
async-executor-activate: false
#项目日志的配置
logging:
config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
type-aliases-package: com.njcn.bpm.pojo
gw:
url: dwzyywzt-pms3-proxy.com
code: 13B9B47F1E483324E05338297A0A0595
mqtt:
client-id: @artifactId@${random.value}
profiles:
active: @spring.profiles.active@

View File

@@ -75,9 +75,9 @@ public interface PatternRegex {
String ROLE_REGEX = "^[a-zA-Z][a-zA-Z0-9]{2,50}$";
/**
* 部门名称由汉字组成长度为0-20
* 部门名称由汉字组成长度为0-32 前端统一32了这边改下长度
*/
String DEPT_NAME_REGEX = "^[\\u4e00-\\u9fa5]{1,20}$";
String DEPT_NAME_REGEX = "^[\\u4e00-\\u9fa5]{1,32}$";
/**
* 字典名称包括中文、数字、字母、罗马数字、括号以及点号
@@ -258,7 +258,7 @@ public interface PatternRegex {
/**
* 任意字符长度在1-20位常用于名称、编码等常规录入
*/
String ALL_CHAR_1_20 = "^[-_A-Za-z0-9\\u4e00-\\u9fa5]{1,20}$";
String ALL_CHAR_1_20 = "^[-_A-Za-z0-9\\u4e00-\\u9fa5]{1,32}$";
String SPECIALCHARACTER ="[<>%'%;()&+/\\\\-\\\\\\\\_|@*?#$!,.]|html";

View File

@@ -25,6 +25,12 @@ public class SimpleDTO implements Serializable {
@ApiModelProperty(name = "value", value = "数值")
private String value;
/**
* 针对云南曲靖特殊处理的五层树标识符
* 特殊在不显示供电公司,显示(变电站、线路)这两个是部门的名称+母线_监测点的名称
*/
private String deptName;
private Integer sort;
private Integer algoDescribe;

View File

@@ -57,6 +57,11 @@
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--vastbase驱动用postgresql-->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!--达梦驱动-->
<dependency>
<groupId>com.dameng</groupId>
@@ -69,6 +74,12 @@
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!--数据库相关********end-->
</dependencies>

View File

@@ -33,6 +33,8 @@ public class PieGenerator {
Option reasonOption = new Option();
//取消渲染动画
reasonOption.setAnimation(false);
String[] colorArr = {"#526ADE", "#00BFF5","#FFBF00","#77DA63","#D5FF6B"};
reasonOption.setColor(colorArr);
//背景色
reasonOption.setBackgroundColor(PicCommonData.PIC_BACK_COLOR);
//标题

View File

@@ -25,7 +25,7 @@ public class BusinessDataUtil {
List<List<Double>> unTolerateData = new ArrayList<>();
for (List<Double> list : originData) {
//是否超过上限
if (list.get(0) <= 0.03) {
if (list.get(0) <= 0.003) {
int line = 230 - 30000 * list.get(0).intValue();
if (list.get(1) > line) {
unTolerateData.add(list);

View File

@@ -432,7 +432,7 @@ public class WaveFileComponent {
rateDTO.setNOneSample(result);
// 总点数 //这里的strTemp是一个偏移量
rateDTO.setNSampleNum((Integer.parseInt(strTempArray[1]) - nOffset));
nOffset = rateDTO.getNSampleNum();
nOffset += rateDTO.getNSampleNum();
lstRate.add(rateDTO);
}
comtradeCfgDTO.setLstRate(lstRate);
@@ -497,7 +497,7 @@ public class WaveFileComponent {
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 = datArray.length / nBlockSize;
int nBlockNum = (int)Math.floor(datArray.length / nBlockSize);
// 获取采样率
int finalSampleRate = getFinalWaveSample(comtradeCfgDTO.getLstRate(), iType);
@@ -612,6 +612,9 @@ public class WaveFileComponent {
}
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;
//WW 2019-11-14
/*************************
@@ -767,6 +770,7 @@ public class WaveFileComponent {
}
}
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(WaveFileResponseEnum.DAT_DATA_ERROR);
}

View File

@@ -1,5 +1,7 @@
package com.njcn.microservice.listener;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import org.slf4j.LoggerFactory;
@@ -34,33 +36,46 @@ public class NacosLogbackConfigLoader implements SpringApplicationRunListener, A
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
// String serverAddr = environment.getProperty("spring.cloud.nacos.config.server-addr");
// String namespace = environment.getProperty("spring.cloud.nacos.config.namespace");
// String projectName = environment.getProperty("microservice.ename");
// String logLevel = environment.getProperty("logging.level.root");
// String url = String.format("http://%s/nacos/v1/cs/configs?tenant=%s&group=DEFAULT_GROUP&dataId=logback.xml", serverAddr, namespace);
// HttpHeaders headers = new HttpHeaders();
// headers.set("cndl408125hawen", "lanxia201");
// HttpEntity<String> entity = new HttpEntity<>(headers);
// RestTemplate restTemplate = new RestTemplate();
// ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
// if (response.getStatusCode().is2xxSuccessful()) {
// String logbackConfigContent = response.getBody();
// //替换项目名称
// logbackConfigContent = logbackConfigContent.replace("projectDefaultName",projectName);
// logbackConfigContent = logbackConfigContent.replace("logDefaultLevel",logLevel);
// // 应用获取到的Logback配置
// applyLogbackConfig(logbackConfigContent);
// }
String active = environment.getProperty("spring.profiles.active");
if(!"jb".equalsIgnoreCase(active)){
String serverAddr = environment.getProperty("spring.cloud.nacos.config.server-addr");
String namespace = environment.getProperty("spring.cloud.nacos.config.namespace");
String projectName = environment.getProperty("microservice.ename");
String logLevel = environment.getProperty("logging.level.root");
String url = String.format("http://%s/nacos/v1/cs/configs?tenant=%s&group=DEFAULT_GROUP&dataId=logback.xml", serverAddr, namespace);
HttpHeaders headers = new HttpHeaders();
headers.set("cndl408125hawen", "lanxia201");
HttpEntity<String> entity = new HttpEntity<>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
String logbackConfigContent = response.getBody();
//替换项目名称
logbackConfigContent = logbackConfigContent.replace("projectDefaultName",projectName);
logbackConfigContent = logbackConfigContent.replace("logDefaultLevel",logLevel);
// 应用获取到的Logback配置
applyLogbackConfig(logbackConfigContent,logLevel);
}
}
}
private void applyLogbackConfig(String logbackConfigContent) {
private void applyLogbackConfig(String logbackConfigContent,String logLevel) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(logbackConfigContent.getBytes(StandardCharsets.UTF_8))) {
configurator.doConfigure(inputStream);
Logger root = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
if("debug".equalsIgnoreCase(logLevel)){
root.setLevel(Level.DEBUG);
}
if("info".equalsIgnoreCase(logLevel)){
root.setLevel(Level.INFO);
}
if("error".equalsIgnoreCase(logLevel)){
root.setLevel(Level.ERROR);
}
} catch (Exception e) {
e.printStackTrace();
}

View File

@@ -30,7 +30,52 @@ public interface BusinessTopic {
String NJCN_APP_FILE_STREAM_TOPIC = "njcnAppFileStreamTopic";
/**
* 云前置主题
*/
String CLD_ASK_REAL_DATA_TOPIC = "ask_real_data_Topic";
String CLD_HANDLE_REAL_DATA_TOPIC = "Real_Time_Data_Topic";
/**
* 云前置心跳主题
*/
String HEART_BEAT_TOPIC = "Heart_Beat_Topic";
/**
* 云前置状态反转主题
*/
String DEVICE_RUN_FLAG_TOPIC = "Device_Run_Flag_Topic";
/**
* 云前置日志主题
*/
String LOG_TOPIC = "log_Topic";
/**
* 台账更新下发
*/
String CONTROL_TOPIC = "control_Topic";
/**
* 台账更新前置端响应
*/
String REPLY_TOPIC = "Reply_Topic";
/**
* 前置进程控制
*/
String PROCESS_TOPIC = "process_Topic";
/**
* 补召下发命令
*/
String ASK_RECALL_TOPIC = "ask_recall_Topic";
/**
* 补召应答命令
*/
String REPLY_RECALL_TOPIC = "reply_recall_Topic";
/********************************数据中心*********************************/
@@ -79,5 +124,4 @@ public interface BusinessTopic {
String STREAM_TAG = "streamInfo";
}
}

View File

@@ -28,14 +28,14 @@ public class AppFileMessage extends BaseMessage {
private Integer code;
private AppFileMessage.Msg msg;
private Msg msg;
@Data
public static class Msg{
private String type;
private AppFileMessage.FileInfo fileInfo;
private FileInfo fileInfo;
private String data;

View File

@@ -0,0 +1,59 @@
package com.njcn.mq.message;
import com.njcn.middle.rocket.domain.BaseMessage;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* @author xy
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class BZEventMessage extends BaseMessage {
//补召事件
@Data
public static class Event{
@ApiModelProperty("请求的guid")
private String guid;
@ApiModelProperty("终端id")
private String terminalId;
@ApiModelProperty("监测点id")
private List<String> monitorIdList;
@ApiModelProperty("数据类型 0 稳态 1 暂态事件 2 暂态波形")
private Integer dataType;
@ApiModelProperty("时间范围")
private List<String> timeInterval;
}
//补召波形
@Data
public static class File{
@ApiModelProperty("请求的guid")
private String guid;
@ApiModelProperty("终端id")
private String terminalId;
@ApiModelProperty("监测点id")
private String monitorId;
@ApiModelProperty("数据类型 0 稳态 1 暂态事件 2 暂态波形")
private Integer dataType;
@ApiModelProperty("缺失波形时标集合")
private List<String> timeList;
}
}

View File

@@ -0,0 +1,53 @@
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 BzMessage extends BaseMessage {
@ApiModelProperty("唯一标识")
private String guid;
@ApiModelProperty("补召类型")
private String dataType;
@ApiModelProperty("响应码")
private Integer code;
@ApiModelProperty("结果")
private String result;
@ApiModelProperty("设备id")
private String terminalId;
@ApiModelProperty("监测点id")
private String monitorId;
@ApiModelProperty("补召起始时间")
private String recallStartDate;
@ApiModelProperty("补召结束时间")
private String recallEndDate;
@ApiModelProperty("前置服务器id")
private String nodeId;
@ApiModelProperty("前置进程")
private String processNo;
}

View File

@@ -0,0 +1,38 @@
package com.njcn.mq.message;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 类的介绍:日志信息
*
* @author xuyang
* @version 1.0.0
* @createTime 2025/9/18 15:06
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CldControlMessage {
@ApiModelProperty("请求的guid")
private String guid;
@ApiModelProperty("功能代号")
private String code;
@ApiModelProperty("前置服务器id")
private String nodeId;
@ApiModelProperty("指定处理的进程号")
private Integer processNo;
@ApiModelProperty("delete用于杀死进程")
private String fun;
@ApiModelProperty("进程数")
private Integer processNum;
}

View File

@@ -0,0 +1,31 @@
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 2023/8/11 15:06
*/
@Data
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
public class CldDeviceRunFlagMessage extends BaseMessage {
@ApiModelProperty("设备id")
private String id;
@ApiModelProperty("前置类型")
private String date;
@ApiModelProperty("状态 0:中断 1:连接")
private String status;
}

View File

@@ -0,0 +1,35 @@
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 2023/8/11 15:06
*/
@Data
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
public class CldHeartBeatMessage extends BaseMessage {
@ApiModelProperty("前置类型")
private String frontType;
@ApiModelProperty("前置id")
private String nodeId;
@ApiModelProperty("进程id")
private Integer processNo;
@ApiModelProperty("状态")
private String status;
}

View File

@@ -0,0 +1,47 @@
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/18 15:06
*/
@Data
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
public class CldLogMessage extends BaseMessage {
@ApiModelProperty("前置id")
private String nodeId;
@ApiModelProperty("进程id")
private String processNo;
@ApiModelProperty("监测点id、装置id")
private String businessId;
@ApiModelProperty("级别(process进程、terminal装置、measurepoint监测点)")
private String level;
@ApiModelProperty("日志等级")
private String grade;
@ApiModelProperty("告警码")
private String code;
@ApiModelProperty("告警时间")
private String time;
@ApiModelProperty("日志信息")
private String log;
}

View File

@@ -0,0 +1,93 @@
package com.njcn.mq.message;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* cld设备更新台账实体
* @author xy
*/
@Data
public class CldUpdateLedgerMessage implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("消息唯一标识")
private String guid;
@ApiModelProperty("add_terminal/delete_terminal/ledger_modify")
private String code;
@ApiModelProperty("进程号")
private Integer processNo;
@ApiModelProperty("数据")
private List<CldDeviceDto> data;
@Data
public static class CldDeviceDto implements Serializable {
@ApiModelProperty("最大进程数")
private Integer maxProcessNum;
@ApiModelProperty("进程号")
private Integer node;
@ApiModelProperty("设备id")
private String id;
@ApiModelProperty("设备MAC")
private String ip;
@ApiModelProperty("设备型号")
private String devType;
@ApiModelProperty("设备名称")
private String name;
@ApiModelProperty("监测点信息集合")
private List<CldMonitorDto> monitorData;
}
@Data
public static class CldMonitorDto implements Serializable {
@ApiModelProperty("监测点id")
private String id;
@ApiModelProperty("监测点名称")
private String name;
@ApiModelProperty("监测点线路号")
private String lineNo;
@ApiModelProperty("电压等级")
private String voltageLevel;
@ApiModelProperty("status")
private Integer status;
@ApiModelProperty("接线方式")
private String ptType;
@ApiModelProperty("设备id")
private String deviceId;
@ApiModelProperty("pt一次变比")
private Double pt1;
@ApiModelProperty("pt二次变比")
private Double pt2;
@ApiModelProperty("ct一次变比")
private Double ct1;
@ApiModelProperty("ct二次变比")
private Double ct2;
}
}

View File

@@ -0,0 +1,41 @@
package com.njcn.mq.message;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 类的介绍:
*
* @author xuyang
* @version 1.0.0
* @createTime 2023/8/11 15:06
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RealDataMessage {
@ApiModelProperty("终端序号")
private String devSeries;
@ApiModelProperty("监测点序号")
private Integer line;
@ApiModelProperty("实时数据开启/关闭")
private Boolean realData;
@ApiModelProperty("Soe开启/关闭")
private Boolean soeData;
@ApiModelProperty("限制")
private Integer limit;
@ApiModelProperty("限制")
private Integer count;
@ApiModelProperty("idx")
private Integer idx;
}

View File

@@ -0,0 +1,45 @@
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;
import java.io.Serializable;
import java.util.List;
/**
* 类的介绍:
*
* @author xuyang
* @version 1.0.0
* @createTime 2025/9/29 15:06
*/
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UpdateLedgerMessage extends BaseMessage {
@ApiModelProperty("唯一标识")
private String guid;
@ApiModelProperty("数据")
private List<HandleData> data;
@Data
public static class HandleData implements Serializable {
@ApiModelProperty("设备id")
private String deviceId;
@ApiModelProperty("响应码")
private Integer code;
@ApiModelProperty("结果描述")
private String result;
}
}

View File

@@ -0,0 +1,31 @@
package com.njcn.mq.template;
import com.alibaba.fastjson.JSON;
import com.njcn.middle.rocket.domain.BaseMessage;
import com.njcn.middle.rocket.template.RocketMQEnhanceTemplate;
import com.njcn.mq.constant.BusinessResource;
import com.njcn.mq.constant.BusinessTopic;
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 BZEventMessageTemplate extends RocketMQEnhanceTemplate {
public BZEventMessageTemplate(RocketMQTemplate template) {
super(template);
}
public SendResult sendMember(Object message, String tag) {
BaseMessage baseMessage = new BaseMessage();
baseMessage.setSource(BusinessResource.WEB_RESOURCE);
baseMessage.setMessageBody(JSON.toJSONString(message));
return send(BusinessTopic.ASK_RECALL_TOPIC,tag,baseMessage);
}
}

View File

@@ -0,0 +1,33 @@
package com.njcn.mq.template;
import com.google.gson.Gson;
import com.njcn.middle.rocket.domain.BaseMessage;
import com.njcn.middle.rocket.template.RocketMQEnhanceTemplate;
import com.njcn.mq.constant.BusinessResource;
import com.njcn.mq.constant.BusinessTopic;
import com.njcn.mq.message.CldControlMessage;
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 CldControlMessageTemplate extends RocketMQEnhanceTemplate {
public CldControlMessageTemplate(RocketMQTemplate template) {
super(template);
}
public SendResult sendMember(CldControlMessage message, String tag) {
BaseMessage baseMessage = new BaseMessage();
baseMessage.setSource(BusinessResource.WEB_RESOURCE);
baseMessage.setMessageBody(new Gson().toJson(message));
return send(BusinessTopic.PROCESS_TOPIC,tag,baseMessage);
}
}

View File

@@ -0,0 +1,33 @@
package com.njcn.mq.template;
import com.google.gson.Gson;
import com.njcn.middle.rocket.domain.BaseMessage;
import com.njcn.middle.rocket.template.RocketMQEnhanceTemplate;
import com.njcn.mq.constant.BusinessResource;
import com.njcn.mq.constant.BusinessTopic;
import com.njcn.mq.message.CldUpdateLedgerMessage;
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 CldUpdateLedgerMessageTemplate extends RocketMQEnhanceTemplate {
public CldUpdateLedgerMessageTemplate(RocketMQTemplate template) {
super(template);
}
public SendResult sendMember(CldUpdateLedgerMessage cldUpdateLedgerMessage, String tag) {
BaseMessage baseMessage = new BaseMessage();
baseMessage.setSource(BusinessResource.WEB_RESOURCE);
baseMessage.setMessageBody(new Gson().toJson(cldUpdateLedgerMessage));
return send(BusinessTopic.CONTROL_TOPIC,tag,baseMessage);
}
}

View File

@@ -0,0 +1,33 @@
package com.njcn.mq.template;
import com.google.gson.Gson;
import com.njcn.middle.rocket.domain.BaseMessage;
import com.njcn.middle.rocket.template.RocketMQEnhanceTemplate;
import com.njcn.mq.constant.BusinessResource;
import com.njcn.mq.constant.BusinessTopic;
import com.njcn.mq.message.RealDataMessage;
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 RealDataMessageTemplate extends RocketMQEnhanceTemplate {
public RealDataMessageTemplate(RocketMQTemplate template) {
super(template);
}
public SendResult sendMember(RealDataMessage realDataMessage,String tag) {
BaseMessage baseMessage = new BaseMessage();
baseMessage.setSource(BusinessResource.WEB_RESOURCE);
baseMessage.setMessageBody(new Gson().toJson(realDataMessage));
return send(BusinessTopic.CLD_ASK_REAL_DATA_TOPIC,tag,baseMessage);
}
}

View File

@@ -48,6 +48,28 @@
<artifactId>minioss-springboot-starter</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.njcn</groupId>
<artifactId>aliyun-oss-springboot-starter</artifactId>
<version>1.0.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.18.0</version>
<optional>false</optional>
</dependency>
</dependencies>
</project>

View File

@@ -13,6 +13,7 @@ public interface GeneralConstant {
Integer LOCAL_DISK = 1;
Integer HUAWEI_OBS = 2;
Integer MINIO_OSS = 3;
Integer AliYUN_OSS = 4;
/***
* 波形文件的3种后缀

View File

@@ -12,6 +12,8 @@ public interface OssPath {
*/
String WAVE_DIR="comtrade/";
String WAVE_FILE="wave/";
/***
* 下载文件
*/
@@ -167,4 +169,14 @@ public interface OssPath {
*/
String CONFIGURATIONNAME = "configuration.json";
/**
* APP 稳态报告路径
*/
String APP_HARMONIC_REPORT = "app/report/harmonic/";
/**
* APP 暂态报告路径
*/
String APP_EVENT_REPORT = "app/report/event/";
}

View File

@@ -1,7 +1,8 @@
package com.njcn.oss.utils;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.njcn.ali.oss.util.AliYunOssUtils;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.huawei.obs.util.OBSUtil;
@@ -12,7 +13,6 @@ import com.njcn.oss.constant.GeneralConstant;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.enums.OssResponseEnum;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -65,6 +65,11 @@ public class FileStorageUtil {
private final MinIossProperties minIossProperties;
/**
* 阿里云文件服务器
*/
private final AliYunOssUtils aliYunOssUtils;
/***
* 上传MultipartFile文件
@@ -78,7 +83,7 @@ public class FileStorageUtil {
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
filePath = dir + minIoUtils.minFileName(multipartFile.getOriginalFilename());
obsUtil.uploadMultipart(multipartFile, filePath);
} else if(generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS){
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS) {
try {
//把名称存入数据
MinIoUploadResDTO minIoUploadResDTO = minIoUtils.upload(multipartFile, minIossProperties.getBucket(), dir);
@@ -86,18 +91,29 @@ public class FileStorageUtil {
} catch (Exception e) {
throw new BusinessException(OssResponseEnum.UPLOAD_FILE_ERROR);
}
}else {
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
filePath = dir;
aliYunOssUtils.uploadFile(dir, multipartFile);
} else {
try {
// 确保目录存在
Path uploadPath = Paths.get(generalInfo.getLocalStorePath());
// 构建完整目录:基准目录 + dir子目录
Path basePath = Paths.get(generalInfo.getLocalStorePath());
// 将dir作为子目录添加
Path uploadPath = basePath.resolve(dir);
// 确保完整目录存在包括dir子目录
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// 生成本地文件名(可以添加时间戳或UUID防止重名
// 生成本地文件名(处理扩展名,防止异常
String originalFilename = multipartFile.getOriginalFilename();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String newFilename = UUID.randomUUID().toString() + fileExtension;
String fileExtension = "";
int extIndex = originalFilename.lastIndexOf(".");
if (extIndex > 0 && extIndex < originalFilename.length() - 1) {
fileExtension = originalFilename.substring(extIndex);
}
String newFilename = IdUtil.simpleUUID().toUpperCase() + fileExtension;
// 构建完整路径
Path filePathPath = uploadPath.resolve(newFilename);
@@ -105,7 +121,7 @@ public class FileStorageUtil {
// 保存文件
multipartFile.transferTo(filePathPath.toFile());
// 返回相对路径或完整路径,根据需求调整
// 返回相对路径或完整路径
filePath = dir + File.separator + newFilename;
} catch (IOException e) {
throw new BusinessException("本地文件上传失败: " + e.getMessage());
@@ -127,6 +143,9 @@ public class FileStorageUtil {
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
filePath = dir + minIoUtils.minFileName(multipartFile.getOriginalFilename());
obsUtil.uploadMultipart(multipartFile, filePath);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
filePath = dir;
aliYunOssUtils.uploadFile(dir, multipartFile);
} else {
try {
//把名称存入数据
@@ -152,7 +171,7 @@ public class FileStorageUtil {
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
filePath = dir + minIoUtils.minFileName(fileName);
obsUtil.uploadStream(inputStream, filePath);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS){
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS) {
try {
//把名称存入数据
MinIoUploadResDTO minIoUploadResDTO = minIoUtils.uploadStream(inputStream, minIossProperties.getBucket(), dir, minIoUtils.minFileName(fileName));
@@ -160,14 +179,17 @@ public class FileStorageUtil {
} catch (Exception e) {
throw new BusinessException(OssResponseEnum.UPLOAD_FILE_ERROR);
}
}else {
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
filePath = dir + fileName;
aliYunOssUtils.uploadFile(filePath, inputStream);
} else {
// 本地存储逻辑
try {
// 1. 获取本地存储路径
String localStoragePath = generalInfo.getLocalStorePath();
// 2. 确保目录存在(如果不存在则创建)
File targetDir = new File(localStoragePath +File.separator+ dir);
File targetDir = new File(localStoragePath + File.separator + dir);
if (!targetDir.exists()) {
boolean created = targetDir.mkdirs();
if (!created) {
@@ -185,7 +207,7 @@ public class FileStorageUtil {
// 5. 返回相对路径
filePath = dir + finalFileName;
} catch (IOException e) {
throw new BusinessException(OssResponseEnum.UPLOAD_FILE_ERROR,e.getMessage());
throw new BusinessException(OssResponseEnum.UPLOAD_FILE_ERROR, e.getMessage());
}
}
return filePath;
@@ -201,6 +223,9 @@ public class FileStorageUtil {
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
filePath = dir + minIoUtils.minFileName(fileName);
obsUtil.uploadStream(inputStream, filePath);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
filePath = dir + fileName;
aliYunOssUtils.uploadFile(filePath, inputStream);
} else {
try {
//把名称存入数据
@@ -224,6 +249,8 @@ public class FileStorageUtil {
String url;
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
url = obsUtil.getFileUrl(filePath);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
url = aliYunOssUtils.generatePresignedUrl(filePath, 3600);
} else {
url = minIoUtils.getObjectUrl(minIossProperties.getBucket(), filePath, 7 * 24 * 60 * 60);
}
@@ -242,10 +269,12 @@ public class FileStorageUtil {
try {
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
inputStream = obsUtil.downloadStream(filePath);
} else if(generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS) {
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS) {
inputStream = minIoUtils.downloadStream(minIossProperties.getBucket(), filePath);
}else {
Path path = Paths.get(generalInfo.getLocalStorePath()+File.separator+filePath);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
inputStream = aliYunOssUtils.downloadStream(filePath);
} else {
Path path = Paths.get(generalInfo.getLocalStorePath() + File.separator + filePath);
inputStream = Files.newInputStream(path);
}
} catch (Exception exception) {
@@ -266,12 +295,13 @@ public class FileStorageUtil {
try {
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
inputStream = obsUtil.downloadStream(filePath);
} else if(generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS){
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS) {
inputStream = minIoUtils.downloadStream(minIossProperties.getBucket(), filePath);
}else {
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
inputStream = aliYunOssUtils.downloadStream(filePath);
} else {
// 本地存储处理
Path path = Paths.get(generalInfo.getLocalStorePath()+File.separator+filePath);
System.out.println("下载文件路径:"+generalInfo.getLocalStorePath()+File.separator+filePath);
Path path = Paths.get(generalInfo.getLocalStorePath() + File.separator + filePath);
inputStream = Files.newInputStream(path);
// 设置下载文件名(从路径中提取)
@@ -324,8 +354,17 @@ public class FileStorageUtil {
public void deleteFile(String fileName) {
if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
obsUtil.delete(fileName);
} else {
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.MINIO_OSS) {
minIoUtils.removeObject(minIossProperties.getBucket(), fileName);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
aliYunOssUtils.deleteFile(fileName);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.LOCAL_DISK) {
Path path = Paths.get(generalInfo.getLocalStorePath() + File.separator + fileName);
try {
Files.delete(path);
} catch (IOException e) {
log.info("删除本地文件{}失败失败原因{}", path, e.getMessage());
}
}
}
@@ -395,9 +434,10 @@ public class FileStorageUtil {
file = File.createTempFile(lastItem.objectName(), "xlsx");
FileUtil.writeFromStream(stream, file);
}else if(generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS){
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.HUAWEI_OBS) {
file = obsUtil.getLastFile(OssPath.LOGBAK);
} else if (generalInfo.getBusinessFileStorage() == GeneralConstant.AliYUN_OSS) {
file = aliYunOssUtils.getLastFile(directory);
}
return file;
}

View File

@@ -40,7 +40,27 @@ public enum RedisKeyEnum {
/***
* 存放用户的角色关系
*/
USER_ROLE_TYPE_KEY("USER_ROLE_TYPE_KEY", -1L);
USER_ROLE_TYPE_KEY("USER_ROLE_TYPE_KEY", -1L),
/**
* 云前置心跳
*/
CLD_HEART_BEAT_KEY("CLD_HEART_BEAT:", 180L),
/**
* 用户日志队列
*/
USER_LOG_QUEUE("USER_LOG_QUEUE", -1L),
/**
* 用户日志邮件推送队列
*/
USER_LOG_EMAIL_QUEUE("USER_LOG_EMAIL_QUEUE", -1L),
/**
* 终端日志
*/
DEVICE_LOG_QUEUE("DEVICE_LOG_QUEUE", -1L);
private final String key;

View File

@@ -0,0 +1,66 @@
package com.njcn.redis.utils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Redis 消息队列工具类
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class RedisMessageQueueUtil {
private final RedisTemplate<String, Object> redisTemplate;
/**
* 推送消息到队列(左推)
*
* @param queueKey 队列Key
* @param message 消息内容JSON字符串
*/
public void pushMessage(String queueKey, String message) {
try {
redisTemplate.opsForList().leftPush(queueKey, message);
} catch (Exception e) {
log.error("推送消息到队列失败queueKey={}", queueKey, e);
throw e;
}
}
/**
* 阻塞式弹出消息(右弹)
*
* @param queueKey 队列Key
* @param timeout 超时时间(秒)
* @return 消息内容超时返回null
*/
public String popMessage(String queueKey, long timeout) {
try {
Object result = redisTemplate.opsForList().rightPop(queueKey, timeout, TimeUnit.SECONDS);
return result != null ? result.toString() : null;
} catch (Exception e) {
log.error("弹出消息失败queueKey={}", queueKey, e);
return null;
}
}
/**
* 获取队列长度(用于监控)
*
* @param queueKey 队列Key
* @return 队列长度
*/
public Long getQueueSize(String queueKey) {
try {
return redisTemplate.opsForList().size(queueKey);
} catch (Exception e) {
log.error("获取队列长度失败queueKey={}", queueKey, e);
return 0L;
}
}
}

View File

@@ -45,6 +45,9 @@ public class Knife4jSwaggerConfig {
@Value("${microservice.gateway.url}")
private String gatewayUrl;
@Value("${swagger.enable:true}")
private Boolean swaggerEnable;
/**
* swagger通用配置
*/
@@ -56,6 +59,7 @@ public class Knife4jSwaggerConfig {
"com.njcn.prepare.harmonic.controller",
"com.njcn.prepare.event.controller",
"com.njcn.device.pq.controller",
"com.njcn.device.terminal.controller",
"com.njcn.device.pms.controller",
"com.njcn.auth.controller",
"com.njcn.system.controller",
@@ -71,6 +75,7 @@ public class Knife4jSwaggerConfig {
"com.njcn.cswarn.controller",
"com.njcn.csharmonic.controller",
"com.njcn.cssystem.controller",
"com.njcn.csreport.controller",
"com.njcn.advance.controller",
"com.njcn.stat.controller",
"com.njcn.rt.controller",
@@ -81,7 +86,11 @@ public class Knife4jSwaggerConfig {
"com.njcn.supervision.controller",
"com.njcn.algorithm",
"com.njcn.dataProcess",
"com.njcn.migration"
"com.njcn.migration",
"com.njcn.harmonic.rstatlimitrate.controller",
"com.njcn.device.device.controller",
"com.njcn.device.userledger.controller",
"com.njcn.migration.read.controller"
)
.collect(Collectors.toList());
List<GrantType> grantTypes = new ArrayList<>();
@@ -94,7 +103,7 @@ public class Knife4jSwaggerConfig {
//securyContext
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(true)
.enable(swaggerEnable)
.select()
// 指定添加swagger注解的方法
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

View File

@@ -47,6 +47,7 @@ public class FeignConfig {
@Bean
public Decoder feignDecoder() {
return (response, type) -> {
String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
//对结果进行转换
HttpResult<Object> result = PubUtils.json2obj(bodyStr, type);
@@ -60,6 +61,8 @@ public class FeignConfig {
}
switch (commonResponseEnum) {
case SUCCESS:
// case NO_DATA:
// case FAIL:
return result;
default:
throw new BusinessException(result);

View File

@@ -19,7 +19,7 @@ public interface ValidMessage {
String NAME_NOT_BLANK = "名称不能为空请检查name参数";
String NAME_FORMAT_ERROR = "名称格式错误存在特殊符号或超过20字符请检查name参数";
String NAME_FORMAT_ERROR = "名称格式错误,存在特殊符号或超过32字符请检查name参数";
String INDUSTRY_NOT_BLANK = "行业不能为空请检查industry参数";
String INDUSTRY_FORMAT_ERROR = "行业格式错误请检查industry参数";

View File

@@ -1,8 +1,6 @@
package com.njcn.web.service.impl;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.LogInfo;
import com.njcn.common.pojo.dto.DeviceLogDTO;
import com.njcn.common.pojo.dto.LogInfoDTO;
@@ -10,6 +8,8 @@ import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.PubUtils;
import com.njcn.common.utils.ReflectCommonUtil;
import com.njcn.redis.pojo.enums.RedisKeyEnum;
import com.njcn.redis.utils.RedisMessageQueueUtil;
import com.njcn.web.advice.DeviceLog;
import com.njcn.web.service.ILogService;
import com.njcn.web.utils.RequestUtil;
@@ -46,8 +46,15 @@ public class LogServiceImpl implements ILogService {
private final GeneralInfo generalInfo;
/**
* mqtt处理日志异步发布
*/
// private final MqttPublisher publisher;
private final MqttPublisher publisher;
/**
* redis队列处理日志异步发布
*/
private final RedisMessageQueueUtil redisMessageQueueUtil;
/**
@@ -82,14 +89,27 @@ public class LogServiceImpl implements ILogService {
String operateType = ReflectCommonUtil.getOperateTypeByMethod(returnType.getMethod());
Integer severity = levelStringToNumber(level);
LogInfoDTO logInfoDTO = new LogInfoDTO(loginName, userName, ip, methodDescribe, operateType, result.equalsIgnoreCase("失败") ? 0 : 1, "", severity, type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), userIndex, LocalDateTime.now());
publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 2, false);
// publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 2, false);
redisMessageQueueUtil.pushMessage(
RedisKeyEnum.USER_LOG_QUEUE.getKey(),
PubUtils.obj2json(logInfoDTO)
);
//推送审计消息功能
if (severity != 0) {
if (!logInfoDTO.getLoginName().equals(LogInfo.UNKNOWN_USER)) {
publisher.send("/userLogPush", PubUtils.obj2json(logInfoDTO), 2, false);
/**注意此处是给前端推送的如果没有了mqtt协议此处前端就无消息可消费了*/
// publisher.send("/userLogPush", PubUtils.obj2json(logInfoDTO), 2, false);
//发送邮箱功能
if (severity == 2 && logInfoDTO.getResult() == 0) {
//publisher.send("/userLogEmailPush", PubUtils.obj2json(logInfoDTO), 2, false);
// redisMessageQueueUtil.pushMessage(
// RedisKeyEnum.USER_LOG_EMAIL_QUEUE.getKey(),
// PubUtils.obj2json(logInfoDTO)
// );
}
}
}
@@ -97,8 +117,11 @@ public class LogServiceImpl implements ILogService {
if (Objects.nonNull((returnType.getMethod())) && (returnType.getMethod()).isAnnotationPresent(DeviceLog.class)) {
String deviceOperate = returnType.getMethod().getAnnotation(DeviceLog.class).operateType();
DeviceLogDTO deviceLogDTO = new DeviceLogDTO(userName, deviceOperate, result.equalsIgnoreCase("失败") ? 0 : 1, "", loginName, userIndex);
publisher.send("/deviceLog", PubUtils.obj2json(deviceLogDTO), 2, false);
// publisher.send("/deviceLog", PubUtils.obj2json(deviceLogDTO), 2, false);
redisMessageQueueUtil.pushMessage(
RedisKeyEnum.DEVICE_LOG_QUEUE.getKey(),
PubUtils.obj2json(deviceLogDTO)
);
}
}
@@ -135,7 +158,11 @@ public class LogServiceImpl implements ILogService {
String operateType = ReflectCommonUtil.getOperateTypeByMethod(method);
Integer severity = levelStringToNumber(level);
LogInfoDTO logInfoDTO = new LogInfoDTO(tempLogInfo.getLoginName(), tempLogInfo.getUserName(), tempLogInfo.getIp(), ReflectCommonUtil.getMethodDescribeByMethod(method), operateType, result.equalsIgnoreCase("失败") ? 0 : 1, message, severity, type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), userIndex, LocalDateTime.now());
publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 1, false);
// publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 1, false);
redisMessageQueueUtil.pushMessage(
RedisKeyEnum.USER_LOG_QUEUE.getKey(),
PubUtils.obj2json(logInfoDTO)
);
auditPush(severity, logInfoDTO);
}
@@ -163,7 +190,11 @@ public class LogServiceImpl implements ILogService {
Integer severity = levelStringToNumber(level);
String operateType = ReflectCommonUtil.getOperateTypeByMethod(method);
LogInfoDTO logInfoDTO = new LogInfoDTO(loginName, "", ip, ReflectCommonUtil.getMethodDescribeByMethod(method), operateType, result.equalsIgnoreCase("失败") ? 0 : 1, message, severity, type.equalsIgnoreCase("业务事件") ? 0 : 1, generalInfo.getMicroServiceName(), loginName, LocalDateTime.now());
publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 1, false);
// publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 1, false);
redisMessageQueueUtil.pushMessage(
RedisKeyEnum.USER_LOG_QUEUE.getKey(),
PubUtils.obj2json(logInfoDTO)
);
auditPush(severity, logInfoDTO);
}
@@ -171,7 +202,12 @@ public class LogServiceImpl implements ILogService {
//推送审计消息功能
if (severity != 0) {
if (!logInfoDTO.getLoginName().equals(LogInfo.UNKNOWN_USER)) {
publisher.send("/userLogPush", PubUtils.obj2json(logInfoDTO), 2, false);
/**注意此处是给前端推送的如果没有了mqtt协议此处前端就无消息可消费了*/
// publisher.send("/userLogPush", PubUtils.obj2json(logInfoDTO), 2, false);
// redisMessageQueueUtil.pushMessage(
// RedisKeyEnum.USER_LOG_QUEUE.getKey(),
// PubUtils.obj2json(logInfoDTO)
// );
//发送邮箱功能
if (severity == 2 && logInfoDTO.getResult() == 0) {
//publisher.send("/userLogEmailPush", PubUtils.obj2json(logInfoDTO), 2, false);

View File

@@ -1,9 +1,9 @@
package com.njcn.web.utils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
@@ -15,8 +15,11 @@ import java.util.Map;
* @createDate 2019-02-08
*
*/
@Component
public class RestTemplateUtil {
private static final Logger log = LoggerFactory.getLogger(RestTemplateUtil.class);
private static final RestTemplate restTemplate = new RestTemplate();
// ----------------------------------GET-------------------------------------------------------
@@ -263,6 +266,24 @@ public class RestTemplateUtil {
return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables);
}
public <T> ResponseEntity<T> post(String url, Object requestBody, HttpHeaders headers, Class<T> responseType) {
try {
if (headers == null) {
headers = new HttpHeaders();
}
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
log.info("发送POST请求到: {}", url);
ResponseEntity<T> response = restTemplate.postForEntity(url, entity, responseType);
log.info("POST请求响应状态: {}", response.getStatusCode());
return response;
} catch (Exception e) {
log.error("POST请求异常: {}", e.getMessage(), e);
throw e;
}
}
// ----------------------------------PUT-------------------------------------------------------
/**

View File

@@ -60,6 +60,7 @@
<artifactId>pqs-influx</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -51,6 +51,13 @@ public interface CommTerminalGeneralClient {
@PostMapping("deptGetLine")
HttpResult<List<DeptGetChildrenMoreDTO>> deptGetLine(@RequestBody @Validated DeptGetLineParam deptGetLineParam);
@PostMapping("deptGetLineInfo")
HttpResult<List<MonitorCommLedgerInfoDTO>> deptGetLineInfo(@RequestBody @Validated DeptGetLineParam deptGetLineParam);
@PostMapping("deptGetAllLine")
HttpResult<List<DeptGetChildrenMoreDTO>> deptGetAllLine(@RequestBody @Validated DeptGetLineParam deptGetLineParam);
/**
* 根据单位获取所有变电站

View File

@@ -15,6 +15,7 @@ import com.njcn.device.biz.utils.DeviceEnumUtil;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@@ -50,6 +51,19 @@ public class CommTerminalGeneralClientFallbackFactory implements FallbackFactory
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<MonitorCommLedgerInfoDTO>> deptGetLineInfo(DeptGetLineParam deptGetLineParam) {
log.error("{}异常,降级处理,异常为:{}", "根据部门获取监测点信息", throwable.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<DeptGetChildrenMoreDTO>> deptGetAllLine(DeptGetLineParam deptGetLineParam) {
log.error("{}异常,降级处理,异常为:{}", "根据单位获取all监测点信息", throwable.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<DeptGetSubStationDTO>> deptSubStation(DeptGetLineParam deptGetLineParam) {
log.error("{}异常,降级处理,异常为:{}", "根据单位获取所有变电站", throwable.toString());

View File

@@ -32,6 +32,7 @@ public enum DeviceResponseEnum {
DEVICE_SAME_NAME("A0290","设备名称已存在"),
DEVICE_REPETITION("A0291","设备名称重复"),
MODEL_NAME_REPEAT("A00350","名称不可重复"),
DEVICE_IP_REPETITION("A0292","设备ip端口号重复"),
DEVICE_SAME_IP("A0293","当前设备ip端口号已存在"),
DEVICE_EMPTY("A0294","设备为空"),

View File

@@ -0,0 +1,22 @@
package com.njcn.device.biz.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.device.biz.pojo.po.Overlimit;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author xy
* @since 2022-01-04
*/
@DS("sjzx")
@Mapper
public interface OverLimitWlMapper extends BaseMapper<Overlimit> {
}

View File

@@ -0,0 +1,28 @@
package com.njcn.device.biz.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.device.biz.pojo.po.Overlimit;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author cdf
* @since 2022-01-04
*/
public interface OverlimitMapper extends BaseMapper<Overlimit> {
/**
* 获取所有在线投运的监测点限值
*
* @author cdf
* @date 2022/3/23
*/
List<Overlimit> getAllLineOverLimit(@Param("list") List<Integer> list);
}

View File

@@ -0,0 +1,16 @@
package com.njcn.device.biz.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.device.biz.pojo.po.PqSensitiveUser;
/**
* <p>
* Mapper 接口
* </p>
*
* @author xy
* @since 2025-11-17
*/
public interface PqSensitiveUserMapper extends BaseMapper<PqSensitiveUser> {
}

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.device.biz.mapper.OverlimitMapper">
<select id="getAllLineOverLimit" resultType="com.njcn.device.biz.pojo.po.Overlimit">
select f.* from pq_line a
inner join pq_line_detail b on a.id = b.id
inner join pq_line c on a.pid = c.id
inner join pq_line d on c.pid = d.id
inner join pq_device e on d.id = e.id
inner join pq_overlimit f on a.id=f.id
where e.dev_data_type in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
and e.run_flag = 0
and e.dev_model = 1
</select>
</mapper>

View File

@@ -28,6 +28,8 @@ public class LineDevGetDTO {
private String pointName;
private Integer lineRunFlag;
/**
* 装置监测点索引集合
*/

View File

@@ -0,0 +1,40 @@
package com.njcn.device.biz.pojo.dto;
import lombok.Data;
import java.io.Serializable;
/**
* @Author: cdf
* @CreateTime: 2026-01-06
* @Description:
*/
@Data
public class MonitorCommLedgerInfoDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String monitorId;
private String monitorName;
private String gdName;
private String bdName;
private String busBarName;
private String voltageLevel;
private String shortCapacity;
private String devCapacity;
private String dealCapacity;
private String standardCapacity;
private Integer timeInterval;
}

View File

@@ -13,6 +13,8 @@ public class PollutionLineInfoDTO {
/**
* 所属变电站
*/
private String subStationId;
private String subStationName;
/**
@@ -74,7 +76,10 @@ public class PollutionLineInfoDTO {
* 电压等级
*/
private String lineVoltage;
/**
* 变电站电压等级
*/
private String subVoltage;
/**
* 装置id
*/
@@ -85,4 +90,18 @@ public class PollutionLineInfoDTO {
*/
private String monitorId;
/**
* 监测点统计间隔(解决MySQL关键字问题)
*/
private Integer timeInterval;
/**
* 监测点名称
*/
private String lineName;
/**
* 实际安装位置
*/
private String actualArea;
}

View File

@@ -32,7 +32,6 @@ public class DeptGetLineParam {
private Boolean monitorStateRunning=true;
@ApiModelProperty(name = "isUpToGrid",value = "0.非送国网 1.需要送国网的")
private Integer isUpToGrid;
/**
* 0-电网侧
@@ -48,4 +47,7 @@ public class DeptGetLineParam {
@ApiModelProperty("监测点运行状态")
@Range(min = 0, max = 2, message = "监测点运行状态" + ValidMessage.PARAM_FORMAT_ERROR)
private Integer lineRunFlag;
@ApiModelProperty("搜索值")
private String searchValue;
}

View File

@@ -762,81 +762,6 @@ public class Overlimit implements Serializable {
public Overlimit(){}
public Overlimit(String lineId, String scaTmp, float fDLRL, float fJZRL, float fXYRL, float fSBRL){
float[] fLimit = COverlimit.GetOverLimit(scaTmp, fDLRL, fJZRL, fXYRL, fSBRL);
this.id=lineId;
this.freqDev=fLimit[0];
this.voltageDev=fLimit[1];
this.ubalance=fLimit[2];
this.flicker=fLimit[3];
this.uaberrance=fLimit[4];
this.uharm2=fLimit[5];
this.uharm3=fLimit[6];
this.uharm4=fLimit[7];
this.uharm5=fLimit[8];
this.uharm6=fLimit[9];
this.uharm7=fLimit[10];
this.uharm8=fLimit[11];
this.uharm9=fLimit[12];
this.uharm10=fLimit[13];
this.uharm11=fLimit[14];
this.uharm12=fLimit[15];
this.uharm13=fLimit[16];
this.uharm14=fLimit[17];
this.uharm15=fLimit[18];
this.uharm16=fLimit[19];
this.uharm17=fLimit[20];
this.uharm18=fLimit[21];
this.uharm19=fLimit[22];
this.uharm20=fLimit[23];
this.uharm21=fLimit[24];
this.uharm22=fLimit[25];
this.uharm23=fLimit[26];
this.uharm24=fLimit[27];
this.uharm25=fLimit[28];
this.iharm2=fLimit[29];
this.iharm3=fLimit[30];
this.iharm4=fLimit[31];
this.iharm5=fLimit[32];
this.iharm6=fLimit[33];
this.iharm7=fLimit[34];
this.iharm8=fLimit[35];
this.iharm9=fLimit[36];
this.iharm10=fLimit[37];
this.iharm11=fLimit[38];
this.iharm12=fLimit[39];
this.iharm13=fLimit[40];
this.iharm14=fLimit[41];
this.iharm15=fLimit[42];
this.iharm16=fLimit[43];
this.iharm17=fLimit[44];
this.iharm18=fLimit[45];
this.iharm19=fLimit[46];
this.iharm20=fLimit[47];
this.iharm21=fLimit[48];
this.iharm22=fLimit[49];
this.iharm23=fLimit[50];
this.iharm24=fLimit[51];
this.iharm25=fLimit[52];
this.uvoltageDev=fLimit[53];
this.iNeg=fLimit[54];
this.inuharm1=fLimit[55];
this.inuharm2=fLimit[56];
this.inuharm3=fLimit[57];
this.inuharm4=fLimit[58];
this.inuharm5=fLimit[59];
this.inuharm6=fLimit[60];
this.inuharm7=fLimit[61];
this.inuharm8=fLimit[62];
this.inuharm9=fLimit[63];
this.inuharm10=fLimit[64];
this.inuharm11=fLimit[65];
this.inuharm12=fLimit[66];
this.inuharm13=fLimit[67];
this.inuharm14=fLimit[68];
this.inuharm15=fLimit[69];
this.inuharm16=fLimit[70];
}
public void buildIHarm(Float[] iHarmTem){
this.iharm2= iHarmTem[0];

View File

@@ -0,0 +1,62 @@
package com.njcn.device.biz.pojo.po;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.bo.BaseEntity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import static com.baomidou.mybatisplus.annotation.IdType.ASSIGN_ID;
/**
* @Author: cdf
* @CreateTime: 2026-02-10
* @Description:
*/
@Getter
@Setter
@TableName("pq_sensitive_user")
public class PqSensitiveUser extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(value = "id",type = ASSIGN_ID)
private String id;
/**
* 敏感用户名称
*/
private String name;
/**
* 敏感负荷类型
*/
private String loadType;
/**
* 用户协议容量
*/
private Double userAgreementCapacity;
/**
* 装机容量
*/
private Double installedCapacity;
/**
* 所属厂站名称
*/
private String substationName;
/**
* 排序
*/
private Integer sort;
}

View File

@@ -57,8 +57,8 @@ public class COverlimitUtil {
//配网
Float[] iHarmTem = new Float[49];
for (int i = 0; i <= 48; i++) {
iHarmTem[i] = -3.14159f;
//目前只处理了配网II类测点III类测点暂未处理III类测点参考主网
iHarmTem[i] = getHarmTag(i+2,voltageLevel).floatValue();
}
overlimit.buildIHarm(iHarmTem);
overlimit.setINeg(-3.14159f);

View File

@@ -0,0 +1,67 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10202
max-http-header-size: 1048576
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
server-addr: @nacos.url@
namespace: @nacos.namespace@
config:
username: @nacos.username@
password: @nacos.password@
server-addr: @nacos.url@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-Id: share-config-datasource-db.yaml
refresh: true
main:
allow-bean-definition-overriding: true
servlet:
multipart:
#上传文件总的最大值
max-request-size: 200MB
#上传文件的最大值
max-file-size: 200MB
#项目日志的配置
logging:
config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.device.pq.pojo,com.njcn.device.pms.pojo,com.njcn.device.biz.pojo.dto
#是否是冀北设备台账树
isJb: false
oracle:
isSync: false
syncLedgerLineUrl: http://localhost:8082/export/syncLedgerLine
syncLedgerUpdateLine: http://localhost:8082/export/syncLedgerUpdateLine
syncLedgerDeleteLine: http://localhost:8082/export/syncLedgerDeleteLine

View File

@@ -0,0 +1,72 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10202
max-http-header-size: 1048576
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
ip: @service.server.url@
server-addr: @nacos.url@
username: @nacos.username@
password: @nacos.password@
namespace: @nacos.namespace@
config:
server-addr: @nacos.url@
username: @nacos.username@
password: @nacos.password@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-id: share-config-datasource-db.yaml
refresh: true
main:
allow-bean-definition-overriding: true
servlet:
multipart:
#上传文件总的最大值
max-request-size: 200MB
#上传文件的最大值
max-file-size: 200MB
#项目日志的配置
logging:
#config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.device.pq.pojo,com.njcn.device.pms.pojo,com.njcn.device.biz.pojo.dto
#是否是冀北设备台账树
isJb: false
mqtt:
client-id: @artifactId@${random.value}
oracle:
isSync: false
syncLedgerLineUrl: http://localhost:8082/export/syncLedgerLine
syncLedgerUpdateLine: http://localhost:8082/export/syncLedgerUpdateLine
syncLedgerDeleteLine: http://localhost:8082/export/syncLedgerDeleteLine

View File

@@ -1,68 +1,3 @@
#当前服务的基本信息
microservice:
ename: @artifactId@
name: '@name@'
version: @version@
sentinel:
url: @sentinel.url@
gateway:
url: @gateway.url@
server:
port: 10202
max-http-header-size: 1048576
#feign接口开启服务熔断降级处理
feign:
sentinel:
enabled: true
spring:
application:
name: @artifactId@
#nacos注册中心以及配置中心的指定
cloud:
nacos:
discovery:
ip: @service.server.url@
server-addr: @nacos.url@
namespace: @nacos.namespace@
config:
server-addr: @nacos.url@
namespace: @nacos.namespace@
file-extension: yaml
shared-configs:
- data-id: share-config.yaml
refresh: true
- data-Id: share-config-datasource-db.yaml
refresh: true
main:
allow-bean-definition-overriding: true
servlet:
multipart:
#上传文件总的最大值
max-request-size: 200MB
#上传文件的最大值
max-file-size: 200MB
#项目日志的配置
#项目日志的配置
logging:
config: http://@nacos.url@/nacos/v1/cs/configs?tenant=@nacos.namespace@&group=DEFAULT_GROUP&dataId=logback.xml
level:
root: info
#mybatis配置信息
mybatis-plus:
#别名扫描
type-aliases-package: com.njcn.device.pq.pojo,com.njcn.device.pms.pojo,com.njcn.device.biz.pojo.dto
#是否是冀北设备台账树
isJb: false
mqtt:
client-id: @artifactId@${random.value}
oracle:
isSync: false
syncLedgerLineUrl: http://localhost:8082/export/syncLedgerLine
syncLedgerUpdateLine: http://localhost:8082/export/syncLedgerUpdateLine
syncLedgerDeleteLine: http://localhost:8082/export/syncLedgerDeleteLine
profiles:
active: @spring.profiles.active@

View File

@@ -7,10 +7,10 @@
SELECT DISTINCT
monitor.Org_Id AS orgId,
monitor.Org_Name AS orgName,
monitor.`Powerr_Id` AS powerId,
monitor.`Powerr_Name` AS powerName,
monitor.Powerr_Id AS powerId,
monitor.Powerr_Name AS powerName,
monitor.id AS monitorId,
monitor.`Name` AS monitorName,
monitor.Name AS monitorName,
monitor.Line_Id,
monitor.Line_Name,
pdm.Monitor_Sort AS monitorSort,
@@ -29,8 +29,8 @@
(
SELECT
pm.id,
pm.`Name`,
pm.`Status`,
pm.Name,
pm.Status,
pm.Org_Id,
pm.Org_Name,
pm.Powerr_Id,
@@ -51,8 +51,8 @@
) AS monitor
INNER JOIN pms_distribution_monitor AS pdm ON monitor.id = pdm.Monitor_Id
WHERE
monitor.`Status` = 1
AND pdm.`Status` = 1
monitor.Status = 1
AND pdm.Status = 1
AND monitor.Org_Id IN
<foreach collection="deptIdList" item="orgId" open="(" close=")" separator=",">
#{orgId}
@@ -85,7 +85,7 @@
AND pdm.If_Power_User = #{pwPmsMonitorParam.ifPowerUser}
</if>
<if test="pwPmsMonitorParam.monitorName !=null and pwPmsMonitorParam.monitorName != ''">
AND monitor.`Name` LIKE CONCAT('%',#{pwPmsMonitorParam.monitorName},'%')
AND monitor.Name LIKE CONCAT('%',#{pwPmsMonitorParam.monitorName},'%')
</if>
</select>

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