Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 46ec9923a7 | |||
|
|
d2388576a9 | ||
|
|
7f21049d0f | ||
|
|
49ca27d994 | ||
| 3cb4a46a16 | |||
|
|
13677f21d9 | ||
|
|
a1941a375b | ||
|
|
9dc8ecd873 | ||
|
|
7c6c103f17 | ||
|
|
b113788e54 | ||
|
|
599edde008 | ||
|
|
cc0b685c66 | ||
|
|
29b0a4f966 | ||
|
|
c651b18e72 | ||
|
|
6fd180b4d4 | ||
|
|
282f9cf4eb | ||
|
|
1cfea7fd6c | ||
|
|
251e302e59 | ||
|
|
873e920add |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -48,3 +48,8 @@ rebel.xml
|
||||
/.fastRequest/collections/Root/Default Group/directory.json
|
||||
/.fastRequest/collections/Root/directory.json
|
||||
/.fastRequest/config/fastRequestCurrentProjectConfig.json
|
||||
|
||||
# 个人工作文档,不与团队共享
|
||||
CLAUDE.md
|
||||
docs/
|
||||
data/
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,18 +1,27 @@
|
||||
package com.njcn.gather.detection.controller;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||
import com.njcn.common.pojo.constant.OperateType;
|
||||
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.LogUtil;
|
||||
import com.njcn.gather.detection.lock.DetectionLock;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager.AcquireResult;
|
||||
import com.njcn.gather.detection.pojo.enums.DetectionResponseEnum;
|
||||
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
|
||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
|
||||
import com.njcn.gather.detection.pojo.vo.DetectionLockHolderVO;
|
||||
import com.njcn.gather.detection.service.PreDetectionService;
|
||||
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
||||
import com.njcn.gather.detection.util.socket.FormalTestManager;
|
||||
import com.njcn.gather.user.user.pojo.po.SysUser;
|
||||
import com.njcn.gather.user.user.service.ISysUserService;
|
||||
import com.njcn.web.controller.BaseController;
|
||||
import com.njcn.web.utils.HttpResultUtil;
|
||||
import com.njcn.web.utils.RequestUtil;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
@@ -33,6 +42,7 @@ import org.springframework.web.bind.annotation.*;
|
||||
public class PreDetectionController extends BaseController {
|
||||
|
||||
private final PreDetectionService preDetectionService;
|
||||
private final ISysUserService sysUserService;
|
||||
|
||||
/**
|
||||
* 开始检测通用入口
|
||||
@@ -43,10 +53,27 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo
|
||||
@ApiOperation("开始检测")
|
||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||
public HttpResult<String> startPreTest(@RequestBody @Validated PreDetectionParam param) {
|
||||
public HttpResult<?> startPreTest(@RequestBody @Validated PreDetectionParam param) {
|
||||
String methodDescribe = getMethodDescribe("startPreTest");
|
||||
preDetectionService.sourceCommunicationCheck(param);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
HttpResult<DetectionLockHolderVO> busy = tryAcquireLock(param.getUserPageId());
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
// 同步阶段抛异常时回滚锁(PLAN_AND_SOURCE_NOT / SOURCE_INFO_NOT 等业务异常会被全局处理器吞掉,
|
||||
// 锁会卡在用户手上直到 4 小时超时,故需 finally 兜底)
|
||||
boolean keepLock = false;
|
||||
try {
|
||||
// 重置 FormalTestManager 暂停计数残留,避免上次暂停残留计数误触发 R4
|
||||
FormalTestManager.stopTime = 0;
|
||||
FormalTestManager.hasStopFlag = false;
|
||||
preDetectionService.sourceCommunicationCheck(param);
|
||||
keepLock = true;
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
} finally {
|
||||
if (!keepLock) {
|
||||
releaseLockSelf("START_PRE_SYNC_FAILED");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +87,12 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo
|
||||
@ApiOperation("源通讯校验")
|
||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||
public HttpResult<String> ytxCheckSimulate(@RequestBody @Validated SimulateDetectionParam param) {
|
||||
public HttpResult<?> ytxCheckSimulate(@RequestBody @Validated SimulateDetectionParam param) {
|
||||
String methodDescribe = getMethodDescribe("ytxCheckSimulate");
|
||||
HttpResult<DetectionLockHolderVO> busy = requireFreeOrSelf();
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
preDetectionService.ytxCheckSimulate(param);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
@@ -73,8 +104,12 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo
|
||||
@ApiOperation("启动")
|
||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||
public HttpResult<String> startTestSimulate(@RequestBody @Validated SimulateDetectionParam param) {
|
||||
public HttpResult<?> startTestSimulate(@RequestBody @Validated SimulateDetectionParam param) {
|
||||
String methodDescribe = getMethodDescribe("startTestSimulate");
|
||||
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
preDetectionService.sendScript(param);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
@@ -86,9 +121,18 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo
|
||||
@ApiOperation("停止")
|
||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||
public HttpResult<String> closeSimulateTest(@RequestBody @Validated SimulateDetectionParam param) {
|
||||
public HttpResult<?> closeSimulateTest(@RequestBody @Validated SimulateDetectionParam param) {
|
||||
String methodDescribe = getMethodDescribe("closeSimulateTest");
|
||||
preDetectionService.closeTestSimulate(param);
|
||||
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
try {
|
||||
preDetectionService.closeTestSimulate(param);
|
||||
} finally {
|
||||
// 即使业务异常也要释放锁,避免锁残留导致他人无法接手
|
||||
releaseLockSelf("USER_STOP");
|
||||
}
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
|
||||
@@ -100,8 +144,12 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo
|
||||
@ApiOperation("系数校验")
|
||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||
public HttpResult<String> coefficientCheck(@RequestBody PreDetectionParam param) {
|
||||
public HttpResult<?> coefficientCheck(@RequestBody PreDetectionParam param) {
|
||||
String methodDescribe = getMethodDescribe("coefficientCheck");
|
||||
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
preDetectionService.coefficientCheck(param);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
@@ -114,8 +162,13 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo
|
||||
@ApiOperation("暂停检测")
|
||||
@ApiImplicitParam(name = "param", value = "参数", required = true)
|
||||
public HttpResult<String> temStopTest() {
|
||||
public HttpResult<?> temStopTest() {
|
||||
String methodDescribe = getMethodDescribe("temStopTest");
|
||||
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
// 暂停保持锁(spec §2.3),不释放
|
||||
preDetectionService.temStopTest();
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
@@ -127,8 +180,12 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo
|
||||
@ApiOperation("重新开始检测")
|
||||
@ApiImplicitParam(name = "param", value = "参数", required = true)
|
||||
public HttpResult<String> restartTemTest(@RequestBody PreDetectionParam param) {
|
||||
public HttpResult<?> restartTemTest(@RequestBody PreDetectionParam param) {
|
||||
String methodDescribe = getMethodDescribe("restartTemTest");
|
||||
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
preDetectionService.restartTemTest(param);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
@@ -141,10 +198,26 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo
|
||||
@ApiOperation("开始比对检测")
|
||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||
public HttpResult<String> startContrastTest(@RequestBody @Validated ContrastDetectionParam param) {
|
||||
public HttpResult<?> startContrastTest(@RequestBody @Validated ContrastDetectionParam param) {
|
||||
String methodDescribe = getMethodDescribe("startContrastTest");
|
||||
preDetectionService.startContrastTest(param);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
// ContrastDetectionParam 无 userPageId 字段,用 loginName 作为会话标识(与 WS 会话 key 一致)
|
||||
HttpResult<DetectionLockHolderVO> busy = tryAcquireLock(param.getLoginName());
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
// 同步阶段抛异常时回滚锁,理由同 startPreTest
|
||||
boolean keepLock = false;
|
||||
try {
|
||||
FormalTestManager.stopTime = 0;
|
||||
FormalTestManager.hasStopFlag = false;
|
||||
preDetectionService.startContrastTest(param);
|
||||
keepLock = true;
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
} finally {
|
||||
if (!keepLock) {
|
||||
releaseLockSelf("START_CONTRAST_SYNC_FAILED");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -170,33 +243,91 @@ public class PreDetectionController extends BaseController {
|
||||
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
||||
@GetMapping("/startCoefficient")
|
||||
@ApiOperation("比对模式开启系数校验")
|
||||
public HttpResult<String> startCoefficient() {
|
||||
public HttpResult<?> startCoefficient() {
|
||||
String methodDescribe = getMethodDescribe("startCoefficient");
|
||||
LogUtil.njcnDebug(log, "{}", methodDescribe);
|
||||
|
||||
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||
if (busy != null) {
|
||||
return busy;
|
||||
}
|
||||
preDetectionService.startCoefficient();
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
||||
@GetMapping("/startFreqConverter")
|
||||
@ApiOperation("开启变频器测试")
|
||||
public HttpResult<String> startFreqConverter(@RequestParam("userId") String userId, @RequestParam("converterId") String converterId, @RequestParam("monitorId") String monitorId, @RequestParam("reset") Boolean reset) {
|
||||
String methodDescribe = getMethodDescribe("startFreqConverter");
|
||||
LogUtil.njcnDebug(log, "{}", methodDescribe);
|
||||
// ============ 检测互斥锁辅助方法 ============
|
||||
|
||||
preDetectionService.startFreqConverter(userId, converterId, monitorId,reset);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
/** 抢锁入口(startPreTest / startContrastTest 用)。
|
||||
* 抢到→null;被他人持有或竞态失败→返回 busy 响应;
|
||||
* 使用方:拿到非 null 返回值直接 return 给上层。 */
|
||||
private HttpResult<DetectionLockHolderVO> tryAcquireLock(String userPageId) {
|
||||
String userId = RequestUtil.getUserId();
|
||||
AcquireResult r = DetectionLockManager.getInstance()
|
||||
.tryAcquire(userId, resolveDisplayName(userId), userPageId);
|
||||
if (r.isOk()) {
|
||||
return null;
|
||||
}
|
||||
return HttpResultUtil.assembleResult(
|
||||
DetectionResponseEnum.DETECTION_BUSY.getCode(),
|
||||
r.getHolder(),
|
||||
DetectionResponseEnum.DETECTION_BUSY.getMessage());
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
||||
@GetMapping("/stopFreqConverter")
|
||||
@ApiOperation("关闭变频器测试")
|
||||
public HttpResult<String> stopFreqConverter(@RequestParam("userId") String userId) {
|
||||
String methodDescribe = getMethodDescribe("stopFreqConverter");
|
||||
LogUtil.njcnDebug(log, "{}", methodDescribe);
|
||||
/** 中间接口校验:要求当前 holder == 自己。
|
||||
* 空闲 → 返回 busy data=null("请先开始检测"语义);
|
||||
* 他人持有 → 返回 busy + holder;
|
||||
* 自己持有 → 返回 null(放行)。 */
|
||||
private HttpResult<DetectionLockHolderVO> requireHolderSelf() {
|
||||
DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
|
||||
String me = RequestUtil.getUserId();
|
||||
if (cur != null && me.equals(cur.getUserId())) {
|
||||
return null;
|
||||
}
|
||||
DetectionLockHolderVO holder = cur == null ? null : DetectionLockManager.toHolderVO(cur);
|
||||
return HttpResultUtil.assembleResult(
|
||||
DetectionResponseEnum.DETECTION_BUSY.getCode(),
|
||||
holder,
|
||||
DetectionResponseEnum.DETECTION_BUSY.getMessage());
|
||||
}
|
||||
|
||||
preDetectionService.stopFreqConverter(userId + CnSocketUtil.FREQ_CONVERTER_TAG, userId + CnSocketUtil.DEV_TAG);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
/** 辅助接口规则(ytxCheckSimulate):锁空闲 → 放行;他人持有 → busy;自己持有 → 放行。 */
|
||||
private HttpResult<DetectionLockHolderVO> requireFreeOrSelf() {
|
||||
DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
|
||||
if (cur == null) {
|
||||
return null;
|
||||
}
|
||||
String me = RequestUtil.getUserId();
|
||||
if (me.equals(cur.getUserId())) {
|
||||
return null;
|
||||
}
|
||||
return HttpResultUtil.assembleResult(
|
||||
DetectionResponseEnum.DETECTION_BUSY.getCode(),
|
||||
DetectionLockManager.toHolderVO(cur),
|
||||
DetectionResponseEnum.DETECTION_BUSY.getMessage());
|
||||
}
|
||||
|
||||
/** 释放锁(用户主动终止)。 */
|
||||
private void releaseLockSelf(String reason) {
|
||||
DetectionLockManager.getInstance().releaseIfHeldBy(RequestUtil.getUserId(), reason);
|
||||
}
|
||||
|
||||
/** 解析展示给前端的用户名(昵称优先,loginName 兜底,避免 BUSY 弹窗显示 "unknown user")。 */
|
||||
private String resolveDisplayName(String userId) {
|
||||
if (StrUtil.isBlank(userId)) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
SysUser user = sysUserService.getById(userId);
|
||||
if (user != null && StrUtil.isNotBlank(user.getName())) {
|
||||
return user.getName();
|
||||
}
|
||||
if (user != null && StrUtil.isNotBlank(user.getLoginName())) {
|
||||
return user.getLoginName();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("解析检测锁持有者昵称失败,userId={}", userId, e);
|
||||
}
|
||||
// 最终兜底:用 token 里的 loginName,不要返回 "unknown user"
|
||||
String loginName = RequestUtil.getLoginNameByToken();
|
||||
return StrUtil.isNotBlank(loginName) ? loginName : userId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ import com.njcn.gather.storage.pojo.po.ContrastNonHarmonicResult;
|
||||
import com.njcn.gather.storage.service.DetectionDataDealService;
|
||||
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
|
||||
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
|
||||
import com.njcn.gather.system.config.PathConfig;
|
||||
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
|
||||
import com.njcn.gather.system.dictionary.pojo.po.DictData;
|
||||
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
|
||||
@@ -57,7 +58,6 @@ import com.njcn.gather.tools.comtrade.comparewave.service.ICompareWaveService;
|
||||
import com.njcn.gather.util.StorageUtil;
|
||||
import com.njcn.web.utils.ExcelUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
@@ -127,8 +127,9 @@ public class SocketContrastResponseService {
|
||||
// private SysRegRes contrastRegRes = null;
|
||||
|
||||
|
||||
@Value("${report.reportDir}")
|
||||
private String alignDataFilePath;
|
||||
// @Value("${report.reportDir}")
|
||||
// private String alignDataFilePath;
|
||||
private final PathConfig pathConfig;
|
||||
|
||||
public static final Map<String, List<String>> testItemCodeMap = new HashMap() {{
|
||||
put("FREQ", Arrays.asList(DetectionCodeEnum.FREQ.getCode()));
|
||||
@@ -2314,7 +2315,7 @@ public class SocketContrastResponseService {
|
||||
});
|
||||
});
|
||||
|
||||
ExcelUtil.saveExcel(alignDataFilePath, "对齐数据.xlsx", sheetsList);
|
||||
ExcelUtil.saveExcel(pathConfig.getDataPath(), "对齐数据.xlsx", sheetsList);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,6 +6,7 @@ import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||
import com.njcn.gather.detection.pojo.dto.DevXiNumData;
|
||||
import com.njcn.gather.detection.pojo.enums.DetectionCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
@@ -33,6 +34,7 @@ import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
|
||||
import com.njcn.gather.script.pojo.po.SourceIssue;
|
||||
import com.njcn.gather.script.service.IPqScriptCheckDataService;
|
||||
import com.njcn.gather.script.service.IPqScriptDtlsService;
|
||||
import com.njcn.gather.source.service.IPqSourceService;
|
||||
import com.njcn.gather.storage.pojo.param.StorageParam;
|
||||
import com.njcn.gather.storage.pojo.po.SimAndDigHarmonicResult;
|
||||
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
|
||||
@@ -76,6 +78,7 @@ public class SocketDevResponseService {
|
||||
private final SimAndDigHarmonicService adHarmonicService;
|
||||
private final IAdPlanService adPlanService;
|
||||
private final IDictDataService dictDataService;
|
||||
private final IPqSourceService pqSourceService;
|
||||
|
||||
/**
|
||||
* 存储的装置相序数据
|
||||
@@ -391,6 +394,7 @@ public class SocketDevResponseService {
|
||||
if (param.getTestItemList().get(2)) {
|
||||
//如果后续做正式检测
|
||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||
issueParam.setSourceId(param.getSourceName());
|
||||
issueParam.setPlanId(param.getPlanId());
|
||||
issueParam.setSourceId(param.getSourceId());
|
||||
issueParam.setDevIds(param.getDevIds());
|
||||
@@ -688,7 +692,7 @@ public class SocketDevResponseService {
|
||||
*/
|
||||
private Double reduceList(List<Double> valList) {
|
||||
// valList.subList(0, 5).clear();
|
||||
valList.subList(valList.size() - 2, valList.size()).clear();
|
||||
valList.subList(valList.size() - 2, valList.size()).clear();
|
||||
return valList.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
|
||||
}
|
||||
|
||||
@@ -894,7 +898,7 @@ public class SocketDevResponseService {
|
||||
//开始下源控制脚本
|
||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||
issueParam.setPlanId(param.getPlanId());
|
||||
issueParam.setSourceId(param.getSourceId());
|
||||
issueParam.setSourceId(param.getSourceName());
|
||||
issueParam.setDevIds(param.getDevIds());
|
||||
issueParam.setScriptId(param.getScriptId());
|
||||
|
||||
@@ -1162,8 +1166,8 @@ public class SocketDevResponseService {
|
||||
} else if (param.getTestItemList().get(2)) {
|
||||
// 后续做正式检测
|
||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||
issueParam.setSourceId(param.getSourceName());
|
||||
issueParam.setPlanId(param.getPlanId());
|
||||
issueParam.setSourceId(param.getSourceId());
|
||||
issueParam.setDevIds(param.getDevIds());
|
||||
issueParam.setScriptId(param.getScriptId());
|
||||
|
||||
@@ -1374,8 +1378,11 @@ public class SocketDevResponseService {
|
||||
checkDataParam.setIsValueTypeName(false);
|
||||
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
|
||||
|
||||
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity());
|
||||
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), true);
|
||||
CnSocketUtil.quitSend(param);
|
||||
// 数模式检测全部小项完成 → 释放锁,避免用户必须点"停止"才能让出
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "DEV_TEST_FINISHED");
|
||||
}
|
||||
successComm.clear();
|
||||
FormalTestManager.realDataXiList.clear();
|
||||
@@ -1816,8 +1823,8 @@ public class SocketDevResponseService {
|
||||
XiNumberManager.devParameterList.add(devParameterSmall);
|
||||
|
||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||
issueParam.setSourceId(param.getSourceName());
|
||||
issueParam.setPlanId(param.getPlanId());
|
||||
issueParam.setSourceId(param.getSourceId());
|
||||
issueParam.setDevIds(param.getDevIds());
|
||||
issueParam.setScriptId(param.getScriptId());
|
||||
issueParam.setIsPhaseSequence(CommonEnum.COEFFICIENT_TEST.getValue());
|
||||
|
||||
@@ -1,369 +0,0 @@
|
||||
package com.njcn.gather.detection.handler;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.collection.ListUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.njcn.db.mybatisplus.handler.DynamicTableNameHandler;
|
||||
import com.njcn.gather.detection.pojo.enums.DetectionCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.param.DevPhaseSequenceParam;
|
||||
import com.njcn.gather.detection.pojo.po.DevData;
|
||||
import com.njcn.gather.detection.pojo.vo.SocketDataMsg;
|
||||
import com.njcn.gather.detection.pojo.vo.SocketMsg;
|
||||
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
||||
import com.njcn.gather.detection.util.socket.FormalTestManager;
|
||||
import com.njcn.gather.detection.util.socket.MsgUtil;
|
||||
import com.njcn.gather.detection.util.socket.SocketManager;
|
||||
import com.njcn.gather.detection.util.socket.cilent.NettyClient;
|
||||
import com.njcn.gather.detection.util.socket.cilent.NettyFreqConverterDevClientHandler;
|
||||
import com.njcn.gather.detection.util.socket.config.SocketConnectionConfig;
|
||||
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
|
||||
import com.njcn.gather.device.pojo.po.PqDev;
|
||||
import com.njcn.gather.device.pojo.vo.PreDetection;
|
||||
import com.njcn.gather.device.service.IPqDevService;
|
||||
import com.njcn.gather.dip.pojo.po.PqDipData;
|
||||
import com.njcn.gather.dip.service.IPqDipDataService;
|
||||
import com.njcn.gather.freqConverter.config.FreqConverterConfig;
|
||||
import com.njcn.gather.freqConverter.pojo.po.FreqConverterStatus;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterTestRes;
|
||||
import com.njcn.gather.freqConverter.service.IFreqConverterService;
|
||||
import com.njcn.gather.freqConverter.service.IPqFreqConverterTestResService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SocketFreqConverterDevService {
|
||||
|
||||
private final SocketConnectionConfig socketConnectionConfig;
|
||||
private final IPqDevService pqDevService;
|
||||
private final IPqDipDataService pqDipDataService;
|
||||
private final IFreqConverterService freqConverterService;
|
||||
private final IPqFreqConverterTestResService pqFreqConverterTestResService;
|
||||
private final FreqConverterConfig freqConverterConfig;
|
||||
private String monitorId;
|
||||
private String userId;
|
||||
|
||||
public static final String DIP_DATA_SUFFIX = "&&VOLTAGE";
|
||||
|
||||
/**
|
||||
* 连接设备Socket
|
||||
*
|
||||
* @param devTag 设备Channel唯一标识符
|
||||
*/
|
||||
public void connectSocket(String devTag) {
|
||||
if (SocketManager.isChannelActive(devTag)) {
|
||||
return;
|
||||
}
|
||||
String ip = socketConnectionConfig.getDevice().getIp();
|
||||
Integer port = socketConnectionConfig.getDevice().getPort();
|
||||
|
||||
NettyFreqConverterDevClientHandler handler = new NettyFreqConverterDevClientHandler(devTag, this);
|
||||
CompletableFuture.runAsync(() -> {
|
||||
NettyClient.commonConnect(ip, port, devTag, handler);
|
||||
});
|
||||
}
|
||||
|
||||
private void init(String userId, String converterId, String monitorId, Boolean reset) {
|
||||
FormalTestManager.freqConverterDevStep = null;
|
||||
// FormalTestManager.stopFlag = false;
|
||||
FormalTestManager.isRemoveSocket = false;
|
||||
FormalTestManager.pendingDipTaskMap.clear();
|
||||
if (reset) {
|
||||
pqDipDataService.clearAllData(FormalTestManager.freqConverterTableSuffix);
|
||||
pqFreqConverterTestResService.clearAllData(FormalTestManager.freqConverterTableSuffix);
|
||||
}
|
||||
this.userId = userId;
|
||||
this.monitorId = monitorId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接设备
|
||||
*/
|
||||
public void connectionDev(String userId, String devTag, String converterId, String monitorId, Boolean reset) {
|
||||
this.init(userId, converterId, monitorId, reset);
|
||||
|
||||
String payload = buildSingleMonitorPayload(monitorId);
|
||||
if (StrUtil.isBlank(payload)) {
|
||||
return;
|
||||
}
|
||||
|
||||
SocketMsg<String> socketMsg = new SocketMsg<>();
|
||||
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_SBTXJY.getValue());
|
||||
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_INIT_GATHER_03.getValue());
|
||||
socketMsg.setData(payload);
|
||||
SocketManager.sendMsg(devTag, JSON.toJSONString(socketMsg));
|
||||
FormalTestManager.freqConverterDevStep = SourceOperateCodeEnum.YJC_SBTXJY;
|
||||
}
|
||||
|
||||
public void handleRead(String devTag, String msg) {
|
||||
SocketDataMsg socketDataMsg = MsgUtil.socketDataMsg(msg);
|
||||
|
||||
switch (FormalTestManager.freqConverterDevStep) {
|
||||
case YJC_SBTXJY:
|
||||
handleYjcSbtxjy(devTag, socketDataMsg);
|
||||
break;
|
||||
case FORMAL_REAL:
|
||||
handleFormalReal(devTag, socketDataMsg);
|
||||
break;
|
||||
case QUITE:
|
||||
handleQuit(devTag, socketDataMsg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleYjcSbtxjy(String devTag, SocketDataMsg socketDataMsg) {
|
||||
SourceResponseCodeEnum responseCodeEnum = SourceResponseCodeEnum.getDictDataEnumByCode(socketDataMsg.getCode());
|
||||
switch (Objects.requireNonNull(responseCodeEnum)) {
|
||||
case UNPROCESSED_BUSINESS:
|
||||
break;
|
||||
case RE_OPERATE:
|
||||
WebServiceManager.sendMsg(this.userId, JSON.toJSONString(socketDataMsg));
|
||||
break;
|
||||
case SUCCESS:
|
||||
// 暂态协议触发后等待5秒,将装置历史缓存的暂态数据给抛掉
|
||||
CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
this.sendGetDipDataMsg(devTag);
|
||||
FormalTestManager.freqConverterDevStep = SourceOperateCodeEnum.FORMAL_REAL;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.error("异步调用sendGetDipDataMsg被中断", e);
|
||||
}
|
||||
});
|
||||
break;
|
||||
default:
|
||||
log.warn("设备响应异常,devTag={}, operateCode={}, code={}, data={}", devTag, socketDataMsg.getOperateCode(), socketDataMsg.getCode(), socketDataMsg.getData());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleFormalReal(String devTag, SocketDataMsg socketDataMsg) {
|
||||
SourceResponseCodeEnum responseCodeEnum = SourceResponseCodeEnum.getDictDataEnumByCode(socketDataMsg.getCode());
|
||||
|
||||
switch (responseCodeEnum) {
|
||||
case UNPROCESSED_BUSINESS:
|
||||
break;
|
||||
case SUCCESS:
|
||||
case NORMAL_RESPONSE:
|
||||
DevData devData = JSON.parseObject(socketDataMsg.getData(), DevData.class);
|
||||
// 如果变频器不是处于 “故障中” 状态,就保存数据,反之,这段时期内的数据不保存
|
||||
// if (!FormalTestManager.stopFlag) {
|
||||
// saveDipData(devData);
|
||||
// }
|
||||
saveDipData(devData);
|
||||
break;
|
||||
case DEV_ERROR:
|
||||
case DEV_TARGET:
|
||||
case COMMUNICATION_ERR:
|
||||
case DATA_RESOLVE:
|
||||
case NO_INIT_DEV:
|
||||
default:
|
||||
log.warn("设备响应异常,devTag={}, operateCode={}, code={}, data={}", devTag, socketDataMsg.getOperateCode(), socketDataMsg.getCode(), socketDataMsg.getData());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleQuit(String devTag, SocketDataMsg socketDataMsg) {
|
||||
SourceResponseCodeEnum responseCodeEnum = SourceResponseCodeEnum.getDictDataEnumByCode(socketDataMsg.getCode());
|
||||
|
||||
switch (responseCodeEnum) {
|
||||
case UNPROCESSED_BUSINESS:
|
||||
break;
|
||||
case SUCCESS:
|
||||
cleanup(devTag);
|
||||
break;
|
||||
default:
|
||||
log.warn("设备关闭响应失败,devTag={}, operateCode={}, code={}, data={}", devTag, socketDataMsg.getOperateCode(), socketDataMsg.getCode(), socketDataMsg.getData());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void stopTest(String converterTag, String devTag) {
|
||||
FormalTestManager.freqConverterDevStep = SourceOperateCodeEnum.QUITE;
|
||||
sendQuitMsg(devTag, SourceOperateCodeEnum.QUIT_INIT_03);
|
||||
}
|
||||
|
||||
|
||||
private String buildSingleMonitorPayload(String monitorId) {
|
||||
String[] split = monitorId.split(CnSocketUtil.SPLIT_TAG);
|
||||
if (split.length < 2 || StrUtil.isBlank(split[0]) || StrUtil.isBlank(split[1])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<PreDetection> preDetections = pqDevService.getDevInfo(Collections.singletonList(split[0]));
|
||||
if (CollUtil.isEmpty(preDetections)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
PreDetection preDetection = preDetections.get(0);
|
||||
List<PreDetection.MonitorListDTO> monitorList = preDetection.getMonitorList();
|
||||
if (CollUtil.isEmpty(monitorList)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<PreDetection.MonitorListDTO> matchedMonitorList = monitorList.stream()
|
||||
.filter(item -> split[1].equals(StrUtil.EMPTY + item.getLine()))
|
||||
.collect(Collectors.toList());
|
||||
if (CollUtil.isEmpty(matchedMonitorList)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
preDetection.setMonitorList(matchedMonitorList);
|
||||
Map<String, List<PreDetection>> payload = new HashMap<>(1);
|
||||
payload.put("deviceList", Collections.singletonList(preDetection));
|
||||
return JSON.toJSONString(payload);
|
||||
}
|
||||
|
||||
private void sendGetDipDataMsg(String devTag) {
|
||||
SocketMsg<String> socketMsg = new SocketMsg<>();
|
||||
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + DIP_DATA_SUFFIX);
|
||||
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
|
||||
|
||||
DevPhaseSequenceParam phaseSequenceParam = new DevPhaseSequenceParam();
|
||||
String[] split = this.monitorId.split(String.valueOf(StrUtil.C_UNDERLINE));
|
||||
PqDev dev = pqDevService.getById(split[0]);
|
||||
|
||||
// 设置监测点ID列表
|
||||
phaseSequenceParam.setMoniterIdList(ListUtil.of(dev.getIp() + StrUtil.C_UNDERLINE + split[1]));
|
||||
|
||||
// 设置数据类型列表
|
||||
phaseSequenceParam.setDataType(ListUtil.of("avg$MAG", "avg$DUR"));
|
||||
// 设置读取次数
|
||||
phaseSequenceParam.setReadCount(0);
|
||||
// 设置忽略次数
|
||||
phaseSequenceParam.setIgnoreCount(0);
|
||||
socketMsg.setData(JSON.toJSONString(phaseSequenceParam));
|
||||
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_03.getValue());
|
||||
SocketManager.sendMsg(devTag, JSON.toJSONString(socketMsg));
|
||||
}
|
||||
|
||||
private void sendQuitMsg(String devTag, SourceOperateCodeEnum operateCodeEnum) {
|
||||
SocketMsg<String> socketMsg = new SocketMsg<>();
|
||||
socketMsg.setRequestId(SourceOperateCodeEnum.QUITE.getValue());
|
||||
socketMsg.setOperateCode(operateCodeEnum.getValue());
|
||||
SocketManager.sendMsg(devTag, JSON.toJSONString(socketMsg));
|
||||
}
|
||||
|
||||
private void saveDipData(DevData devData) {
|
||||
if (Objects.isNull(devData) || CollUtil.isEmpty(devData.getSqlData())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Double residualVoltage = null;
|
||||
Integer durationMs = null;
|
||||
for (DevData.SqlDataDTO sqlDataDTO : devData.getSqlData()) {
|
||||
if (Objects.isNull(sqlDataDTO) || Objects.isNull(sqlDataDTO.getList())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Double value = getSqlDataValue(sqlDataDTO.getList());
|
||||
if (Objects.isNull(value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (DetectionCodeEnum.MAG.getCode().equalsIgnoreCase(sqlDataDTO.getDesc())) {
|
||||
residualVoltage = value;
|
||||
} else if (DetectionCodeEnum.DUR.getCode().equalsIgnoreCase(sqlDataDTO.getDesc())) {
|
||||
durationMs = (int) Math.round(value * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
PqDipData pqDipData = new PqDipData();
|
||||
pqDipData.setId(IdUtil.fastSimpleUUID());
|
||||
pqDipData.setStartTime(LocalDateTime.parse(devData.getTime()));
|
||||
pqDipData.setResidualVoltage(residualVoltage);
|
||||
pqDipData.setDurationMs(durationMs);
|
||||
DynamicTableNameHandler.setTableName("pq_dip_data_" + FormalTestManager.freqConverterTableSuffix);
|
||||
pqDipDataService.save(pqDipData);
|
||||
DynamicTableNameHandler.remove();
|
||||
|
||||
this.initDipTestRes(pqDipData);
|
||||
}
|
||||
|
||||
private void initDipTestRes(PqDipData pqDipData) {
|
||||
Integer suffix = FormalTestManager.freqConverterTableSuffix;
|
||||
FreqConverterStatus lastStatusData = freqConverterService.getLastStatusData(suffix, pqDipData.getStartTime());
|
||||
if (Objects.isNull(lastStatusData)) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<FreqConverterStatus> statusList = freqConverterService.getDipDurationStatusData(suffix, lastStatusData.getTimestamp(), pqDipData.getStartTime().plusNanos(pqDipData.getDurationMs() * 1000_000L));
|
||||
Integer originalTolerant = (lastStatusData.getStatusWord1() == freqConverterConfig.getTolerant()) ? 1 : 0;
|
||||
LocalDateTime targetEndTime = pqDipData.getStartTime()
|
||||
.plusNanos(pqDipData.getDurationMs() * 1000_000L)
|
||||
.plusNanos(freqConverterConfig.getDt() * 1000_000L);
|
||||
|
||||
if (CollUtil.isNotEmpty(statusList)) {
|
||||
FreqConverterStatus status = statusList.get(statusList.size() - 1);
|
||||
PqFreqConverterTestRes testRes = new PqFreqConverterTestRes();
|
||||
testRes.setId(IdUtil.fastSimpleUUID());
|
||||
testRes.setTolerant(originalTolerant == 1 ?
|
||||
(status.getStatusWord1() == freqConverterConfig.getTolerant() ? 1 : 0)
|
||||
: 0);
|
||||
testRes.setDurationMs(pqDipData.getDurationMs());
|
||||
testRes.setResidualVoltage(pqDipData.getResidualVoltage());
|
||||
testRes.setTime(LocalDateTime.now());
|
||||
|
||||
FormalTestManager.pendingDipTaskMap.put(testRes.getId(), new FormalTestManager.PendingDipTask(
|
||||
pqDipData,
|
||||
targetEndTime,
|
||||
originalTolerant
|
||||
));
|
||||
|
||||
pqFreqConverterTestResService.saveTestRes(suffix, Collections.singletonList(testRes));
|
||||
}
|
||||
}
|
||||
|
||||
private Double getSqlDataValue(DevData.SqlDataDTO.ListDTO listDTO) {
|
||||
if (Objects.nonNull(listDTO.getA())) {
|
||||
return listDTO.getA();
|
||||
}
|
||||
if (Objects.nonNull(listDTO.getB())) {
|
||||
return listDTO.getB();
|
||||
}
|
||||
if (Objects.nonNull(listDTO.getC())) {
|
||||
return listDTO.getC();
|
||||
}
|
||||
return listDTO.getT();
|
||||
}
|
||||
|
||||
public void cleanup(String devTag) {
|
||||
String currentUserId = this.userId;
|
||||
FormalTestManager.freqConverterDevStep = null;
|
||||
FormalTestManager.isRemoveSocket = true;
|
||||
SocketManager.removeUser(devTag);
|
||||
clearStateIfStopped(currentUserId);
|
||||
this.userId = null;
|
||||
this.monitorId = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果设备已停止,则清除共享的运行时状态
|
||||
*
|
||||
* @param currentUserId 当前用户ID
|
||||
*/
|
||||
private void clearStateIfStopped(String currentUserId) {
|
||||
if (StrUtil.isBlank(currentUserId)) {
|
||||
FormalTestManager.clearFreqConverterRuntimeState();
|
||||
return;
|
||||
}
|
||||
String freqConverterTag = currentUserId + CnSocketUtil.FREQ_CONVERTER_TAG;
|
||||
// 避免过早把 freqConverterTableSuffix 等全局值清掉,造成变频器无法使用全局变量
|
||||
if (!SocketManager.isChannelActive(freqConverterTag)) {
|
||||
FormalTestManager.freqConverterStep = null;
|
||||
FormalTestManager.clearFreqConverterRuntimeState();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,433 +0,0 @@
|
||||
package com.njcn.gather.detection.handler;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.njcn.gather.detection.pojo.dto.FreqConverterRespDTO;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.vo.SocketDataMsg;
|
||||
import com.njcn.gather.detection.pojo.vo.SocketMsg;
|
||||
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
||||
import com.njcn.gather.detection.util.socket.FormalTestManager;
|
||||
import com.njcn.gather.detection.util.socket.SocketManager;
|
||||
import com.njcn.gather.detection.util.socket.cilent.NettyClient;
|
||||
import com.njcn.gather.detection.util.socket.cilent.NettyFreqConverterClientHandler;
|
||||
import com.njcn.gather.detection.util.socket.config.SocketConnectionConfig;
|
||||
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
|
||||
import com.njcn.gather.freqConverter.config.FreqConverterConfig;
|
||||
import com.njcn.gather.freqConverter.pojo.po.FreqConverterStatus;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterConfig;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterTestRes;
|
||||
import com.njcn.gather.freqConverter.pojo.vo.TolerantPointVO;
|
||||
import com.njcn.gather.freqConverter.service.IFreqConverterService;
|
||||
import com.njcn.gather.freqConverter.service.IPqFreqConverterConfigService;
|
||||
import com.njcn.gather.freqConverter.service.IPqFreqConverterTestResService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author czh
|
||||
* @version 1.0
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SocketFreqConverterService {
|
||||
private final IFreqConverterService freqConverterService;
|
||||
|
||||
private final SocketConnectionConfig socketConnectionConfig;
|
||||
|
||||
private final IPqFreqConverterConfigService pqFreqConverterConfigService;
|
||||
private final IPqFreqConverterTestResService pqFreqConverterTestResService;
|
||||
private String userId;
|
||||
/**
|
||||
* 上一个暂降点耐受检测结果
|
||||
*/
|
||||
private TolerantPointVO lastTolerancePoint;
|
||||
private final FreqConverterConfig freqConverterConfig;
|
||||
|
||||
/**
|
||||
* 连接变频器Socket
|
||||
*
|
||||
* @param converterChannelTag 变频器Channel唯一标识符
|
||||
*/
|
||||
public void connectSocket(String converterChannelTag) {
|
||||
if (SocketManager.isChannelActive(converterChannelTag)) {
|
||||
return;
|
||||
}
|
||||
String ip = socketConnectionConfig.getFreqConverter().getIp();
|
||||
Integer port = socketConnectionConfig.getFreqConverter().getPort();
|
||||
|
||||
NettyFreqConverterClientHandler handler = new NettyFreqConverterClientHandler(converterChannelTag, this);
|
||||
|
||||
CompletableFuture.runAsync(() -> {
|
||||
NettyClient.commonConnect(ip, port, converterChannelTag, handler);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 重连
|
||||
*
|
||||
* @param converterChannelTag
|
||||
*/
|
||||
public void reconnect(String converterChannelTag) {
|
||||
SocketManager.removeUser(converterChannelTag);
|
||||
|
||||
String ip = socketConnectionConfig.getFreqConverter().getIp();
|
||||
Integer port = socketConnectionConfig.getFreqConverter().getPort();
|
||||
|
||||
NettyFreqConverterClientHandler handler = new NettyFreqConverterClientHandler(converterChannelTag, this);
|
||||
|
||||
CompletableFuture.runAsync(() -> {
|
||||
NettyClient.commonConnect(ip, port, converterChannelTag, handler);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试连接成功,重新开启定时任务,获取变频器状态数据
|
||||
*
|
||||
* @param converterChannelTag
|
||||
*/
|
||||
public void onReconnectSuccess(String converterChannelTag) {
|
||||
log.info("变频器重连成功,恢复数据采集,converterChannelTag={}", converterChannelTag);
|
||||
|
||||
// FormalTestManager.stopFlag = false;
|
||||
|
||||
if (FormalTestManager.scheduler == null) {
|
||||
FormalTestManager.scheduler = Executors.newScheduledThreadPool(1);
|
||||
FormalTestManager.scheduledFuture = FormalTestManager.scheduler.scheduleAtFixedRate(() -> {
|
||||
this.sendGetDeviceStatusMsg(converterChannelTag);
|
||||
}, 0l, 200l, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
public void init(String userId, String converterId, String monitorId, Boolean reset) {
|
||||
this.lastTolerancePoint = null;
|
||||
this.userId = userId;
|
||||
FormalTestManager.freqConverterStep = null;
|
||||
FormalTestManager.currentFreqConverterId = converterId;
|
||||
Integer suffix = pqFreqConverterConfigService.getSuffix(converterId);
|
||||
if (reset) {
|
||||
freqConverterService.clearAllData(suffix);
|
||||
}
|
||||
FormalTestManager.freqConverterTableSuffix = suffix;
|
||||
FormalTestManager.isRemoveSocket = false;
|
||||
FormalTestManager.pendingDipTaskMap.clear();
|
||||
pqFreqConverterConfigService.updateTestStatus(converterId, 0);
|
||||
clearScheduleTask();
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接变频器
|
||||
*/
|
||||
public void connectionFreqConverter(String userId, String freqConverterTag, String converterId, String monitorId, Boolean reset) {
|
||||
this.init(userId, converterId, monitorId, reset);
|
||||
|
||||
SocketMsg<Map<String, Object>> socketMsg = new SocketMsg<>();
|
||||
socketMsg.setOperateCode(SourceOperateCodeEnum.CMD_INIT_SERIAL.getValue());
|
||||
String requestId = IdUtil.fastSimpleUUID();
|
||||
socketMsg.setRequestId(requestId);
|
||||
|
||||
PqFreqConverterConfig freqConverterConfig = pqFreqConverterConfigService.getById(converterId);
|
||||
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("portName", freqConverterConfig.getPortName());
|
||||
map.put("slaveAddress", freqConverterConfig.getSlaveAddress());
|
||||
map.put("baudRate", freqConverterConfig.getBaudRate());
|
||||
map.put("parity", freqConverterConfig.getParity());
|
||||
map.put("dataBits", freqConverterConfig.getDataBits());
|
||||
map.put("stopBits", freqConverterConfig.getStopBits());
|
||||
map.put("timeoutMs", freqConverterConfig.getTimeoutMs());
|
||||
socketMsg.setData(map);
|
||||
|
||||
SocketManager.sendMsg(freqConverterTag, JSON.toJSONString(socketMsg));
|
||||
FormalTestManager.freqConverterStep = SourceOperateCodeEnum.CMD_INIT_SERIAL;
|
||||
}
|
||||
|
||||
public void handleRead(String converterChannelTag, String msg) {
|
||||
FreqConverterRespDTO respDTO = JSON.parseObject(msg, FreqConverterRespDTO.class);
|
||||
|
||||
if (respDTO.getCode() != 0) {
|
||||
SocketDataMsg socketDataMsg = new SocketDataMsg();
|
||||
socketDataMsg.setRequestId(FormalTestManager.freqConverterStep.getValue());
|
||||
socketDataMsg.setCode(respDTO.getCode());
|
||||
WebServiceManager.sendMsg(this.userId, JSON.toJSONString(socketDataMsg));
|
||||
} else {
|
||||
switch (FormalTestManager.freqConverterStep) {
|
||||
case CMD_INIT_SERIAL:
|
||||
handleInitSerial(converterChannelTag, respDTO);
|
||||
break;
|
||||
case CMD_GET_DEVICE_STATUS:
|
||||
handleGetDeviceStatus(converterChannelTag, respDTO);
|
||||
break;
|
||||
case CMD_CLOSE_SERIAL:
|
||||
handleCloseSerial(converterChannelTag, respDTO);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void stopTest(String converterTag, String devTag) {
|
||||
FormalTestManager.freqConverterStep = SourceOperateCodeEnum.CMD_CLOSE_SERIAL;
|
||||
this.sendClose(converterTag);
|
||||
}
|
||||
|
||||
public void cleanup(String converterChannelTag) {
|
||||
String currentUserId = this.userId;
|
||||
clearScheduleTask();
|
||||
FormalTestManager.freqConverterStep = null;
|
||||
// FormalTestManager.stopFlag = false;
|
||||
FormalTestManager.isRemoveSocket = true;
|
||||
SocketManager.removeUser(converterChannelTag);
|
||||
updateCurrentTestStatus();
|
||||
clearStateIfStopped(currentUserId);
|
||||
this.userId = null;
|
||||
this.lastTolerancePoint = null;
|
||||
}
|
||||
|
||||
private void handleInitSerial(String converterChannelTag, FreqConverterRespDTO respDTO) {
|
||||
if (respDTO.getCode() == 0 && respDTO.getSuccess()) {
|
||||
FormalTestManager.freqConverterStep = SourceOperateCodeEnum.CMD_GET_DEVICE_STATUS;
|
||||
|
||||
if (Objects.isNull(FormalTestManager.scheduler)) {
|
||||
FormalTestManager.scheduler = Executors.newScheduledThreadPool(1);
|
||||
FormalTestManager.scheduledFuture = FormalTestManager.scheduler.scheduleAtFixedRate(() -> {
|
||||
this.sendGetDeviceStatusMsg(converterChannelTag);
|
||||
}, 0l, freqConverterConfig.getSchedulePeriod(), TimeUnit.MILLISECONDS);
|
||||
}
|
||||
} else {
|
||||
log.warn("变频器初始化串口失败,converterChannelTag={}, converterId={}, converterTag={}, msg={}", converterChannelTag, converterChannelTag, converterChannelTag, respDTO.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void handleGetDeviceStatus(String converterChannelTag, FreqConverterRespDTO respDTO) {
|
||||
JSONObject obj = JSONUtil.parseObj(respDTO.getData().toString());
|
||||
String timestamp = (String) obj.get("Timestamp");
|
||||
timestamp = timestamp.replace("+08:00", StrUtil.EMPTY);
|
||||
obj.set("Timestamp", timestamp);
|
||||
|
||||
FreqConverterStatus freqConverterStatus = JSON.parseObject(obj.toString(), FreqConverterStatus.class);
|
||||
// 变频器故障中,移除这段时期内的设备数据
|
||||
// if (freqConverterStatus.getStatusWord1() == freqConverterConfig.getNoTolerant()) {
|
||||
// FormalTestManager.stopFlag = true;
|
||||
// } else {
|
||||
// FormalTestManager.stopFlag = false;
|
||||
// }
|
||||
this.consumePendingDipTasks(freqConverterStatus);
|
||||
freqConverterService.saveFreqConverterStatus(FormalTestManager.freqConverterTableSuffix, freqConverterStatus);
|
||||
}
|
||||
|
||||
private void handleCloseSerial(String converterChannelTag, FreqConverterRespDTO respDTO) {
|
||||
if (respDTO.getCode() == 0 && respDTO.getSuccess()) {
|
||||
if (FormalTestManager.currentFreqConverterId != null) {
|
||||
pqFreqConverterConfigService.updateTestStatus(FormalTestManager.currentFreqConverterId, 1);
|
||||
}
|
||||
cleanup(converterChannelTag);
|
||||
} else {
|
||||
this.sendClose(converterChannelTag);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void sendGetDeviceStatusMsg(String converterId) {
|
||||
SocketMsg<Map<String, Object>> socketMsg = new SocketMsg<>();
|
||||
socketMsg.setOperateCode(SourceOperateCodeEnum.CMD_GET_DEVICE_STATUS.getValue());
|
||||
String requestId = IdUtil.fastSimpleUUID();
|
||||
socketMsg.setRequestId(requestId);
|
||||
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
socketMsg.setData(map);
|
||||
SocketManager.sendMsg(converterId, JSON.toJSONString(socketMsg));
|
||||
}
|
||||
|
||||
private void sendClose(String converterTag) {
|
||||
SocketMsg<Map<String, Object>> socketMsg = new SocketMsg<>();
|
||||
socketMsg.setOperateCode(SourceOperateCodeEnum.CMD_CLOSE_SERIAL.getValue());
|
||||
String requestId = IdUtil.fastSimpleUUID();
|
||||
socketMsg.setRequestId(requestId);
|
||||
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
socketMsg.setData(map);
|
||||
SocketManager.sendMsg(converterTag, JSON.toJSONString(socketMsg));
|
||||
}
|
||||
|
||||
|
||||
private void clearScheduleTask() {
|
||||
if (FormalTestManager.scheduledFuture != null) {
|
||||
FormalTestManager.scheduledFuture.cancel(true);
|
||||
FormalTestManager.scheduledFuture = null;
|
||||
}
|
||||
if (FormalTestManager.scheduler != null) {
|
||||
FormalTestManager.scheduler.shutdown();
|
||||
FormalTestManager.scheduler = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCurrentTestStatus() {
|
||||
if (StrUtil.isNotBlank(FormalTestManager.currentFreqConverterId)) {
|
||||
pqFreqConverterConfigService.updateTestStatus(FormalTestManager.currentFreqConverterId, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果变频器已停止,则清除共享的运行时状态
|
||||
*
|
||||
* @param currentUserId 当前用户ID
|
||||
*/
|
||||
private void clearStateIfStopped(String currentUserId) {
|
||||
if (StrUtil.isBlank(currentUserId)) {
|
||||
FormalTestManager.clearFreqConverterRuntimeState();
|
||||
return;
|
||||
}
|
||||
String devTag = currentUserId + CnSocketUtil.DEV_TAG;
|
||||
// 避免过早把 freqConverterTableSuffix 等全局值清掉,造成设备无法使用全局变量
|
||||
if (!SocketManager.isChannelActive(devTag)) {
|
||||
FormalTestManager.freqConverterDevStep = null;
|
||||
FormalTestManager.clearFreqConverterRuntimeState();
|
||||
}
|
||||
}
|
||||
|
||||
private void consumePendingDipTasks(FreqConverterStatus freqConverterStatus) {
|
||||
if (FormalTestManager.pendingDipTaskMap.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Integer suffix = FormalTestManager.freqConverterTableSuffix;
|
||||
List<String> finishedTestResIdList = new ArrayList<>();
|
||||
List<PqFreqConverterTestRes> saveTestResList = new ArrayList<>();
|
||||
List<PqFreqConverterTestRes> updateTestResList = new ArrayList<>();
|
||||
|
||||
FormalTestManager.pendingDipTaskMap.forEach((key, task) -> {
|
||||
if (freqConverterStatus.getTimestamp().isAfter(task.getTargetEndTime())) {
|
||||
PqFreqConverterTestRes testRes = new PqFreqConverterTestRes();
|
||||
testRes.setId(key);
|
||||
testRes.setDurationMs(task.getPqDipData().getDurationMs());
|
||||
testRes.setResidualVoltage(task.getPqDipData().getResidualVoltage());
|
||||
testRes.setTolerant(task.getOriginalTolerant() & (freqConverterStatus.getStatusWord1() == freqConverterConfig.getTolerant() ? 1 : 0));
|
||||
|
||||
finishedTestResIdList.add(key);
|
||||
|
||||
SocketDataMsg socketDataMsg = new SocketDataMsg();
|
||||
socketDataMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL + SocketFreqConverterDevService.DIP_DATA_SUFFIX);
|
||||
|
||||
TolerantPointVO newTolerantPointVO = new TolerantPointVO();
|
||||
newTolerantPointVO.setResidualVoltage(task.getPqDipData().getResidualVoltage());
|
||||
newTolerantPointVO.setDurationMs(task.getPqDipData().getDurationMs());
|
||||
newTolerantPointVO.setTolerant(testRes.getTolerant());
|
||||
socketDataMsg.setData(JSON.toJSONString(newTolerantPointVO));
|
||||
WebServiceManager.sendMsg(this.userId, JSON.toJSONString(socketDataMsg));
|
||||
|
||||
if (testRes.getTolerant() == 0) {
|
||||
if (ObjectUtil.isNotNull(this.lastTolerancePoint) && this.lastTolerancePoint.getTolerant() == 1) {
|
||||
TolerantPointVO featurePointVO = new TolerantPointVO();
|
||||
|
||||
featurePointVO.setResidualVoltage(Math.round((task.getPqDipData().getResidualVoltage() + this.lastTolerancePoint.getResidualVoltage()) / 2D * 100) / 100D);
|
||||
featurePointVO.setDurationMs(Integer.valueOf((task.getPqDipData().getDurationMs().intValue() + this.lastTolerancePoint.getDurationMs().intValue()) / 2));
|
||||
featurePointVO.setTolerant(2);
|
||||
socketDataMsg.setData(JSON.toJSONString(featurePointVO));
|
||||
WebServiceManager.sendMsg(this.userId, JSON.toJSONString(socketDataMsg));
|
||||
|
||||
PqFreqConverterTestRes featureTestRes = new PqFreqConverterTestRes();
|
||||
featureTestRes.setId(IdUtil.fastSimpleUUID());
|
||||
featureTestRes.setDurationMs(featurePointVO.getDurationMs());
|
||||
featureTestRes.setResidualVoltage(featurePointVO.getResidualVoltage());
|
||||
featureTestRes.setTolerant(2);
|
||||
featureTestRes.setTime(LocalDateTime.now());
|
||||
saveTestResList.add(featureTestRes);
|
||||
}
|
||||
|
||||
// 从数据库按照列查询距离该暂降点最近的一个暂降点
|
||||
if (freqConverterConfig.getDirection() == 0) {
|
||||
PqFreqConverterTestRes lastByDuration = pqFreqConverterTestResService.getLastByDuration(suffix, key, task.getPqDipData().getDurationMs());
|
||||
if (ObjectUtil.isNotNull(lastByDuration) && lastByDuration.getTolerant() == 1) {
|
||||
TolerantPointVO featurePointVO = new TolerantPointVO();
|
||||
|
||||
featurePointVO.setResidualVoltage(Math.round((task.getPqDipData().getResidualVoltage() + lastByDuration.getResidualVoltage()) / 2D * 100) / 100D);
|
||||
featurePointVO.setDurationMs(Integer.valueOf((task.getPqDipData().getDurationMs().intValue() + lastByDuration.getDurationMs().intValue()) / 2));
|
||||
featurePointVO.setTolerant(2);
|
||||
socketDataMsg.setData(JSON.toJSONString(featurePointVO));
|
||||
WebServiceManager.sendMsg(this.userId, JSON.toJSONString(socketDataMsg));
|
||||
|
||||
PqFreqConverterTestRes featureTestRes = new PqFreqConverterTestRes();
|
||||
featureTestRes.setId(IdUtil.fastSimpleUUID());
|
||||
featureTestRes.setDurationMs(featurePointVO.getDurationMs());
|
||||
featureTestRes.setResidualVoltage(featurePointVO.getResidualVoltage());
|
||||
featureTestRes.setTolerant(2);
|
||||
featureTestRes.setTime(LocalDateTime.now());
|
||||
saveTestResList.add(featureTestRes);
|
||||
}
|
||||
}
|
||||
// 从数据库按照行查询距离该暂降点最近的一个暂降点
|
||||
if (freqConverterConfig.getDirection() == 1) {
|
||||
PqFreqConverterTestRes lastByResidualVoltage = pqFreqConverterTestResService.getLastByResidualVoltage(suffix, key, task.getPqDipData().getResidualVoltage());
|
||||
if (ObjectUtil.isNotNull(lastByResidualVoltage) && lastByResidualVoltage.getTolerant() == 1) {
|
||||
TolerantPointVO featurePointVO = new TolerantPointVO();
|
||||
|
||||
featurePointVO.setResidualVoltage(Math.round((task.getPqDipData().getResidualVoltage() + lastByResidualVoltage.getResidualVoltage()) / 2D * 100) / 100D);
|
||||
featurePointVO.setDurationMs(Integer.valueOf((task.getPqDipData().getDurationMs().intValue() + lastByResidualVoltage.getDurationMs().intValue()) / 2));
|
||||
featurePointVO.setTolerant(2);
|
||||
socketDataMsg.setData(JSON.toJSONString(featurePointVO));
|
||||
WebServiceManager.sendMsg(this.userId, JSON.toJSONString(socketDataMsg));
|
||||
|
||||
PqFreqConverterTestRes featureTestRes = new PqFreqConverterTestRes();
|
||||
featureTestRes.setId(IdUtil.fastSimpleUUID());
|
||||
featureTestRes.setDurationMs(featurePointVO.getDurationMs());
|
||||
featureTestRes.setResidualVoltage(featurePointVO.getResidualVoltage());
|
||||
featureTestRes.setTolerant(2);
|
||||
featureTestRes.setTime(LocalDateTime.now());
|
||||
saveTestResList.add(featureTestRes);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.lastTolerancePoint = newTolerantPointVO;
|
||||
updateTestResList.add(testRes);
|
||||
}
|
||||
});
|
||||
|
||||
if (!saveTestResList.isEmpty()) {
|
||||
pqFreqConverterTestResService.saveTestRes(suffix, saveTestResList);
|
||||
}
|
||||
if (!updateTestResList.isEmpty()) {
|
||||
pqFreqConverterTestResService.updateTestRes(suffix, updateTestResList);
|
||||
}
|
||||
|
||||
for (String dipId : finishedTestResIdList) {
|
||||
FormalTestManager.pendingDipTaskMap.remove(dipId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为新的一组测试脚本
|
||||
*
|
||||
* @param lastTolerancePoint 上一个暂降点
|
||||
* @param newTolerantPointVO 最新的暂降点
|
||||
* @return
|
||||
*/
|
||||
private boolean isNewGroup(TolerantPointVO lastTolerancePoint, TolerantPointVO newTolerantPointVO) {
|
||||
// 横向分组
|
||||
if (freqConverterConfig.getDirection() == 0) {
|
||||
return lastTolerancePoint.getDurationMs() - newTolerantPointVO.getDurationMs() >= 10;
|
||||
}
|
||||
// 纵向分租
|
||||
if (freqConverterConfig.getDirection() == 1) {
|
||||
return lastTolerancePoint.getResidualVoltage() - newTolerantPointVO.getResidualVoltage() <= -2;
|
||||
}
|
||||
|
||||
// if (Math.abs(lastTolerancePoint.getDurationMs() - newTolerantPointVO.getDurationMs()) >= 10 && Math.abs(lastTolerancePoint.getResidualVoltage() - newTolerantPointVO.getResidualVoltage()) >= 2) {
|
||||
// return true;
|
||||
// }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.njcn.gather.detection.lock;
|
||||
|
||||
/**
|
||||
* 检测互斥锁对象(不可变)。
|
||||
* 字段含义见 docs/superpowers/specs/2026-05-28-单用户检测互斥-design.md §2.1
|
||||
*/
|
||||
public final class DetectionLock {
|
||||
|
||||
private final String userId;
|
||||
private final String userName;
|
||||
private final String userPageId;
|
||||
private final long acquireTime;
|
||||
private final long expireAt;
|
||||
|
||||
public DetectionLock(String userId, String userName, String userPageId,
|
||||
long acquireTime, long expireAt) {
|
||||
this.userId = userId;
|
||||
this.userName = userName;
|
||||
this.userPageId = userPageId;
|
||||
this.acquireTime = acquireTime;
|
||||
this.expireAt = expireAt;
|
||||
}
|
||||
|
||||
public String getUserId() { return userId; }
|
||||
public String getUserName() { return userName; }
|
||||
public String getUserPageId() { return userPageId; }
|
||||
public long getAcquireTime() { return acquireTime; }
|
||||
public long getExpireAt() { return expireAt; }
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.njcn.gather.detection.lock;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import com.njcn.gather.detection.pojo.vo.DetectionLockHolderVO;
|
||||
|
||||
/**
|
||||
* 检测互斥锁管理器(进程内单例)。
|
||||
* 详细设计:docs/superpowers/specs/2026-05-28-单用户检测互斥-design.md
|
||||
*/
|
||||
@Slf4j
|
||||
public final class DetectionLockManager {
|
||||
|
||||
private static final long LOCK_MAX_HOLD_MS = TimeUnit.HOURS.toMillis(4);
|
||||
|
||||
private static final DetectionLockManager INSTANCE = new DetectionLockManager();
|
||||
|
||||
public static DetectionLockManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private final AtomicReference<DetectionLock> current = new AtomicReference<>(null);
|
||||
|
||||
private DetectionLockManager() {}
|
||||
|
||||
/** 抢锁。同账号视为重入(刷新 page/expireAt)。 */
|
||||
public AcquireResult tryAcquire(String userId, String userName, String userPageId) {
|
||||
for (int attempt = 0; attempt < 2; attempt++) {
|
||||
DetectionLock cur = current.get();
|
||||
long now = System.currentTimeMillis();
|
||||
// 空闲 或 绝对超时已过 → 直接抢
|
||||
if (cur == null || now > cur.getExpireAt()) {
|
||||
DetectionLock fresh = new DetectionLock(userId, userName, userPageId, now, now + LOCK_MAX_HOLD_MS);
|
||||
if (current.compareAndSet(cur, fresh)) {
|
||||
log.info("DetectionLock acquired by userId={}, userName={}, userPageId={}", userId, userName, userPageId);
|
||||
return AcquireResult.ok();
|
||||
}
|
||||
continue; // CAS 失败重试
|
||||
}
|
||||
// 同账号重入 → 刷新
|
||||
if (userId.equals(cur.getUserId())) {
|
||||
DetectionLock refreshed = new DetectionLock(userId, userName, userPageId, now, now + LOCK_MAX_HOLD_MS);
|
||||
if (current.compareAndSet(cur, refreshed)) {
|
||||
log.debug("DetectionLock reentered by userId={}, new userPageId={}", userId, userPageId);
|
||||
return AcquireResult.ok();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// 被他人持有
|
||||
return AcquireResult.busy(toHolderVO(cur));
|
||||
}
|
||||
// 两次 CAS 都失败属于罕见高并发场景:绝不返回 ok()(那样会让调用方误以为持锁)。
|
||||
// 返回 busy,data 可能为 null(锁刚被释放);调用方/前端按"请重试"处理。
|
||||
DetectionLock cur = current.get();
|
||||
return AcquireResult.busy(cur == null ? null : toHolderVO(cur));
|
||||
}
|
||||
|
||||
/** 仅当 holder.userId == userId 才释放(幂等)。
|
||||
* 循环终止性:每轮 CAS 失败意味着 current 被其他线程改写;
|
||||
* 下一轮 get 后 cur 可能变成 null 或不再匹配 userId,命中前置 return 退出。
|
||||
* 唯一可能继续的情况是另一线程把它换成了同 userId 的新 lock,下一轮 CAS 会再次尝试;
|
||||
* 最坏情况下 CAS 成功,仍然终止。 */
|
||||
public void releaseIfHeldBy(String userId, String reason) {
|
||||
while (true) {
|
||||
DetectionLock cur = current.get();
|
||||
if (cur == null || !cur.getUserId().equals(userId)) return;
|
||||
if (current.compareAndSet(cur, null)) {
|
||||
log.info("DetectionLock released, reason={}, userId={}", reason, userId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅当 holder.userPageId == userPageId 才释放(幂等)。终止性同 releaseIfHeldBy。 */
|
||||
public void releaseIfMatchPage(String userPageId, String reason) {
|
||||
while (true) {
|
||||
DetectionLock cur = current.get();
|
||||
if (cur == null || !cur.getUserPageId().equals(userPageId)) return;
|
||||
if (current.compareAndSet(cur, null)) {
|
||||
log.info("DetectionLock released, reason={}, userPageId={}", reason, userPageId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 管理员强制释放,不校验 holder。 */
|
||||
public void forceRelease(String operatorUserId, String reason) {
|
||||
DetectionLock cur = current.getAndSet(null);
|
||||
if (cur != null) {
|
||||
log.warn("DetectionLock force-released by operator={}, victim userId={}, reason={}",
|
||||
operatorUserId, cur.getUserId(), reason);
|
||||
}
|
||||
}
|
||||
|
||||
/** 返回当前 holder 快照;返回 null 表示空闲。 */
|
||||
public DetectionLock getCurrent() {
|
||||
DetectionLock cur = current.get();
|
||||
// 顺手做惰性超时回收(spec R5)
|
||||
if (cur != null && System.currentTimeMillis() > cur.getExpireAt()) {
|
||||
current.compareAndSet(cur, null);
|
||||
return null;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
/** 把 DetectionLock 转成给前端的 VO。 */
|
||||
public static DetectionLockHolderVO toHolderVO(DetectionLock lock) {
|
||||
DetectionLockHolderVO vo = new DetectionLockHolderVO();
|
||||
vo.setHolderUserId(lock.getUserId());
|
||||
vo.setHolderUserName(lock.getUserName());
|
||||
vo.setAcquireTime(new Date(lock.getAcquireTime()));
|
||||
vo.setExpireAt(new Date(lock.getExpireAt()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 抢锁结果。 */
|
||||
public static final class AcquireResult {
|
||||
private final boolean ok;
|
||||
private final DetectionLockHolderVO holder;
|
||||
|
||||
private AcquireResult(boolean ok, DetectionLockHolderVO holder) {
|
||||
this.ok = ok;
|
||||
this.holder = holder;
|
||||
}
|
||||
public static AcquireResult ok() { return new AcquireResult(true, null); }
|
||||
public static AcquireResult busy(DetectionLockHolderVO holder) { return new AcquireResult(false, holder); }
|
||||
public boolean isOk() { return ok; }
|
||||
public DetectionLockHolderVO getHolder() { return holder; }
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.njcn.gather.detection.pojo.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-08
|
||||
*/
|
||||
@Data
|
||||
public class FreqConverterRespDTO {
|
||||
/**
|
||||
* 请求编号
|
||||
*/
|
||||
@JsonAlias({"RequestId"})
|
||||
private String requestId;
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
@JsonAlias({"Success"})
|
||||
private Boolean success;
|
||||
|
||||
/**
|
||||
* 状态码
|
||||
*/
|
||||
@JsonAlias({"Code"})
|
||||
private Integer code;
|
||||
|
||||
/**
|
||||
* 消息
|
||||
*/
|
||||
@JsonAlias({"Message"})
|
||||
private String message;
|
||||
|
||||
/**
|
||||
* 数据
|
||||
*/
|
||||
@JsonAlias({"Data"})
|
||||
private Object data;
|
||||
}
|
||||
@@ -20,7 +20,7 @@ public enum DetectionResponseEnum {
|
||||
|
||||
SCRIPT_CHECK_DATA_NOT_EXIST("A020040","测试脚本项暂无配置" ),
|
||||
EXCEED_MAX_TIME("A020041","检测次数超出最大限制!" ),
|
||||
SOCKET_CONNECT_TIMEOUT("A020042","socket连接超时!");
|
||||
DETECTION_BUSY("A020042", "检测进行中");
|
||||
|
||||
private final String code;
|
||||
private final String message;
|
||||
|
||||
@@ -52,7 +52,7 @@ public enum SourceOperateCodeEnum {
|
||||
YJC_MXYZXJY("yjc_mxyzxjy", "模型一致性校验"),
|
||||
FORMAL_REAL("formal_real","正式检测"),
|
||||
RECORD_WAVE_STEP1("record_wave_step1","启动录波_step1"),
|
||||
// RECORD_WAVE_STEP2("record_wave_step2","启动录波_step2"),
|
||||
// RECORD_WAVE_STEP2("record_wave_step2","启动录波_step2"),
|
||||
// SIMULATE_REAL("simulate_real","模拟检测"),
|
||||
Coefficient_Check("Coefficient_Check","系数校验"),
|
||||
QUITE("quit","关闭设备通讯初始化"),
|
||||
@@ -70,6 +70,9 @@ public enum SourceOperateCodeEnum {
|
||||
FLICKER_DATA_CHECK("flicker_data_check","闪变数据校验"),
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@@ -97,17 +100,12 @@ public enum SourceOperateCodeEnum {
|
||||
small_comp_start("small_comp_start","小电压校准开始"),
|
||||
small_comp_end("small_comp_end","小电压校准结束"),
|
||||
|
||||
|
||||
/**
|
||||
* ftp文件传送指令
|
||||
*/
|
||||
FTP_SEND_01("FTP_SEND$01", "发送文件"),
|
||||
RDRE$01("RDRE$01", "启动录波"),
|
||||
|
||||
CMD_PING("ping", "检查 TCP 服务是否在线"),
|
||||
CMD_INIT_SERIAL("initSerial", "初始化并打开串口连接"),
|
||||
CMD_GET_SERIAL_CONFIG("getSerialConfig", "获取当前串口配置"),
|
||||
CMD_GET_DEVICE_STATUS("getDeviceStatus", "读取变频器运行状态"),
|
||||
CMD_CLOSE_SERIAL("closeSerial", "关闭串口"),;
|
||||
RDRE$01("RDRE$01", "启动录波");
|
||||
|
||||
private final String value;
|
||||
private final String msg;
|
||||
|
||||
@@ -46,6 +46,11 @@ public class PreDetectionParam {
|
||||
*/
|
||||
private String sourceId;
|
||||
|
||||
/**
|
||||
* 源名称
|
||||
*/
|
||||
private String sourceName;
|
||||
|
||||
/**
|
||||
* 所属误差体系
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.njcn.gather.detection.pojo.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 检测锁持有者信息,用于在抢锁失败响应中返回给前端。
|
||||
*/
|
||||
@Data
|
||||
public class DetectionLockHolderVO {
|
||||
|
||||
private String holderUserId;
|
||||
private String holderUserName;
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private Date acquireTime;
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private Date expireAt;
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
|
||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* @author wr
|
||||
@@ -52,6 +55,7 @@ public interface PreDetectionService {
|
||||
void closeTestSimulate(SimulateDetectionParam param);
|
||||
|
||||
/**
|
||||
*
|
||||
* @param param
|
||||
*/
|
||||
void startContrastTest(ContrastDetectionParam param);
|
||||
@@ -64,8 +68,4 @@ public interface PreDetectionService {
|
||||
boolean getCanCoefficient();
|
||||
|
||||
void startCoefficient();
|
||||
|
||||
void startFreqConverter(String userId, String converterId, String monitorId,Boolean reset);
|
||||
|
||||
void stopFreqConverter(String converterId, String monitorId);
|
||||
}
|
||||
|
||||
@@ -446,7 +446,9 @@ public class DetectionServiceImpl {
|
||||
fData = sourceIssue.getFFreq();
|
||||
}
|
||||
if (P.equals(type)) {
|
||||
fData = sourceIssue.getFUn() * sourceIssue.getFIn();
|
||||
fData = sourceIssue.getFUn() * sourceIssue.getFIn() * 0.01;
|
||||
Double finalFData = fData;
|
||||
errDtlsCheckData.stream().forEach(x -> x.setValue(x.getValue() * finalFData));
|
||||
}
|
||||
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
|
||||
String[] split = dev.get(0).getId().split("_");
|
||||
|
||||
@@ -6,7 +6,9 @@ import cn.hutool.core.util.ObjectUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.njcn.common.pojo.exception.BusinessException;
|
||||
import com.njcn.gather.detection.handler.*;
|
||||
import com.njcn.gather.detection.handler.SocketContrastResponseService;
|
||||
import com.njcn.gather.detection.handler.SocketDevResponseService;
|
||||
import com.njcn.gather.detection.handler.SocketSourceResponseService;
|
||||
import com.njcn.gather.detection.pojo.constant.DetectionCommunicateConstant;
|
||||
import com.njcn.gather.detection.pojo.enums.DetectionResponseEnum;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
@@ -39,6 +41,7 @@ import com.njcn.gather.script.service.IPqScriptDtlsService;
|
||||
import com.njcn.gather.source.pojo.po.SourceInitialize;
|
||||
import com.njcn.gather.source.service.IPqSourceService;
|
||||
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
|
||||
import com.njcn.gather.system.config.PathConfig;
|
||||
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
|
||||
import com.njcn.gather.system.dictionary.service.IDictDataService;
|
||||
import com.njcn.web.utils.HttpServletUtil;
|
||||
@@ -51,6 +54,7 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -74,15 +78,14 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
private final SocketDevResponseService socketDevResponseService;
|
||||
private final SocketSourceResponseService socketSourceResponseService;
|
||||
private final SocketContrastResponseService socketContrastResponseService;
|
||||
private final SocketFreqConverterService socketFreqConverterService;
|
||||
private final SocketFreqConverterDevService socketFreqConverterDevService;
|
||||
private final IPqScriptCheckDataService iPqScriptCheckDataService;
|
||||
private final SocketManager socketManager;
|
||||
private final ISysTestConfigService sysTestConfigService;
|
||||
|
||||
|
||||
@Value("${report.reportDir}")
|
||||
private String alignDataFilePath;
|
||||
// @Value("${report.reportDir}")
|
||||
// private String alignDataFilePath;
|
||||
private final PathConfig pathConfig;
|
||||
|
||||
|
||||
@Override
|
||||
@@ -135,6 +138,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
);
|
||||
if (ObjectUtil.isNotNull(planSource)) {
|
||||
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(planSource.getSourceId());
|
||||
param.setSourceName(sourceParam.getSourceId());
|
||||
if (ObjectUtil.isNotNull(sourceParam)) {
|
||||
//开始组装socket报文请求头
|
||||
socketDevResponseService.initList(param);
|
||||
@@ -181,6 +185,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
if (ObjectUtil.isNotNull(planSource)) {
|
||||
//获取源初始化参数
|
||||
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(planSource.getSourceId());
|
||||
param.setSourceName(sourceParam.getSourceId());
|
||||
if (ObjectUtil.isNotNull(sourceParam)) {
|
||||
//开始组装socket报文请求头
|
||||
socketDevResponseService.initList(param);
|
||||
@@ -243,6 +248,8 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
FormalTestManager.stopFlag = false;
|
||||
socketDevResponseService.initRestart();
|
||||
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
|
||||
SourceInitialize sourceInitialize = pqSourceService.getSourceInitializeParam(param.getSourceId());
|
||||
param.setSourceName(sourceInitialize.getSourceId());
|
||||
if (CollUtil.isNotEmpty(sourceIssueList)) {
|
||||
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
|
||||
SocketMsg<String> xuMsg = new SocketMsg<>();
|
||||
@@ -258,7 +265,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
checkDataParam.setIsValueTypeName(false);
|
||||
List<String> adType = iPqScriptCheckDataService.getValueType(checkDataParam);
|
||||
|
||||
iPqDevService.updateResult(param.getDevIds(), adType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity());
|
||||
iPqDevService.updateResult(param.getDevIds(), adType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), true);
|
||||
CnSocketUtil.quitSend(param);
|
||||
}
|
||||
|
||||
@@ -289,7 +296,8 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
}
|
||||
//组装源控制脚本
|
||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||
issueParam.setSourceId(param.getSourceId());
|
||||
SourceInitialize sourceInitialize = pqSourceService.getSourceInitializeParam(param.getSourceId());
|
||||
issueParam.setSourceId(sourceInitialize.getSourceId());
|
||||
issueParam.setScriptId(param.getScriptId());
|
||||
issueParam.setType(1);
|
||||
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.SIMULATE_TEST.getValue());
|
||||
@@ -348,7 +356,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
|
||||
response.setContentType("application/octet-stream;charset=UTF-8");
|
||||
try {
|
||||
InputStream inputStream = new FileInputStream(alignDataFilePath + "\\" + fileName);
|
||||
InputStream inputStream = new FileInputStream(pathConfig.getDataPath() + File.separator + fileName);
|
||||
byte[] buffer = new byte[1024];
|
||||
int len = 0;
|
||||
ServletOutputStream outputStream = response.getOutputStream();
|
||||
@@ -393,38 +401,6 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startFreqConverter(String userId, String converterId, String monitorId, Boolean reset) {
|
||||
String freqConverterTag = userId + CnSocketUtil.FREQ_CONVERTER_TAG;
|
||||
String devTag = userId + CnSocketUtil.DEV_TAG;
|
||||
// socketFreqConverterService.init(userId, converterId, monitorId);
|
||||
socketFreqConverterService.connectSocket(freqConverterTag);
|
||||
socketFreqConverterDevService.connectSocket(devTag);
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
long timeout = 3000; // 3秒超时时间
|
||||
while (true) {
|
||||
if (SocketManager.isChannelActive(freqConverterTag) && SocketManager.isChannelActive(devTag)) {
|
||||
// if (SocketManager.isChannelActive(devTag)) {
|
||||
socketFreqConverterService.connectionFreqConverter(userId, freqConverterTag, converterId, monitorId, reset);
|
||||
socketFreqConverterDevService.connectionDev(userId, devTag, converterId, monitorId,reset);
|
||||
break;
|
||||
}
|
||||
|
||||
// 检查是否超时
|
||||
if (System.currentTimeMillis() - startTime > timeout) {
|
||||
throw new BusinessException(DetectionResponseEnum.SOCKET_CONNECT_TIMEOUT);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopFreqConverter(String converterTag, String devTag) {
|
||||
socketFreqConverterService.stopTest(converterTag, devTag);
|
||||
socketFreqConverterDevService.stopTest(converterTag, devTag);
|
||||
}
|
||||
|
||||
/**
|
||||
* 比对式-与通信模块进行连接
|
||||
*
|
||||
@@ -483,4 +459,4 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,6 @@ import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
|
||||
*/
|
||||
public class CnSocketUtil {
|
||||
|
||||
public final static String FREQ_CONVERTER_TAG="_FreqConverter";
|
||||
|
||||
public final static String DEV_TAG = "_Dev";
|
||||
|
||||
public final static String CONTRAST_DEV_TAG = "_Contrast_Dev";
|
||||
@@ -49,7 +47,7 @@ public class CnSocketUtil {
|
||||
socketMsg.setRequestId(SourceOperateCodeEnum.QUITE_SOURCE.getValue());
|
||||
socketMsg.setOperateCode(SourceOperateCodeEnum.CLOSE_GATHER.getValue());
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("sourceId", param.getSourceId());
|
||||
jsonObject.put("sourceId", param.getSourceName());
|
||||
socketMsg.setData(jsonObject.toJSONString());
|
||||
SocketManager.sendMsg(param.getUserPageId() + SOURCE_TAG, JSON.toJSONString(socketMsg));
|
||||
WebServiceManager.removePreDetectionParam(param.getUserPageId());
|
||||
|
||||
@@ -7,15 +7,12 @@ import com.njcn.gather.detection.pojo.po.DevData;
|
||||
import com.njcn.gather.detection.pojo.vo.DevLineTestResult;
|
||||
import com.njcn.gather.device.pojo.enums.PatternEnum;
|
||||
import com.njcn.gather.device.pojo.vo.PreDetection;
|
||||
import com.njcn.gather.dip.pojo.po.PqDipData;
|
||||
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
|
||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||
import com.njcn.gather.plan.pojo.po.AdPlanTestConfig;
|
||||
import com.njcn.gather.script.pojo.po.SourceIssue;
|
||||
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -34,20 +31,6 @@ public class FormalTestManager {
|
||||
// 当前步骤
|
||||
public static SourceOperateCodeEnum currentStep;
|
||||
|
||||
public static SourceOperateCodeEnum freqConverterStep;
|
||||
public static SourceOperateCodeEnum freqConverterDevStep;
|
||||
/**
|
||||
* 变频器存放数据的表后缀
|
||||
*/
|
||||
public static Integer freqConverterTableSuffix;
|
||||
|
||||
public static String currentFreqConverterId;
|
||||
|
||||
/**
|
||||
* 待采集后续变频器状态的Dip任务
|
||||
*/
|
||||
public static Map<String, PendingDipTask> pendingDipTaskMap = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* key:设备ip,value:当前设备下面的监测点ID(ip_通道号)
|
||||
*/
|
||||
@@ -225,27 +208,4 @@ public class FormalTestManager {
|
||||
* 是否进行相序校验
|
||||
*/
|
||||
public static boolean isXu;
|
||||
|
||||
/**
|
||||
* 清理变频器耐受实验运行态数据
|
||||
*/
|
||||
public static void clearFreqConverterRuntimeState() {
|
||||
currentFreqConverterId = null;
|
||||
freqConverterTableSuffix = null;
|
||||
pendingDipTaskMap.clear();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class PendingDipTask {
|
||||
private PqDipData pqDipData;
|
||||
|
||||
private LocalDateTime targetEndTime;
|
||||
private Integer originalTolerant;
|
||||
|
||||
public PendingDipTask(PqDipData pqDipData, LocalDateTime targetEndTime, Integer originalTolerant) {
|
||||
this.pqDipData = pqDipData;
|
||||
this.targetEndTime = targetEndTime;
|
||||
this.originalTolerant = originalTolerant;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,4 +315,4 @@ public class SocketManager {
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSON;
|
||||
import com.njcn.gather.detection.handler.SocketContrastResponseService;
|
||||
import com.njcn.gather.detection.handler.SocketDevResponseService;
|
||||
import com.njcn.gather.detection.handler.SocketSourceResponseService;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
|
||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||
@@ -26,6 +27,8 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.Resource;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
@@ -42,6 +45,20 @@ import java.util.concurrent.TimeUnit;
|
||||
@Component
|
||||
public class NettyClient {
|
||||
|
||||
// ========== TODO TEST-ONLY: 联调 BUSY 弹窗用,测试完成后整段删除 ==========
|
||||
/**
|
||||
* 测试期:连接源/设备失败时,延迟若干秒再释放检测锁,方便手动测试 BUSY 弹窗。
|
||||
* 正式上线时把 RELEASE_DELAY_FOR_TEST_SECONDS 改回 0 或直接删除调度逻辑。
|
||||
*/
|
||||
private static final long RELEASE_DELAY_FOR_TEST_SECONDS = 300L;
|
||||
private static final ScheduledExecutorService DELAYED_RELEASER =
|
||||
Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "lock-release-delay-test");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
// ========== /TODO TEST-ONLY ==========
|
||||
|
||||
@Resource
|
||||
private SocketSourceResponseService socketSourceResponseService;
|
||||
|
||||
@@ -56,109 +73,6 @@ public class NettyClient {
|
||||
*/
|
||||
private static NettyClient instance;
|
||||
|
||||
/**
|
||||
* 静态方法:智能连接变频器设备(兼容性包装)
|
||||
*
|
||||
* @param ip IP地址
|
||||
* @param port 端口号
|
||||
* @param ChannelId Channel唯一标识
|
||||
* @param handler 变频器处理器
|
||||
*/
|
||||
public static void commonConnect(String ip, Integer port, String ChannelId,
|
||||
SimpleChannelInboundHandler handler) {
|
||||
if (instance != null) {
|
||||
instance.executeCommonConnect(ip, port, ChannelId, handler);
|
||||
} else {
|
||||
log.error("NettyClient未初始化,无法创建连接");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行变频器Socket连接建立流程
|
||||
*
|
||||
* @param ip 目标服务器IP地址
|
||||
* @param port 目标服务器端口号
|
||||
* @param ChannelId Channel唯一标识id
|
||||
* @param handler 变频器业务处理器
|
||||
*/
|
||||
private static void executeCommonConnect(String ip, Integer port,
|
||||
String ChannelId,
|
||||
SimpleChannelInboundHandler handler) {
|
||||
NioEventLoopGroup group = createEventLoopGroup();
|
||||
|
||||
try {
|
||||
Bootstrap bootstrap = configureBootstrap(group);
|
||||
ChannelInitializer<NioSocketChannel> initializer = createCommonChannelInitializer(ChannelId, handler);
|
||||
bootstrap.handler(initializer);
|
||||
ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
|
||||
handleCommonConnectionResult(channelFuture, ChannelId, handler, group);
|
||||
} catch (Exception e) {
|
||||
handleCommonConnectionException(e, ChannelId, handler, group);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建通用通道初始化器
|
||||
*
|
||||
* @param channelId Channel唯一标识id
|
||||
* @param handler 通用业务处理器
|
||||
* @return ChannelInitializer 通道初始化器
|
||||
*/
|
||||
private static ChannelInitializer<NioSocketChannel> createCommonChannelInitializer(
|
||||
String channelId, SimpleChannelInboundHandler handler) {
|
||||
return new ChannelInitializer<NioSocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(NioSocketChannel ch) {
|
||||
ch.pipeline()
|
||||
.addLast(new LineBasedFrameDecoder(10240 * 2))
|
||||
.addLast(new StringDecoder(CharsetUtil.UTF_8))
|
||||
.addLast(new StringEncoder(CharsetUtil.UTF_8))
|
||||
.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS))
|
||||
.addLast(handler);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理通用连接结果
|
||||
*
|
||||
* @param channelFuture 连接Future对象
|
||||
* @param channelId Channel唯一标识符
|
||||
* @param handler 通用业务处理器
|
||||
* @param group 事件循环组
|
||||
*/
|
||||
private static void handleCommonConnectionResult(ChannelFuture channelFuture,
|
||||
String channelId,
|
||||
SimpleChannelInboundHandler handler,
|
||||
NioEventLoopGroup group) {
|
||||
channelFuture.addListener((ChannelFutureListener) ch -> {
|
||||
if (!ch.isSuccess()) {
|
||||
log.error("连接Socket失败,channelId={}", channelId);
|
||||
group.shutdownGracefully();
|
||||
} else {
|
||||
log.info("连接Socket成功,channel={}, channelId={}",
|
||||
channelId, channelFuture.channel().id());
|
||||
SocketManager.addGroup(channelId, group);
|
||||
SocketManager.addUser(channelId, channelFuture.channel());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理通用连接异常
|
||||
*
|
||||
* @param e 异常对象
|
||||
* @param channelId Channel唯一标识id
|
||||
* @param handler 通用业务处理器
|
||||
* @param group 事件循环组
|
||||
*/
|
||||
private static void handleCommonConnectionException(Exception e, String channelId,
|
||||
SimpleChannelInboundHandler handler,
|
||||
NioEventLoopGroup group) {
|
||||
log.error("连接Socket服务端发生异常,channelId={}, error={}", channelId, e.getMessage(), e);
|
||||
group.shutdownGracefully();
|
||||
}
|
||||
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
@@ -452,7 +366,7 @@ public class NettyClient {
|
||||
NioEventLoopGroup group, String msg) {
|
||||
channelFuture.addListener((ChannelFutureListener) ch -> {
|
||||
if (!ch.isSuccess()) {
|
||||
onConnectionFailure(handler, group);
|
||||
onConnectionFailure(param, handler, group);
|
||||
} else {
|
||||
onConnectionSuccess(channelFuture, param, handler, group, msg);
|
||||
}
|
||||
@@ -461,15 +375,30 @@ public class NettyClient {
|
||||
|
||||
/**
|
||||
* 连接失败处理
|
||||
* 输出失败信息并优雅关闭事件循环组
|
||||
* 输出失败信息、优雅关闭事件循环组、通知前端、释放检测锁
|
||||
*
|
||||
* @param param 检测参数,用于定位锁与前端通知
|
||||
* @param handler 业务处理器,用于区分设备类型
|
||||
* @param group 事件循环组
|
||||
*/
|
||||
private static void onConnectionFailure(SimpleChannelInboundHandler<String> handler, NioEventLoopGroup group) {
|
||||
private static void onConnectionFailure(PreDetectionParam param,
|
||||
SimpleChannelInboundHandler<String> handler, NioEventLoopGroup group) {
|
||||
String deviceType = getDeviceType(handler);
|
||||
log.info("连接{}服务端失败...", deviceType);
|
||||
group.shutdownGracefully();
|
||||
// 异步建连失败时前端原本静默,补一次通知避免用户黑屏等待
|
||||
notifyFrontendError(param, handler);
|
||||
// 释放检测锁:抢锁后由 controller 异步发起的建连若失败,无法走 controller 兜底
|
||||
// TODO TEST-ONLY: 测试 BUSY 弹窗期间延迟释放,正式部署改回立即释放
|
||||
if (param != null && param.getUserPageId() != null) {
|
||||
final String userPageId = param.getUserPageId();
|
||||
DELAYED_RELEASER.schedule(
|
||||
() -> DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(userPageId, "ASYNC_CONNECT_FAILED_DELAYED"),
|
||||
RELEASE_DELAY_FOR_TEST_SECONDS, TimeUnit.SECONDS);
|
||||
log.warn("[TEST-ONLY] 检测锁将在 {}s 后释放(连接失败延迟释放,便于测试 BUSY 弹窗),userPageId={}",
|
||||
RELEASE_DELAY_FOR_TEST_SECONDS, userPageId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -558,6 +487,18 @@ public class NettyClient {
|
||||
|
||||
// 通过WebSocket通知前端页面
|
||||
notifyFrontendError(param, handler);
|
||||
|
||||
// 释放检测锁,理由同 onConnectionFailure
|
||||
// TODO TEST-ONLY: 测试 BUSY 弹窗期间延迟释放,正式部署改回立即释放
|
||||
if (param != null && param.getUserPageId() != null) {
|
||||
final String userPageId = param.getUserPageId();
|
||||
DELAYED_RELEASER.schedule(
|
||||
() -> DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(userPageId, "ASYNC_CONNECT_EXCEPTION_DELAYED"),
|
||||
RELEASE_DELAY_FOR_TEST_SECONDS, TimeUnit.SECONDS);
|
||||
log.warn("[TEST-ONLY] 检测锁将在 {}s 后释放(连接异常延迟释放,便于测试 BUSY 弹窗),userPageId={}",
|
||||
RELEASE_DELAY_FOR_TEST_SECONDS, userPageId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.njcn.gather.detection.util.socket.cilent;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.njcn.gather.detection.handler.SocketContrastResponseService;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||
@@ -68,6 +69,11 @@ public class NettyContrastClientHandler extends SimpleChannelInboundHandler<Stri
|
||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_01, false);
|
||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_02, false);
|
||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_03, true);
|
||||
// 业务消息处理异常 → 释放检测锁
|
||||
if (param != null && param.getUserPageId() != null) {
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "CONTRAST_READ_EXCEPTION");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +82,11 @@ public class NettyContrastClientHandler extends SimpleChannelInboundHandler<Stri
|
||||
System.out.println("与通信模块端断线");
|
||||
ctx.close();
|
||||
SocketManager.removeUser(param.getUserPageId() + CnSocketUtil.CONTRAST_DEV_TAG);
|
||||
// 比对通信模块主动断开 → 本次检测视为结束,释放检测锁
|
||||
if (param != null && param.getUserPageId() != null) {
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "CONTRAST_CHANNEL_INACTIVE");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,11 +161,18 @@ public class NettyContrastClientHandler extends SimpleChannelInboundHandler<Stri
|
||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_02, false);
|
||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_03, true);
|
||||
ctx.close();
|
||||
// 比对通道异常 → 释放检测锁
|
||||
if (param != null && param.getUserPageId() != null) {
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "CONTRAST_EXCEPTION");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 接收数据超时处理
|
||||
* 比对模式读超时(10 分钟 Pst / 1 分钟实时 / 动态统计)都汇到这里,
|
||||
* 推前端的同时一并释放检测锁(避免锁卡到 4 小时绝对超时)。
|
||||
*/
|
||||
private void timeoutSend(SourceOperateCodeEnum sourceOperateCodeEnum) {
|
||||
System.out.println("超时处理-----》" + "统计数据已超时----------------关闭");
|
||||
@@ -164,6 +182,11 @@ public class NettyContrastClientHandler extends SimpleChannelInboundHandler<Stri
|
||||
webSend.setData(sourceOperateCodeEnum.getMsg() + SourceResponseCodeEnum.RECEIVE_DATA_TIME_OUT.getMessage());
|
||||
webSend.setCode(SourceResponseCodeEnum.RECEIVE_DATA_TIME_OUT.getCode());
|
||||
WebServiceManager.sendMsg(param.getUserPageId(), MsgUtil.msgToWebData(webSend, FormalTestManager.devNameMapComm, 0));
|
||||
// 比对模式读超时终态 → 释放检测锁
|
||||
if (param != null && param.getUserPageId() != null) {
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "CONTRAST_IDLE_TIMEOUT");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.njcn.gather.detection.util.socket.cilent;
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.njcn.gather.detection.handler.SocketDevResponseService;
|
||||
import com.njcn.gather.detection.lock.DetectionLock;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||
import com.njcn.gather.detection.pojo.enums.ResultEnum;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||
@@ -115,6 +117,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
||||
ctx.close();
|
||||
SocketManager.removeUser(param.getUserPageId() + CnSocketUtil.DEV_TAG);
|
||||
CnSocketUtil.quitSendSource(param);
|
||||
// 设备主动断开 → 本次检测视为结束,释放检测锁
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "DEV_CHANNEL_INACTIVE");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,6 +137,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
||||
} catch (Exception e) {
|
||||
log.error("处理服务端消息异常", e);
|
||||
CnSocketUtil.quitSend(param);
|
||||
// 业务消息处理异常 → 退出并释放检测锁
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "DEV_READ_EXCEPTION");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +195,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
||||
CnSocketUtil.quitSendSource(param);
|
||||
socketResponseService.backCheckState(param);
|
||||
ctx.close();
|
||||
// 通道异常 → 释放检测锁
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "DEV_EXCEPTION");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -231,6 +242,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
||||
CnSocketUtil.quitSend(param);
|
||||
WebServiceManager.sendDetectionErrorMessage(param.getUserPageId(), SourceOperateCodeEnum.SOCKET_TIMEOUT);
|
||||
socketResponseService.backCheckState(param);
|
||||
// 常规步骤读超时兜底 → 释放检测锁
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "DEV_READ_TIMEOUT");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,6 +258,14 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
||||
if (FormalTestManager.stopTime > STOP_TIMEOUT) {
|
||||
CnSocketUtil.quitSend(param);
|
||||
WebServiceManager.sendDetectionErrorMessage(param.getUserPageId(), SourceOperateCodeEnum.FORMAL_REAL.getValue(), SourceOperateCodeEnum.STOP_TIMEOUT);
|
||||
// R4 释放:暂停 10 分钟超时视同放弃本次检测
|
||||
DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
|
||||
if (cur != null) {
|
||||
DetectionLockManager.getInstance().releaseIfHeldBy(cur.getUserId(), "PAUSE_TIMEOUT");
|
||||
}
|
||||
// 重置 FormalTestManager 状态,避免下次进入误判
|
||||
FormalTestManager.stopTime = 0;
|
||||
FormalTestManager.hasStopFlag = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,6 +324,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
||||
CnSocketUtil.quitSend(param);
|
||||
timeoutSend(sourceIssue);
|
||||
socketResponseService.backCheckState(param);
|
||||
// 单项检测超时本质等于整轮中止(已 quitSend),释放检测锁
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(param.getUserPageId(), "DEV_ITEM_TIMEOUT");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
package com.njcn.gather.detection.util.socket.cilent;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.njcn.gather.detection.handler.SocketFreqConverterService;
|
||||
import com.njcn.gather.detection.util.socket.FormalTestManager;
|
||||
import com.njcn.gather.detection.util.socket.SocketManager;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import io.netty.handler.timeout.IdleState;
|
||||
import io.netty.handler.timeout.IdleStateEvent;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 变频器Netty客户端处理器
|
||||
*/
|
||||
@Slf4j
|
||||
public class NettyFreqConverterClientHandler extends SimpleChannelInboundHandler<String> {
|
||||
|
||||
/**
|
||||
* 变频器Channel唯一标识符
|
||||
*/
|
||||
private final String converterChannelTag;
|
||||
|
||||
|
||||
/**
|
||||
* 变频器Socket响应服务
|
||||
*/
|
||||
private final SocketFreqConverterService socketFreqConverterService;
|
||||
|
||||
/**
|
||||
* 重连次数
|
||||
*/
|
||||
private int reconnectAttempts = 0;
|
||||
|
||||
/**
|
||||
* 最大重连次数
|
||||
*/
|
||||
private static final int MAX_RECONNECT_ATTEMPTS = 3;
|
||||
|
||||
/**
|
||||
* 重连间隔(毫秒)
|
||||
*/
|
||||
private static final long RECONNECT_INTERVAL_MS = 5000;
|
||||
|
||||
/**
|
||||
* 是否正在重连
|
||||
*/
|
||||
private volatile boolean isReconnecting = false;
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
*
|
||||
* @param converterChannelTag 变频器Chanel唯一标识符
|
||||
* @param socketFreqConverterService 变频器Socket响应服务
|
||||
*/
|
||||
public NettyFreqConverterClientHandler(String converterChannelTag, SocketFreqConverterService socketFreqConverterService) {
|
||||
this.converterChannelTag = converterChannelTag;
|
||||
this.socketFreqConverterService = socketFreqConverterService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
||||
log.info("变频器连接已建立,converterChannelTag={}, channelId={}", converterChannelTag, ctx.channel().id());
|
||||
|
||||
// 注册Channel到SocketManager
|
||||
SocketManager.addUser(converterChannelTag, ctx.channel());
|
||||
|
||||
if (reconnectAttempts > 0) {
|
||||
log.info("变频器重连成功,converterChannelTag={}, 重连次数={}", converterChannelTag, reconnectAttempts);
|
||||
reconnectAttempts = 0;
|
||||
isReconnecting = false;
|
||||
socketFreqConverterService.onReconnectSuccess(converterChannelTag);
|
||||
}
|
||||
|
||||
super.channelActive(ctx);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
|
||||
if (StrUtil.isBlank(msg)) {
|
||||
log.debug("收到空消息,忽略,converterChannelTag={}", converterChannelTag);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("收到变频器消息,converterChannelTag={}, msg={}", converterChannelTag, msg);
|
||||
|
||||
// 处理状态数据
|
||||
socketFreqConverterService.handleRead(converterChannelTag, msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
|
||||
log.warn("变频器连接已断开,converterChannelTag={}", converterChannelTag);
|
||||
|
||||
socketFreqConverterService.cleanup(converterChannelTag);
|
||||
|
||||
if (!isReconnecting && reconnectAttempts < MAX_RECONNECT_ATTEMPTS && !FormalTestManager.isRemoveSocket) {
|
||||
attemptReconnect(ctx);
|
||||
} else if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
|
||||
log.error("变频器重连失败,已达到最大重连次数{}次,converterChannelTag={}", MAX_RECONNECT_ATTEMPTS, converterChannelTag);
|
||||
}
|
||||
|
||||
super.channelInactive(ctx);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
log.error("变频器连接发生异常,converterChannelTag={}, error={}", converterChannelTag, cause.getMessage(), cause);
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
|
||||
if (evt instanceof IdleStateEvent) {
|
||||
IdleStateEvent event = (IdleStateEvent) evt;
|
||||
if (event.state() == IdleState.READER_IDLE) {
|
||||
log.warn("变频器连接读空闲,converterChannelTag={}", converterChannelTag);
|
||||
// 可以选择发送心跳或关闭连接
|
||||
}
|
||||
}
|
||||
super.userEventTriggered(ctx, evt);
|
||||
}
|
||||
|
||||
private void attemptReconnect(ChannelHandlerContext ctx) {
|
||||
isReconnecting = true;
|
||||
reconnectAttempts++;
|
||||
|
||||
log.info("准备重连变频器,converterChannelTag={}, 第{}/{}次重连,{}秒后开始",
|
||||
converterChannelTag, reconnectAttempts, MAX_RECONNECT_ATTEMPTS, RECONNECT_INTERVAL_MS / 1000);
|
||||
|
||||
ctx.executor().schedule(() -> {
|
||||
try {
|
||||
log.info("开始执行变频器重连,converterChannelTag={}", converterChannelTag);
|
||||
socketFreqConverterService.reconnect(converterChannelTag);
|
||||
} catch (Exception e) {
|
||||
log.error("变频器重连触发失败,converterChannelTag={}, error={}", converterChannelTag, e.getMessage(), e);
|
||||
isReconnecting = false;
|
||||
|
||||
if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
|
||||
log.warn("将在{}秒后进行下一次重试", RECONNECT_INTERVAL_MS / 1000);
|
||||
ctx.executor().schedule(() -> attemptReconnect(ctx), RECONNECT_INTERVAL_MS, java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
}, RECONNECT_INTERVAL_MS, java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.njcn.gather.detection.util.socket.cilent;
|
||||
|
||||
import com.njcn.gather.detection.handler.SocketFreqConverterDevService;
|
||||
import com.njcn.gather.detection.util.socket.FormalTestManager;
|
||||
import com.njcn.gather.detection.util.socket.SocketManager;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import io.netty.handler.timeout.IdleState;
|
||||
import io.netty.handler.timeout.IdleStateEvent;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 设备 Netty 客户端处理器
|
||||
*/
|
||||
@Slf4j
|
||||
public class NettyFreqConverterDevClientHandler extends SimpleChannelInboundHandler<String> {
|
||||
|
||||
private final String devChannelTag;
|
||||
private final SocketFreqConverterDevService socketFreqConverterDevService;
|
||||
|
||||
public NettyFreqConverterDevClientHandler(String devChannelTag, SocketFreqConverterDevService socketFreqConverterDevService) {
|
||||
this.devChannelTag = devChannelTag;
|
||||
this.socketFreqConverterDevService = socketFreqConverterDevService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
||||
log.info("设备连接已建立,devChannelTag={}, channelId={}", devChannelTag, ctx.channel().id());
|
||||
SocketManager.addUser(devChannelTag, ctx.channel());
|
||||
super.channelActive(ctx);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
|
||||
log.info("收到设备消息,devChannelTag={}, msg={}", devChannelTag, msg);
|
||||
|
||||
socketFreqConverterDevService.handleRead(devChannelTag, msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
|
||||
log.warn("设备连接已断开,devChannelTag={}", devChannelTag);
|
||||
socketFreqConverterDevService.cleanup(devChannelTag);
|
||||
super.channelInactive(ctx);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
log.error("设备连接发生异常,devChannelTag={}, error={}", devChannelTag, cause.getMessage(), cause);
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
|
||||
if (evt instanceof IdleStateEvent) {
|
||||
IdleStateEvent event = (IdleStateEvent) evt;
|
||||
if (event.state() == IdleState.READER_IDLE) {
|
||||
log.warn("设备连接读空闲,devChannelTag={}", devChannelTag);
|
||||
}
|
||||
}
|
||||
super.userEventTriggered(ctx, evt);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.njcn.gather.detection.util.socket.cilent;
|
||||
|
||||
import com.njcn.gather.detection.handler.SocketSourceResponseService;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
||||
@@ -70,6 +71,9 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
|
||||
// 从Socket管理器中移除用户通道映射
|
||||
if (webUser != null && StrUtil.isNotBlank(userId)) {
|
||||
SocketManager.removeUser(userId + CnSocketUtil.SOURCE_TAG);
|
||||
// 源端主动断开 → 本次检测视为结束,释放检测锁
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(userId, "SOURCE_CHANNEL_INACTIVE");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +99,11 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
|
||||
log.error("源设备消息处理异常, userId: {}, message: {}", userId, msg, e);
|
||||
// 发生异常时退出发送,避免后续问题
|
||||
CnSocketUtil.quitSend(webUser);
|
||||
// 业务消息处理异常 → 释放检测锁
|
||||
if (StrUtil.isNotBlank(userId)) {
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(userId, "SOURCE_READ_EXCEPTION");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +145,13 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
|
||||
|
||||
// 发生异常时关闭通道
|
||||
ctx.close();
|
||||
|
||||
// 源通道异常 → 释放检测锁
|
||||
String userIdForRelease = webUser != null ? webUser.getUserPageId() : null;
|
||||
if (StrUtil.isNotBlank(userIdForRelease)) {
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(userIdForRelease, "SOURCE_EXCEPTION");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -18,34 +18,16 @@ import java.util.Set;
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "socket")
|
||||
public class SocketConnectionConfig {
|
||||
/**
|
||||
* 被检设备配置
|
||||
*/
|
||||
private DeviceConfig device = new DeviceConfig();
|
||||
|
||||
/**
|
||||
* 程控源设备配置
|
||||
*/
|
||||
private SourceConfig source = new SourceConfig();
|
||||
|
||||
|
||||
/**
|
||||
* 变频器配置
|
||||
* 被检设备配置
|
||||
*/
|
||||
private DeviceConfig freqConverter = new DeviceConfig();
|
||||
|
||||
@Data
|
||||
public static class DeviceConfig {
|
||||
/**
|
||||
* 被检设备IP地址
|
||||
*/
|
||||
private String ip;
|
||||
|
||||
/**
|
||||
* 被检设备端口号
|
||||
*/
|
||||
private Integer port;
|
||||
}
|
||||
private DeviceConfig device = new DeviceConfig();
|
||||
|
||||
@Data
|
||||
public static class SourceConfig {
|
||||
@@ -53,18 +35,24 @@ public class SocketConnectionConfig {
|
||||
* 程控源IP地址
|
||||
*/
|
||||
private String ip;
|
||||
|
||||
|
||||
/**
|
||||
* 程控源端口号
|
||||
*/
|
||||
private Integer port;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取被检设备配置
|
||||
*/
|
||||
public DeviceConfig getDevice() {
|
||||
return device;
|
||||
@Data
|
||||
public static class DeviceConfig {
|
||||
/**
|
||||
* 被检设备IP地址
|
||||
*/
|
||||
private String ip;
|
||||
|
||||
/**
|
||||
* 被检设备端口号
|
||||
*/
|
||||
private Integer port;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,10 +63,10 @@ public class SocketConnectionConfig {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取变频器配置
|
||||
* 获取被检设备配置
|
||||
*/
|
||||
public DeviceConfig getFreqConverter() {
|
||||
return freqConverter;
|
||||
public DeviceConfig getDevice() {
|
||||
return device;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.njcn.gather.detection.util.socket.websocket;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||
import com.njcn.gather.detection.pojo.vo.WebSocketVO;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
@@ -296,6 +297,8 @@ public class WebServiceManager {
|
||||
webSocketVO.setData(errorType.getMsg());
|
||||
webSocketVO.setOperateCode(errorType.getValue());
|
||||
sendMessage(userId, webSocketVO);
|
||||
// 守门员:错误推送即视为本次检测终态,释放检测锁(幂等,与显式释放点叠加双保险)
|
||||
releaseLockOnTerminal(userId, errorType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -313,6 +316,25 @@ public class WebServiceManager {
|
||||
webSocketVO.setData(errorType.getMsg());
|
||||
webSocketVO.setOperateCode(errorType.getValue());
|
||||
sendMessage(userId, webSocketVO);
|
||||
// 守门员:理由同上
|
||||
releaseLockOnTerminal(userId, errorType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 守门员释放锁
|
||||
* <p>覆盖业务回调里所有走 {@code sendDetectionErrorMessage} 的失败路径,
|
||||
* 等价于在 detection/handler 全目录的错误终态点显式释放。与各 Netty handler
|
||||
* 内的显式释放幂等叠加,形成双保险。</p>
|
||||
*
|
||||
* <p>注:业务"正常完成"路径不走此方法(数模式 formalDeal 已在 Phase 1 显式释放;
|
||||
* 比对模式正常完成走 sendMsg 推 ERROR_FLOW_END,依赖 WS 断开后心跳超时兜底)。</p>
|
||||
*/
|
||||
private static void releaseLockOnTerminal(String userId, SourceOperateCodeEnum errorType) {
|
||||
if (userId == null || userId.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(userId, "WS_ERROR_PUSH:" + errorType.name());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.njcn.gather.detection.util.socket.websocket;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
||||
@@ -414,6 +415,11 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
|
||||
}
|
||||
// 清理完成后移除该用户的检测参数
|
||||
WebServiceManager.removePreDetectionParam(userId);
|
||||
// R3 释放:WS 断开 / 客户端关页面 / 心跳超时后顺手释放检测锁
|
||||
if (preDetectionParam.getUserPageId() != null) {
|
||||
DetectionLockManager.getInstance()
|
||||
.releaseIfMatchPage(preDetectionParam.getUserPageId(), "WS_DISCONNECTED");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("清理Socket连接时发生异常,userId: {}", userId, e);
|
||||
|
||||
@@ -189,14 +189,4 @@ public class PqDevController extends BaseController {
|
||||
}
|
||||
return pqDevService.importDev(file, patternId, planId, response, cover);
|
||||
}
|
||||
|
||||
@OperateInfo
|
||||
@GetMapping("/listAll")
|
||||
@ApiOperation("查询所有未删除设备数据")
|
||||
public HttpResult<List<PqDevVO>> listAll() {
|
||||
String methodDescribe = getMethodDescribe("listAll");
|
||||
LogUtil.njcnDebug(log, "{},查询所有设备", methodDescribe);
|
||||
List<PqDevVO> result = pqDevService.listAll();
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,9 +115,10 @@ public interface IPqDevService extends IService<PqDev> {
|
||||
* @param userId
|
||||
* @param temperature
|
||||
* @param humidity
|
||||
* @param updateCheckNum 是否更新检测次数
|
||||
* @return
|
||||
*/
|
||||
boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity);
|
||||
boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity, boolean updateCheckNum);
|
||||
|
||||
/**
|
||||
* 比对式-修改设备状态
|
||||
@@ -288,6 +289,4 @@ public interface IPqDevService extends IService<PqDev> {
|
||||
* @return
|
||||
*/
|
||||
List<ContrastDevExcel> getExportContrastDevData(List<PqDevVO> pqDevVOList);
|
||||
|
||||
List<PqDevVO> listAll();
|
||||
}
|
||||
|
||||
@@ -38,6 +38,9 @@ import com.njcn.gather.monitor.pojo.po.PqMonitor;
|
||||
import com.njcn.gather.monitor.pojo.vo.PqMonitorExcel;
|
||||
import com.njcn.gather.monitor.service.IPqMonitorService;
|
||||
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
|
||||
import com.njcn.gather.plan.mapper.AdPlanMapper;
|
||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||
import com.njcn.gather.plan.service.IPqDevCheckHistoryService;
|
||||
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
|
||||
import com.njcn.gather.storage.service.DetectionDataDealService;
|
||||
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
||||
@@ -87,6 +90,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
||||
private final IDictTypeService dictTypeService;
|
||||
private final ISysUserService userService;
|
||||
private final IPqDevSubService pqDevSubService;
|
||||
private final AdPlanMapper adPlanMapper;
|
||||
private final IPqDevCheckHistoryService pqDevCheckHistoryService;
|
||||
|
||||
@Override
|
||||
public Page<PqDevVO> listPqDevs(PqDevParam.QueryParam queryParam) {
|
||||
@@ -483,7 +488,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
||||
|
||||
|
||||
@Override
|
||||
public boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity) {
|
||||
public boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity, boolean updateCheckNum) {
|
||||
if (CollUtil.isNotEmpty(ids)) {
|
||||
|
||||
SysTestConfig config = sysTestConfigService.getOneConfig();
|
||||
@@ -515,13 +520,18 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
||||
checkState = CheckStateEnum.DOCUMENTED.getValue();
|
||||
i = pqDevVo.getRecheckNum();
|
||||
} else {
|
||||
checkState = CheckStateEnum.CHECKED.getValue();
|
||||
i = pqDevVo.getRecheckNum() + 1;
|
||||
checkState = pqDevVo.getCheckState() == CheckStateEnum.DOCUMENTED.getValue() ? CheckStateEnum.DOCUMENTED.getValue() : CheckStateEnum.CHECKED.getValue();
|
||||
if (updateCheckNum) {
|
||||
i = pqDevVo.getRecheckNum() + 1;
|
||||
} else {
|
||||
i = pqDevVo.getRecheckNum();
|
||||
}
|
||||
wrapper.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
|
||||
}
|
||||
wrapper.set(PqDevSub::getRecheckNum, i)
|
||||
.set(PqDevSub::getCheckState, checkState);
|
||||
pqDevSubService.update(wrapper);
|
||||
saveCheckHistory(pqDevVo, i, checkState, userId);
|
||||
|
||||
PqDevParam.QueryParam param = new PqDevParam.QueryParam();
|
||||
param.setPlanIdList(Arrays.asList(pqDevVo.getPlanId()));
|
||||
@@ -587,6 +597,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
||||
w.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
|
||||
}
|
||||
w.update();
|
||||
saveCheckHistory(devId, userId);
|
||||
|
||||
PqDevParam.QueryParam param = new PqDevParam.QueryParam();
|
||||
String planId = dev.getPlanId();
|
||||
@@ -622,6 +633,37 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
||||
}
|
||||
}
|
||||
|
||||
private void saveCheckHistory(PqDevVO pqDevVo, Integer recheckNum, Integer checkState, String userId) {
|
||||
if (ObjectUtil.isNull(pqDevVo)
|
||||
|| (!CheckStateEnum.CHECKED.getValue().equals(checkState) && !CheckStateEnum.DOCUMENTED.getValue().equals(checkState))) {
|
||||
return;
|
||||
}
|
||||
AdPlan plan = adPlanMapper.selectById(pqDevVo.getPlanId());
|
||||
if (ObjectUtil.isNull(plan)) {
|
||||
return;
|
||||
}
|
||||
pqDevVo.setRecheckNum(recheckNum);
|
||||
pqDevVo.setCheckBy(userId);
|
||||
pqDevVo.setCheckTime(LocalDateTime.now());
|
||||
pqDevCheckHistoryService.saveOrUpdateDeviceHistory(plan, pqDevVo);
|
||||
}
|
||||
|
||||
private void saveCheckHistory(String devId, String userId) {
|
||||
PqDevVO pqDevVo = this.baseMapper.selectByDevId(devId);
|
||||
if (ObjectUtil.isNull(pqDevVo)
|
||||
|| (!CheckStateEnum.CHECKED.getValue().equals(pqDevVo.getCheckState()) && !CheckStateEnum.DOCUMENTED.getValue().equals(pqDevVo.getCheckState()))) {
|
||||
return;
|
||||
}
|
||||
AdPlan plan = adPlanMapper.selectById(pqDevVo.getPlanId());
|
||||
if (ObjectUtil.isNull(plan)) {
|
||||
return;
|
||||
}
|
||||
if (StrUtil.isBlank(pqDevVo.getCheckBy())) {
|
||||
pqDevVo.setCheckBy(userId);
|
||||
}
|
||||
pqDevCheckHistoryService.saveOrUpdateDeviceHistory(plan, pqDevVo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updatePqDevReportState(String devId, int reportState) {
|
||||
LambdaUpdateWrapper<PqDevSub> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
@@ -1625,31 +1667,4 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<PqDevVO> listAll() {
|
||||
return this.lambdaQuery()
|
||||
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
|
||||
.orderByDesc(PqDev::getCreateTime)
|
||||
.list().stream().map(pqDev -> {
|
||||
PqDevVO pqDevVO = new PqDevVO();
|
||||
BeanUtil.copyProperties(pqDev, pqDevVO);
|
||||
// 解密序列号和密钥
|
||||
if (StrUtil.isNotBlank(pqDevVO.getSeries())) {
|
||||
pqDevVO.setSeries(EncryptionUtil.decoderString(1, pqDevVO.getSeries()));
|
||||
}
|
||||
if (StrUtil.isNotBlank(pqDevVO.getDevKey())) {
|
||||
pqDevVO.setDevKey(EncryptionUtil.decoderString(1, pqDevVO.getDevKey()));
|
||||
}
|
||||
// 填充设备类型信息
|
||||
DevType devType = devTypeService.getById(pqDevVO.getDevType());
|
||||
if (ObjectUtil.isNotNull(devType)) {
|
||||
pqDevVO.setDevType(devType.getName());
|
||||
pqDevVO.setDevChns(devType.getDevChns());
|
||||
pqDevVO.setDevVolt(devType.getDevVolt());
|
||||
pqDevVO.setDevCurr(devType.getDevCurr());
|
||||
}
|
||||
return pqDevVO;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.njcn.gather.dip.mapper;
|
||||
|
||||
import com.github.yulichang.base.MPJBaseMapper;
|
||||
import com.njcn.gather.dip.pojo.po.PqDipData;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @date 2026-04-09
|
||||
*/
|
||||
public interface PqDipDataMapper extends MPJBaseMapper<PqDipData> {
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.njcn.gather.dip.pojo.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 电压暂降数据
|
||||
*
|
||||
* @author caozehui
|
||||
* @date 2026-04-09
|
||||
*/
|
||||
@Data
|
||||
@TableName(value = "ad_harmonic_xx")
|
||||
public class PqDipData {
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 起始时间戳
|
||||
*/
|
||||
private LocalDateTime startTime;
|
||||
|
||||
/**
|
||||
* 残余电压,单位:%Ur
|
||||
*/
|
||||
private Double residualVoltage;
|
||||
|
||||
/**
|
||||
* 持续时间,单位:ms
|
||||
*/
|
||||
private Integer durationMs;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.njcn.gather.dip.pojo.po.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-16
|
||||
*/
|
||||
@Data
|
||||
public class DipPoint {
|
||||
|
||||
/**
|
||||
* 残余电压,单位:%Ur
|
||||
*/
|
||||
private Double residualVoltage;
|
||||
|
||||
/**
|
||||
* 持续时间,单位:ms
|
||||
*/
|
||||
private Integer durationMs;
|
||||
|
||||
/**
|
||||
* 0为不耐受,1为耐受
|
||||
*/
|
||||
private Boolean tolerant;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.njcn.gather.dip.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.njcn.gather.dip.pojo.po.PqDipData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @date 2026-04-09
|
||||
*/
|
||||
public interface IPqDipDataService extends IService<PqDipData> {
|
||||
|
||||
/**
|
||||
* 查询指定变频器所对应的电压暂降数据
|
||||
*
|
||||
* @param suffix 表后缀
|
||||
* @return
|
||||
*/
|
||||
List<PqDipData> listDipData(Integer suffix);
|
||||
|
||||
void clearAllData(Integer suffix);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.njcn.gather.dip.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.njcn.db.mybatisplus.handler.DynamicTableNameHandler;
|
||||
import com.njcn.gather.dip.mapper.PqDipDataMapper;
|
||||
import com.njcn.gather.dip.pojo.po.PqDipData;
|
||||
import com.njcn.gather.dip.service.IPqDipDataService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @date 2026-04-09
|
||||
*/
|
||||
@Service
|
||||
public class PqDipDataServiceImpl extends ServiceImpl<PqDipDataMapper, PqDipData> implements IPqDipDataService {
|
||||
@Override
|
||||
public List<PqDipData> listDipData(Integer suffix) {
|
||||
DynamicTableNameHandler.setTableName("pq_dip_data_" + suffix);
|
||||
LambdaQueryChainWrapper<PqDipData> wrapper = this.lambdaQuery().orderByAsc(PqDipData::getStartTime);
|
||||
List<PqDipData> result = wrapper.list();
|
||||
DynamicTableNameHandler.remove();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearAllData(Integer suffix) {
|
||||
DynamicTableNameHandler.setTableName("pq_dip_data_" + suffix);
|
||||
this.remove(null);
|
||||
DynamicTableNameHandler.remove();
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-15
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "freq-converter")
|
||||
public class FreqConverterConfig {
|
||||
private Long schedulePeriod;
|
||||
private Integer tolerant;
|
||||
private Integer dt;
|
||||
private Integer direction;
|
||||
private Integer allowErrorDuration;
|
||||
private Double allowErrorResidualVoltage;
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.controller;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||
import com.njcn.common.pojo.constant.OperateType;
|
||||
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||
import com.njcn.common.pojo.response.HttpResult;
|
||||
import com.njcn.common.utils.LogUtil;
|
||||
import com.njcn.gather.freqConverter.pojo.param.PqFreqConverterParam;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterConfig;
|
||||
import com.njcn.gather.freqConverter.pojo.vo.TolerantPointVO;
|
||||
import com.njcn.gather.freqConverter.service.IFreqConverterService;
|
||||
import com.njcn.gather.freqConverter.service.IPqFreqConverterConfigService;
|
||||
import com.njcn.web.controller.BaseController;
|
||||
import com.njcn.web.utils.HttpResultUtil;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-13
|
||||
*/
|
||||
@Slf4j
|
||||
@Api(tags = "变频器")
|
||||
@RestController
|
||||
@RequestMapping("/freqConverter")
|
||||
@RequiredArgsConstructor
|
||||
public class FreqConverterController extends BaseController {
|
||||
private final IFreqConverterService freqConverterService;
|
||||
private final IPqFreqConverterConfigService pqFreqConverterConfigService;
|
||||
|
||||
|
||||
@OperateInfo
|
||||
@PostMapping("/list")
|
||||
@ApiOperation("分页查询变频器列表")
|
||||
@ApiImplicitParam(name = "queryParam", value = "查询参数", required = true)
|
||||
public HttpResult<Page<PqFreqConverterConfig>> list(@RequestBody @Validated PqFreqConverterParam.QueryParam queryParam) {
|
||||
String methodDescribe = getMethodDescribe("list");
|
||||
LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, queryParam);
|
||||
Page<PqFreqConverterConfig> result = pqFreqConverterConfigService.listPqFreqConverterConfigs(queryParam);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||
}
|
||||
|
||||
@OperateInfo(operateType = OperateType.ADD)
|
||||
@PostMapping("/add")
|
||||
@ApiOperation("新增变频器")
|
||||
@ApiImplicitParam(name = "pqDevParam", value = "被检设备", required = true)
|
||||
public HttpResult<Boolean> add(@RequestBody @Validated PqFreqConverterParam param) {
|
||||
String methodDescribe = getMethodDescribe("add");
|
||||
LogUtil.njcnDebug(log, "{},新增数据为:{}", methodDescribe, param);
|
||||
boolean result = pqFreqConverterConfigService.addPqFreqConverterConfig(param);
|
||||
if (result) {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
|
||||
} else {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
|
||||
}
|
||||
}
|
||||
|
||||
@OperateInfo(operateType = OperateType.UPDATE)
|
||||
@PostMapping("/update")
|
||||
@ApiOperation("修改变频器")
|
||||
@ApiImplicitParam(name = "updateParam", value = "被检设备", required = true)
|
||||
public HttpResult<Boolean> update(@RequestBody @Validated PqFreqConverterParam.UpdateParam param) {
|
||||
String methodDescribe = getMethodDescribe("update");
|
||||
LogUtil.njcnDebug(log, "{},修改数据为:{}", methodDescribe, param);
|
||||
boolean result = pqFreqConverterConfigService.updatePqFreqConverterConfig(param);
|
||||
if (result) {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
|
||||
} else {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
|
||||
}
|
||||
}
|
||||
|
||||
@OperateInfo(operateType = OperateType.DELETE)
|
||||
@PostMapping("/delete")
|
||||
@ApiOperation("删除变频器")
|
||||
@ApiImplicitParam(name = "param", value = "删除参数", required = true)
|
||||
public HttpResult<Boolean> delete(@RequestBody @Validated List<String> ids) {
|
||||
String methodDescribe = getMethodDescribe("delete");
|
||||
LogUtil.njcnDebug(log, "{},删除ID数据为:{}", methodDescribe, String.join(StrUtil.COMMA, ids));
|
||||
boolean result = pqFreqConverterConfigService.deletePqFreqConverterConfig(ids);
|
||||
if (result) {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
|
||||
} else {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/result")
|
||||
@ApiOperation("查询变频器测试结果")
|
||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||
public HttpResult<List<TolerantPointVO>> result(@RequestParam("converterId") String converterId) {
|
||||
String methodDescribe = getMethodDescribe("result");
|
||||
LogUtil.njcnDebug(log, "{},查询ID数据为:{}", methodDescribe, converterId);
|
||||
List<TolerantPointVO> tolerantPoints = freqConverterService.getDipPoints(converterId);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, tolerantPoints, methodDescribe);
|
||||
}
|
||||
|
||||
// @GetMapping("/scurve")
|
||||
// @ApiOperation("获取绘制特性曲线的point点")
|
||||
// @ApiImplicitParam(name = "converterId", value = "变频器ID", required = true)
|
||||
// public HttpResult<List<TolerantPointVO>> getScurvePoints(@RequestParam("converterId") String converterId) {
|
||||
// String methodDescribe = getMethodDescribe("getScurvePoints");
|
||||
// LogUtil.njcnDebug(log, "{},查询ID数据为:{}", methodDescribe, converterId);
|
||||
// List<TolerantPointVO> tolerantPoints = freqConverterService.getFeaturesScurvePoints(converterId);
|
||||
// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, tolerantPoints, methodDescribe);
|
||||
// }
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.mapper;
|
||||
|
||||
import com.github.yulichang.base.MPJBaseMapper;
|
||||
import com.njcn.gather.freqConverter.pojo.po.FreqConverterStatus;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-07
|
||||
*/
|
||||
public interface FreqConverterStatusMapper extends MPJBaseMapper<FreqConverterStatus> {
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterConfig;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-08
|
||||
*/
|
||||
public interface PqFreqConverterConfigMapper extends BaseMapper<PqFreqConverterConfig> {
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.mapper;
|
||||
|
||||
import com.github.yulichang.base.MPJBaseMapper;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterTestRes;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-14
|
||||
*/
|
||||
public interface PqFreqConverterTestResMapper extends MPJBaseMapper<PqFreqConverterTestRes> {
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.pojo.param;
|
||||
|
||||
import com.njcn.common.pojo.constant.PatternRegex;
|
||||
import com.njcn.gather.pojo.constant.DetectionValidMessage;
|
||||
import com.njcn.web.pojo.param.BaseParam;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-13
|
||||
*/
|
||||
@Data
|
||||
public class PqFreqConverterParam {
|
||||
@ApiModelProperty(value = "名称", required = true)
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "电脑串口名", required = true)
|
||||
private String portName;
|
||||
|
||||
@ApiModelProperty(value = "变频器设置从机地址", required = true)
|
||||
private Integer slaveAddress;
|
||||
|
||||
@ApiModelProperty(value = "变频器设置波特率", required = true)
|
||||
private Integer baudRate;
|
||||
|
||||
@ApiModelProperty(value = "奇偶校验类型: None, Even, Odd", required = true)
|
||||
private String parity;
|
||||
|
||||
@ApiModelProperty(value = "变频器数据位", required = true)
|
||||
private Integer dataBits;
|
||||
|
||||
@ApiModelProperty(value = "变频器停止位,当前只支持 1 或 2", required = true)
|
||||
private Integer stopBits;
|
||||
|
||||
@ApiModelProperty(value = "串口读写超时,单位毫秒", required = true)
|
||||
private Integer timeoutMs;
|
||||
private Integer testStatus;
|
||||
|
||||
/**
|
||||
* 分页查询实体
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class QueryParam extends BaseParam {
|
||||
@ApiModelProperty(value = "名称", required = true)
|
||||
private String name;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新操作实体
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class UpdateParam extends PqFreqConverterParam {
|
||||
|
||||
@ApiModelProperty(value = "id", required = true)
|
||||
@NotBlank(message = DetectionValidMessage.ID_NOT_BLANK)
|
||||
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = DetectionValidMessage.ID_FORMAT_ERROR)
|
||||
private String id;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.pojo.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-07
|
||||
*/
|
||||
@Data
|
||||
@TableName(value = "ad_harmonic_xx")
|
||||
public class FreqConverterStatus {
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
private String id;
|
||||
|
||||
private Integer slaveAddress;
|
||||
|
||||
private Integer statusWord1;
|
||||
|
||||
private String statusWord1Hex;
|
||||
|
||||
/**
|
||||
* 状态记录时刻(时间戳)
|
||||
*/
|
||||
private LocalDateTime timestamp;
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.pojo.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.njcn.db.mybatisplus.bo.BaseEntity;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 变频器配置实体类
|
||||
*/
|
||||
@Data
|
||||
@TableName("pq_freq_converter_config")
|
||||
public class PqFreqConverterConfig extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 变频器名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 电脑串口名,如COM1
|
||||
*/
|
||||
private String portName;
|
||||
|
||||
/**
|
||||
* 变频器设置从机地址,范围1~127
|
||||
*/
|
||||
private Integer slaveAddress;
|
||||
|
||||
/**
|
||||
* 变频器设置波特率,如19200
|
||||
*/
|
||||
private Integer baudRate;
|
||||
|
||||
/**
|
||||
* 奇偶校验类型: None, Even, Odd
|
||||
*/
|
||||
private String parity;
|
||||
|
||||
/**
|
||||
* 变频器数据位
|
||||
*/
|
||||
private Integer dataBits;
|
||||
|
||||
/**
|
||||
* 变频器停止位,当前只支持 1 或 2
|
||||
*/
|
||||
private Integer stopBits;
|
||||
|
||||
/**
|
||||
* 串口读写超时,单位毫秒
|
||||
*/
|
||||
private Integer timeoutMs;
|
||||
|
||||
/**
|
||||
* 数据表后缀
|
||||
*/
|
||||
private Integer suffix;
|
||||
|
||||
/**
|
||||
* 检测状态,0未检测,1检测完成
|
||||
*/
|
||||
private Integer testStatus;
|
||||
|
||||
/**
|
||||
* 状态:0-删除 1-正常
|
||||
*/
|
||||
private Integer state;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.pojo.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-14
|
||||
*/
|
||||
@Data
|
||||
@TableName(value = "ad_harmonic_xx")
|
||||
public class PqFreqConverterTestRes {
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 残余电压,单位:%Ur
|
||||
*/
|
||||
private Double residualVoltage;
|
||||
|
||||
/**
|
||||
* 持续时间,单位:ms
|
||||
*/
|
||||
private Integer durationMs;
|
||||
|
||||
/**
|
||||
* 0为不耐受,1为耐受,2为特性曲线点
|
||||
*/
|
||||
private Integer tolerant;
|
||||
|
||||
/**
|
||||
* 时间
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8")
|
||||
private LocalDateTime time;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.pojo.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-13
|
||||
*/
|
||||
@Data
|
||||
public class TolerantPointVO {
|
||||
/**
|
||||
* 持续时间,单位ms
|
||||
*/
|
||||
private Integer durationMs;
|
||||
|
||||
/**
|
||||
* 残余电压,单位:%Ur
|
||||
*/
|
||||
private Double residualVoltage;
|
||||
|
||||
/**
|
||||
* 是否耐受。0-否,1-是,2-表示特性曲线点
|
||||
*/
|
||||
private Integer tolerant;
|
||||
|
||||
/**
|
||||
* 时间
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8")
|
||||
private LocalDateTime time;
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.njcn.gather.freqConverter.pojo.po.FreqConverterStatus;
|
||||
import com.njcn.gather.freqConverter.pojo.vo.TolerantPointVO;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-07
|
||||
*/
|
||||
public interface IFreqConverterService extends IService<FreqConverterStatus> {
|
||||
|
||||
|
||||
/**
|
||||
* 保存变频器状态数据
|
||||
*
|
||||
* @param suffix 表后缀
|
||||
* @param status 变频器状态数据
|
||||
* @return 是否保存成功
|
||||
*/
|
||||
boolean saveFreqConverterStatus(Integer suffix, FreqConverterStatus status);
|
||||
|
||||
|
||||
/**
|
||||
* 查询指定变频器的状态历史
|
||||
*
|
||||
* @param converterId 变频器ID
|
||||
* @return 状态数据列表
|
||||
*/
|
||||
List<FreqConverterStatus> listStatusData(String converterId);
|
||||
|
||||
/**
|
||||
* 清空所有数据
|
||||
*
|
||||
* @param converterId 变频器ID
|
||||
* @return
|
||||
*/
|
||||
void clearAllData(Integer converterId);
|
||||
|
||||
/**
|
||||
* 根据设备暂降数据判断变频器是否耐受
|
||||
*
|
||||
* @param converterId 变频器Id
|
||||
* @return 是否耐受
|
||||
*/
|
||||
List<TolerantPointVO> getDipPoints(String converterId);
|
||||
|
||||
List<FreqConverterStatus> getDipDurationStatusData(Integer suffix, LocalDateTime startTime, LocalDateTime endTime);
|
||||
|
||||
FreqConverterStatus getLastStatusData(Integer suffix, LocalDateTime startTime);
|
||||
|
||||
/**
|
||||
* 获取变频器特性曲线点
|
||||
*
|
||||
* @param converterId 变频器ID
|
||||
* @return
|
||||
*/
|
||||
List<TolerantPointVO> getFeaturesScurvePoints(String converterId);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.njcn.gather.freqConverter.pojo.param.PqFreqConverterParam;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterConfig;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-08
|
||||
*/
|
||||
public interface IPqFreqConverterConfigService extends IService<PqFreqConverterConfig> {
|
||||
Page<PqFreqConverterConfig> listPqFreqConverterConfigs(PqFreqConverterParam.QueryParam queryParam);
|
||||
|
||||
Integer getSuffix(String converterId);
|
||||
|
||||
boolean addPqFreqConverterConfig(PqFreqConverterParam param);
|
||||
|
||||
boolean updatePqFreqConverterConfig(PqFreqConverterParam.UpdateParam param);
|
||||
|
||||
boolean deletePqFreqConverterConfig(List<String> ids);
|
||||
|
||||
boolean updateTestStatus(String converterId, Integer testStatus);
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterTestRes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-14
|
||||
*/
|
||||
public interface IPqFreqConverterTestResService extends IService<PqFreqConverterTestRes> {
|
||||
/**
|
||||
* 清空所有数据
|
||||
*
|
||||
* @param suffix 表后缀
|
||||
* @return
|
||||
*/
|
||||
void clearAllData(Integer suffix);
|
||||
|
||||
/**
|
||||
* 新增结果记录
|
||||
*
|
||||
* @param suffix 表后缀
|
||||
* @param testResList 结果数据
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean saveTestRes(Integer suffix, List<PqFreqConverterTestRes> testResList);
|
||||
|
||||
/**
|
||||
* 更新结果记录
|
||||
*
|
||||
* @param suffix 表后缀
|
||||
* @param testResList 结果数据
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean updateTestRes(Integer suffix, List<PqFreqConverterTestRes> testResList);
|
||||
|
||||
/**
|
||||
* 查询结果记录
|
||||
*
|
||||
* @param suffix 表后缀
|
||||
* @return 结果列表
|
||||
*/
|
||||
List<PqFreqConverterTestRes> listTestRes(Integer suffix);
|
||||
|
||||
PqFreqConverterTestRes getLastByDuration(Integer suffix, String id, Integer durationMs);
|
||||
|
||||
PqFreqConverterTestRes getLastByResidualVoltage(Integer suffix, String id, Double residualVoltage);
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.service.impl;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.njcn.db.mybatisplus.handler.DynamicTableNameHandler;
|
||||
import com.njcn.gather.dip.service.IPqDipDataService;
|
||||
import com.njcn.gather.freqConverter.mapper.FreqConverterStatusMapper;
|
||||
import com.njcn.gather.freqConverter.pojo.po.FreqConverterStatus;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterTestRes;
|
||||
import com.njcn.gather.freqConverter.pojo.vo.TolerantPointVO;
|
||||
import com.njcn.gather.freqConverter.service.IFreqConverterService;
|
||||
import com.njcn.gather.freqConverter.service.IPqFreqConverterConfigService;
|
||||
import com.njcn.gather.freqConverter.service.IPqFreqConverterTestResService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 变频器状态数据Service实现类
|
||||
* <p>
|
||||
* 实现变频器状态数据的存储、查询和清理功能。
|
||||
* 当数据量超过阈值时,自动清理无效或过期数据,避免内存和数据库资源浪费。
|
||||
* </p>
|
||||
*
|
||||
* @author CN_Gather Detection Team
|
||||
* @version 1.0
|
||||
* @since 2026
|
||||
*/
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class FreqConverterServiceImpl extends ServiceImpl<FreqConverterStatusMapper, FreqConverterStatus> implements IFreqConverterService {
|
||||
private final IPqFreqConverterConfigService pqFreqConverterConfigService;
|
||||
private final IPqDipDataService dipDataService;
|
||||
private final IPqFreqConverterTestResService pqFreqConverterTestResService;
|
||||
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean saveFreqConverterStatus(Integer suffix, FreqConverterStatus status) {
|
||||
if (status.getId() == null) {
|
||||
status.setId(IdUtil.fastSimpleUUID());
|
||||
}
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_STATUS_TB_PREFIX + suffix);
|
||||
boolean result = this.save(status);
|
||||
DynamicTableNameHandler.remove();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<FreqConverterStatus> listStatusData(String converterId) {
|
||||
Integer suffix = pqFreqConverterConfigService.getSuffix(converterId);
|
||||
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_STATUS_TB_PREFIX + suffix);
|
||||
LambdaQueryChainWrapper<FreqConverterStatus> wrapper = this.lambdaQuery().orderByAsc(FreqConverterStatus::getTimestamp);
|
||||
List<FreqConverterStatus> result = wrapper.list();
|
||||
DynamicTableNameHandler.remove();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void clearAllData(Integer suffix) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_STATUS_TB_PREFIX + suffix);
|
||||
this.remove(null);
|
||||
DynamicTableNameHandler.remove();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TolerantPointVO> getDipPoints(String converterId) {
|
||||
Integer suffix = pqFreqConverterConfigService.getSuffix(converterId);
|
||||
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + suffix);
|
||||
List<PqFreqConverterTestRes> pqFreqConverterTestResList = pqFreqConverterTestResService.list();
|
||||
DynamicTableNameHandler.remove();
|
||||
List<TolerantPointVO> result = pqFreqConverterTestResList.stream().map(item -> {
|
||||
TolerantPointVO tolerantPointVO = new TolerantPointVO();
|
||||
tolerantPointVO.setDurationMs(item.getDurationMs());
|
||||
tolerantPointVO.setResidualVoltage(item.getResidualVoltage());
|
||||
tolerantPointVO.setTolerant(item.getTolerant());
|
||||
tolerantPointVO.setTime(item.getTime());
|
||||
return tolerantPointVO;
|
||||
})
|
||||
.sorted(Comparator.comparingInt(TolerantPointVO::getDurationMs))
|
||||
.sorted(Comparator.comparingDouble(TolerantPointVO::getResidualVoltage)).collect(Collectors.toList());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<FreqConverterStatus> getDipDurationStatusData(Integer suffix, LocalDateTime startTime, LocalDateTime endTime) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_STATUS_TB_PREFIX + suffix);
|
||||
List<FreqConverterStatus> result = this.lambdaQuery()
|
||||
.between(FreqConverterStatus::getTimestamp, startTime, endTime)
|
||||
.orderByAsc(FreqConverterStatus::getTimestamp)
|
||||
.list();
|
||||
DynamicTableNameHandler.remove();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FreqConverterStatus getLastStatusData(Integer suffix, LocalDateTime startTime) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_STATUS_TB_PREFIX + suffix);
|
||||
FreqConverterStatus one = this.lambdaQuery().le(FreqConverterStatus::getTimestamp, startTime)
|
||||
.orderByDesc(FreqConverterStatus::getTimestamp)
|
||||
.last("limit 1")
|
||||
.one();
|
||||
DynamicTableNameHandler.remove();
|
||||
return one;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TolerantPointVO> getFeaturesScurvePoints(String converterId) {
|
||||
List<TolerantPointVO> dipPoints = this.getDipPoints(converterId);
|
||||
if (dipPoints == null || dipPoints.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
Map<Integer, List<TolerantPointVO>> durationPointMap = dipPoints.stream()
|
||||
.collect(Collectors.groupingBy(TolerantPointVO::getDurationMs, TreeMap::new, Collectors.toList()));
|
||||
if (durationPointMap.size() < 2) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
List<TolerantPointVO> result = new ArrayList<>();
|
||||
|
||||
TolerantPointVO firstPoint = new TolerantPointVO();
|
||||
|
||||
List<Integer> keyList = durationPointMap.keySet().stream().collect(Collectors.toList());
|
||||
Integer i1 = keyList.get(0);
|
||||
List<TolerantPointVO> tolerantPointVOS1 = durationPointMap.get(i1);
|
||||
Collections.sort(tolerantPointVOS1, Comparator.comparing(TolerantPointVO::getResidualVoltage));
|
||||
TolerantPointVO tolerantPointVO1 = tolerantPointVOS1.get(0);
|
||||
|
||||
Integer i2 = keyList.get(1);
|
||||
List<TolerantPointVO> tolerantPointVOS2 = durationPointMap.get(i2);
|
||||
Collections.sort(tolerantPointVOS2, Comparator.comparing(TolerantPointVO::getResidualVoltage));
|
||||
TolerantPointVO tolerantPointVO2 = tolerantPointVOS2.get(0);
|
||||
|
||||
firstPoint.setDurationMs((i1 + i2) / 2);
|
||||
firstPoint.setResidualVoltage((tolerantPointVO1.getResidualVoltage() + tolerantPointVO2.getResidualVoltage()) / 2D);
|
||||
firstPoint.setTolerant(2);
|
||||
result.add(firstPoint);
|
||||
|
||||
durationPointMap.entrySet().stream()
|
||||
.forEach(entry -> {
|
||||
List<TolerantPointVO> sameDurationPoints = entry.getValue().stream()
|
||||
.sorted(Comparator.comparing(TolerantPointVO::getResidualVoltage, Comparator.reverseOrder()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
for (int index = 0; index < sameDurationPoints.size() - 1; index++) {
|
||||
TolerantPointVO currentPoint = sameDurationPoints.get(index);
|
||||
TolerantPointVO nextPoint = sameDurationPoints.get(index + 1);
|
||||
if (!Objects.equals(currentPoint.getTolerant(), nextPoint.getTolerant())) {
|
||||
TolerantPointVO featurePoint = new TolerantPointVO();
|
||||
featurePoint.setDurationMs(entry.getKey());
|
||||
featurePoint.setResidualVoltage((currentPoint.getResidualVoltage() + nextPoint.getResidualVoltage()) / 2D);
|
||||
featurePoint.setTolerant(2);
|
||||
result.add(featurePoint);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.service.impl;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
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.common.pojo.enums.common.DataStateEnum;
|
||||
import com.njcn.gather.freqConverter.mapper.PqFreqConverterConfigMapper;
|
||||
import com.njcn.gather.freqConverter.pojo.param.PqFreqConverterParam;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterConfig;
|
||||
import com.njcn.gather.freqConverter.service.IPqFreqConverterConfigService;
|
||||
import com.njcn.gather.storage.mapper.TableGenMapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-08
|
||||
*/
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class PqFreqConverterConfigServiceImpl extends ServiceImpl<PqFreqConverterConfigMapper, PqFreqConverterConfig> implements IPqFreqConverterConfigService {
|
||||
private final TableGenMapper tableGenMapper;
|
||||
|
||||
/**
|
||||
* 表名前缀
|
||||
*/
|
||||
public static final String PQ_FREQ_CONVERTER_STATUS_TB_PREFIX = "pq_freq_converter_status_";
|
||||
public static final String PQ_DIP_DATA_TB_PREFIX = "pq_dip_data_";
|
||||
public static final String PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX = "pq_freq_converter_test_res_";
|
||||
|
||||
@Override
|
||||
public Page<PqFreqConverterConfig> listPqFreqConverterConfigs(PqFreqConverterParam.QueryParam queryParam) {
|
||||
QueryWrapper wrapper = new QueryWrapper<>();
|
||||
wrapper.like(StrUtil.isNotBlank(queryParam.getName()), "name", queryParam.getName());
|
||||
wrapper.eq("state", 1);
|
||||
return this.page(new Page<>(queryParam.getPageNum(), queryParam.getPageSize()), wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getSuffix(String converterId) {
|
||||
PqFreqConverterConfig freqConverterConfig = this.lambdaQuery().eq(PqFreqConverterConfig::getId, converterId).one();
|
||||
return freqConverterConfig.getSuffix();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean addPqFreqConverterConfig(PqFreqConverterParam param) {
|
||||
// 建表
|
||||
PqFreqConverterConfig freqConverterConfig = this.lambdaQuery().orderByDesc(PqFreqConverterConfig::getSuffix)
|
||||
.last("limit 1").one();
|
||||
Integer maxSuffix = 1;
|
||||
if (ObjectUtil.isNotNull(freqConverterConfig)) {
|
||||
maxSuffix = freqConverterConfig.getSuffix() + 1;
|
||||
}
|
||||
|
||||
String tableSql = "CREATE TABLE `" + PQ_FREQ_CONVERTER_STATUS_TB_PREFIX + maxSuffix + "`(" +
|
||||
" `id` char(32) NOT NULL COMMENT '主键ID'," +
|
||||
" `slave_address` int(11) DEFAULT NULL COMMENT '从机地址'," +
|
||||
" `status_word1` int(11) DEFAULT NULL COMMENT '状态字1'," +
|
||||
" `status_word1_hex` varchar(20) DEFAULT NULL COMMENT '状态字1十六进制'," +
|
||||
" `timestamp` datetime(3) NOT NULL COMMENT '状态记录时刻(时间戳)'," +
|
||||
" PRIMARY KEY (`id`) USING BTREE" +
|
||||
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='变频器状态表';";
|
||||
tableGenMapper.genTable(tableSql);
|
||||
|
||||
tableSql = "CREATE TABLE `" + PQ_DIP_DATA_TB_PREFIX + maxSuffix + "` (" +
|
||||
" `id` char(32) NOT NULL COMMENT '主键ID'," +
|
||||
" `start_time` datetime(3) NOT NULL COMMENT '起始时间戳'," +
|
||||
" `residual_voltage` decimal(6,2) NOT NULL COMMENT '残余电压(%Ur)'," +
|
||||
" `duration_ms` int(11) NOT NULL COMMENT '持续时间(ms)'," +
|
||||
" PRIMARY KEY (`id`)" +
|
||||
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='电压暂降数据表';";
|
||||
tableGenMapper.genTable(tableSql);
|
||||
|
||||
tableSql = "CREATE TABLE `" + PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + maxSuffix + "` (" +
|
||||
" `id` char(32) NOT NULL COMMENT '主键ID'," +
|
||||
" `residual_voltage` decimal(6,2) NOT NULL COMMENT '残余电压(%Ur)'," +
|
||||
" `duration_ms` int(11) NOT NULL COMMENT '持续时间(ms)'," +
|
||||
" `tolerant` tinyInt(1) NOT NULL COMMENT '0为不耐受,1为耐受,2为特征点'," +
|
||||
" `time` datetime(3) DEFAULT NULL COMMENT '时间',"+
|
||||
" PRIMARY KEY (`id`)" +
|
||||
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='变频器耐受实验结果';";
|
||||
tableGenMapper.genTable(tableSql);
|
||||
|
||||
PqFreqConverterConfig pqFreqConverterConfig = BeanUtil.copyProperties(param, PqFreqConverterConfig.class);
|
||||
pqFreqConverterConfig.setSuffix(maxSuffix);
|
||||
pqFreqConverterConfig.setTestStatus(0);
|
||||
pqFreqConverterConfig.setState(DataStateEnum.ENABLE.getCode());
|
||||
return this.save(pqFreqConverterConfig);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updatePqFreqConverterConfig(PqFreqConverterParam.UpdateParam param) {
|
||||
PqFreqConverterConfig pqFreqConverterConfig = BeanUtil.copyProperties(param, PqFreqConverterConfig.class);
|
||||
return this.updateById(pqFreqConverterConfig);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean deletePqFreqConverterConfig(List<String> ids) {
|
||||
StringBuffer sql = new StringBuffer();
|
||||
sql.append("drop table if exists ");
|
||||
|
||||
List<PqFreqConverterConfig> pqFreqConverterConfigs = this.listByIds(ids);
|
||||
for (PqFreqConverterConfig pqFreqConverterConfig : pqFreqConverterConfigs) {
|
||||
Integer suffix = pqFreqConverterConfig.getSuffix();
|
||||
sql.append(PQ_FREQ_CONVERTER_STATUS_TB_PREFIX + suffix + ",")
|
||||
.append(PQ_DIP_DATA_TB_PREFIX + suffix + ",")
|
||||
.append(PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + suffix + ",");
|
||||
}
|
||||
|
||||
sql.deleteCharAt(sql.length() - 1);
|
||||
// 删除表
|
||||
tableGenMapper.genTable(sql.toString());
|
||||
return this.lambdaUpdate()
|
||||
.in(CollectionUtil.isNotEmpty(ids), PqFreqConverterConfig::getId, ids)
|
||||
.set(PqFreqConverterConfig::getState, 0).update();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateTestStatus(String converterId, Integer testStatus) {
|
||||
return this.lambdaUpdate()
|
||||
.eq(PqFreqConverterConfig::getId, converterId)
|
||||
.set(PqFreqConverterConfig::getTestStatus, testStatus)
|
||||
.update();
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package com.njcn.gather.freqConverter.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.njcn.db.mybatisplus.handler.DynamicTableNameHandler;
|
||||
import com.njcn.gather.freqConverter.config.FreqConverterConfig;
|
||||
import com.njcn.gather.freqConverter.mapper.PqFreqConverterTestResMapper;
|
||||
import com.njcn.gather.freqConverter.pojo.po.PqFreqConverterTestRes;
|
||||
import com.njcn.gather.freqConverter.service.IPqFreqConverterTestResService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-04-14
|
||||
*/
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class PqFreqConverterTestResServiceImpl extends ServiceImpl<PqFreqConverterTestResMapper, PqFreqConverterTestRes> implements IPqFreqConverterTestResService {
|
||||
private final FreqConverterConfig freqConverterConfig;
|
||||
|
||||
@Override
|
||||
public void clearAllData(Integer suffix) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + suffix);
|
||||
this.remove(null);
|
||||
DynamicTableNameHandler.remove();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean saveTestRes(Integer suffix, List<PqFreqConverterTestRes> testResList) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + suffix);
|
||||
this.saveBatch(testResList);
|
||||
DynamicTableNameHandler.remove();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateTestRes(Integer suffix, List<PqFreqConverterTestRes> testResList) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + suffix);
|
||||
this.updateBatchById(testResList);
|
||||
DynamicTableNameHandler.remove();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<PqFreqConverterTestRes> listTestRes(Integer suffix) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + suffix);
|
||||
List<PqFreqConverterTestRes> result = this.list();
|
||||
DynamicTableNameHandler.remove();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PqFreqConverterTestRes getLastByDuration(Integer suffix, String id, Integer durationMs) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + suffix);
|
||||
LambdaQueryWrapper<PqFreqConverterTestRes> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.between(PqFreqConverterTestRes::getDurationMs, durationMs - freqConverterConfig.getAllowErrorDuration(), durationMs + freqConverterConfig.getAllowErrorDuration())
|
||||
.ne(PqFreqConverterTestRes::getId, id)
|
||||
.orderByAsc(PqFreqConverterTestRes::getResidualVoltage)
|
||||
.last("limit 1");
|
||||
PqFreqConverterTestRes result = this.getOne(queryWrapper);
|
||||
DynamicTableNameHandler.remove();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PqFreqConverterTestRes getLastByResidualVoltage(Integer suffix, String id, Double residualVoltage) {
|
||||
DynamicTableNameHandler.setTableName(PqFreqConverterConfigServiceImpl.PQ_FREQ_CONVERTER_TEST_RES_TB_PREFIX + suffix);
|
||||
LambdaQueryWrapper<PqFreqConverterTestRes> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.between(PqFreqConverterTestRes::getResidualVoltage, residualVoltage - freqConverterConfig.getAllowErrorResidualVoltage(), residualVoltage + freqConverterConfig.getAllowErrorResidualVoltage())
|
||||
.ne(PqFreqConverterTestRes::getId, id)
|
||||
.orderByDesc(PqFreqConverterTestRes::getDurationMs)
|
||||
.last("limit 1");
|
||||
PqFreqConverterTestRes result = this.getOne(queryWrapper);
|
||||
DynamicTableNameHandler.remove();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import com.njcn.gather.device.service.IPqDevService;
|
||||
import com.njcn.gather.plan.pojo.param.AdPlanParam;
|
||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||
import com.njcn.gather.plan.pojo.vo.AdPlanVO;
|
||||
import com.njcn.gather.plan.pojo.vo.PlanStatisticsVO;
|
||||
import com.njcn.gather.plan.service.AsyncPlanHandler;
|
||||
import com.njcn.gather.plan.service.IAdPlanService;
|
||||
import com.njcn.gather.type.pojo.po.DevType;
|
||||
@@ -198,6 +199,17 @@ public class AdPlanController extends BaseController {
|
||||
adPlanService.analyse(ids);
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||
@PostMapping("/statistics")
|
||||
@ApiOperation("检测计划统计")
|
||||
@ApiImplicitParam(name = "param", value = "检测计划统计参数", required = true)
|
||||
public HttpResult<PlanStatisticsVO> statistics(@RequestBody @Validated AdPlanParam.StatisticsParam param) {
|
||||
String methodDescribe = getMethodDescribe("statistics");
|
||||
LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, param);
|
||||
PlanStatisticsVO result = adPlanService.statistics(param);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||
@PostMapping("/listByPlanId")
|
||||
@ApiOperation("查询出所有已绑定的设备")
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.njcn.gather.plan.mapper;
|
||||
|
||||
import com.github.yulichang.base.MPJBaseMapper;
|
||||
import com.njcn.gather.plan.pojo.po.PqDevCheckHistory;
|
||||
import com.njcn.gather.plan.pojo.vo.PlanStatisticsItemVO;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PqDevCheckHistoryMapper extends MPJBaseMapper<PqDevCheckHistory> {
|
||||
|
||||
List<PlanStatisticsItemVO> listItemDistributions(@Param("planId") String planId,
|
||||
@Param("manufacturer") String manufacturer,
|
||||
@Param("devType") String devType);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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.gather.plan.mapper.PqDevCheckHistoryMapper">
|
||||
|
||||
<select id="listItemDistributions" resultType="com.njcn.gather.plan.pojo.vo.PlanStatisticsItemVO">
|
||||
SELECT
|
||||
Item_Id AS itemId,
|
||||
Item_Name AS itemName,
|
||||
SUM(CASE WHEN Result = 0 THEN 1 ELSE 0 END) AS unqualifiedCount
|
||||
FROM pq_dev_check_history
|
||||
<where>
|
||||
State = 1
|
||||
AND Plan_Id = #{planId}
|
||||
<if test="manufacturer != null and manufacturer != ''">
|
||||
AND Manufacturer = #{manufacturer}
|
||||
</if>
|
||||
<if test="devType != null and devType != ''">
|
||||
AND Dev_Type = #{devType}
|
||||
</if>
|
||||
</where>
|
||||
GROUP BY Item_Id, Item_Name
|
||||
ORDER BY unqualifiedCount DESC, Item_Name ASC
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -130,4 +130,17 @@ public class AdPlanParam {
|
||||
private String patternId;
|
||||
private String scriptType;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class StatisticsParam {
|
||||
@ApiModelProperty(value = "检测计划ID", required = true)
|
||||
@NotBlank(message = DetectionValidMessage.PLAN_ID_NOT_BLANK)
|
||||
private String planId;
|
||||
|
||||
@ApiModelProperty("设备厂家")
|
||||
private String manufacturer;
|
||||
|
||||
@ApiModelProperty("设备类型")
|
||||
private String devType;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.njcn.gather.plan.pojo.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("pq_dev_check_history")
|
||||
public class PqDevCheckHistory {
|
||||
|
||||
@TableId(value = "Id", type = IdType.ASSIGN_UUID)
|
||||
private String id;
|
||||
|
||||
@TableField("Plan_Id")
|
||||
private String planId;
|
||||
|
||||
@TableField("Dev_Id")
|
||||
private String devId;
|
||||
|
||||
@TableField("Dev_Type")
|
||||
private String devType;
|
||||
|
||||
@TableField("Manufacturer")
|
||||
private String manufacturer;
|
||||
|
||||
@TableField("ReCheck_Num")
|
||||
private Integer recheckNum;
|
||||
|
||||
@TableField("Item_Id")
|
||||
private String itemId;
|
||||
|
||||
@TableField("Item_Name")
|
||||
private String itemName;
|
||||
|
||||
@TableField("Result")
|
||||
private Integer result;
|
||||
|
||||
@TableField("Check_Time")
|
||||
private LocalDateTime checkTime;
|
||||
|
||||
@TableField("State")
|
||||
private Integer state;
|
||||
|
||||
@TableField("Create_By")
|
||||
private String createBy;
|
||||
|
||||
@TableField(value = "Create_Time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("Update_By")
|
||||
private String updateBy;
|
||||
|
||||
@TableField(value = "Update_Time", fill = FieldFill.UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.njcn.gather.plan.pojo.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 检测计划单个检测大项柱状图统计结果。
|
||||
*/
|
||||
@Data
|
||||
public class PlanStatisticsItemVO {
|
||||
|
||||
/**
|
||||
* 检测大项ID。
|
||||
*/
|
||||
private String itemId;
|
||||
|
||||
/**
|
||||
* 检测大项名称。
|
||||
*/
|
||||
private String itemName;
|
||||
|
||||
/**
|
||||
* 不合格次数。
|
||||
*/
|
||||
private Integer unqualifiedCount;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.njcn.gather.plan.pojo.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 检测计划统计结果。
|
||||
*/
|
||||
@Data
|
||||
public class PlanStatisticsVO {
|
||||
|
||||
/**
|
||||
* 检测计划ID。
|
||||
*/
|
||||
private String planId;
|
||||
|
||||
/**
|
||||
* 检测计划名称。
|
||||
*/
|
||||
private String planName;
|
||||
|
||||
/**
|
||||
* 所有设备检测次数之和。
|
||||
*/
|
||||
private Integer totalCheckCount;
|
||||
|
||||
/**
|
||||
* 已检设备总数。
|
||||
*/
|
||||
private Integer checkedDeviceCount;
|
||||
|
||||
/**
|
||||
* 未检设备总数。
|
||||
*/
|
||||
private Integer uncheckedDeviceCount;
|
||||
|
||||
/**
|
||||
* 第一次检测合格的设备数量。
|
||||
*/
|
||||
private Integer firstQualifiedDeviceCount;
|
||||
|
||||
/**
|
||||
* 第二次检测后合格的设备数量。
|
||||
*/
|
||||
private Integer secondQualifiedDeviceCount;
|
||||
|
||||
/**
|
||||
* 第三次及以上检测后合格的设备数量。
|
||||
*/
|
||||
private Integer thirdOrMoreQualifiedDeviceCount;
|
||||
|
||||
/**
|
||||
* 最终合格的设备数量。
|
||||
*/
|
||||
private Integer qualifiedDeviceCount;
|
||||
|
||||
/**
|
||||
* 最终不合格的设备数量。
|
||||
*/
|
||||
private Integer unqualifiedDeviceCount;
|
||||
|
||||
/**
|
||||
* 存在不合格结果的检测项数量。
|
||||
*/
|
||||
private Integer unqualifiedItemCount;
|
||||
|
||||
/**
|
||||
* 一次合格率,百分制。
|
||||
*/
|
||||
private BigDecimal firstPassRate;
|
||||
|
||||
/**
|
||||
* 二次合格率,百分制。
|
||||
*/
|
||||
private BigDecimal secondPassRate;
|
||||
|
||||
/**
|
||||
* 三次及以上合格率,百分制。
|
||||
*/
|
||||
private BigDecimal thirdOrMorePassRate;
|
||||
|
||||
/**
|
||||
* 不合格率,百分制。
|
||||
*/
|
||||
private BigDecimal unqualifiedRate;
|
||||
|
||||
/**
|
||||
* 检测项分布。
|
||||
*/
|
||||
private List<PlanStatisticsItemVO> itemDistributions;
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import com.njcn.gather.monitor.service.IPqMonitorService;
|
||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||
import com.njcn.gather.plan.pojo.vo.AdPlanCheckDataVO;
|
||||
import com.njcn.gather.plan.service.util.BatchFileReader;
|
||||
import com.njcn.gather.system.config.PathConfig;
|
||||
import com.njcn.gather.system.config.handler.NonWebAutoFillValueHandler;
|
||||
import com.njcn.gather.tools.report.model.constant.ReportConstant;
|
||||
import com.njcn.gather.type.pojo.po.DevType;
|
||||
@@ -64,11 +65,11 @@ public class AsyncPlanHandler {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
|
||||
@Value("${report.reportDir}")
|
||||
private String reportPath;
|
||||
@Value("${data.homeDir}")
|
||||
private String dataPath;
|
||||
private final PathConfig pathConfig;
|
||||
// @Value("${report.reportDir}")
|
||||
// private String reportPath;
|
||||
// @Value("${data.homeDir}")
|
||||
// private String dataPath;
|
||||
|
||||
private static final int BATCH_SIZE = 10000;
|
||||
private static final int FINAL_STEP = 85;
|
||||
@@ -199,13 +200,13 @@ public class AsyncPlanHandler {
|
||||
|
||||
// 创建 ZIP 文件
|
||||
String zipFileName = plan.getName() + "_检测数据包.zip";
|
||||
File zipFile = FileUtil.file(dataPath + File.separator + TEST_DATA_DIR + File.separator, zipFileName);
|
||||
File zipFile = FileUtil.file(pathConfig.getDataPath() + File.separator + TEST_DATA_DIR + File.separator, zipFileName);
|
||||
|
||||
// 添加检测报告文件
|
||||
if (ObjectUtil.isNotNull(report) && report.equals(1)) {
|
||||
for (PqDev dev : devList) {
|
||||
DevType devType = devTypeService.getById(dev.getDevType());
|
||||
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
|
||||
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
|
||||
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
|
||||
// 如果reportFile存在,则将reportFile中的文件添加到已有的zip文件中
|
||||
if (FileUtil.exist(reportFile)) {
|
||||
@@ -344,7 +345,7 @@ public class AsyncPlanHandler {
|
||||
for (File docx : docxFiles) {
|
||||
for (PqDev dev : devList) {
|
||||
DevType devType = devTypeService.getById(dev.getDevType());
|
||||
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
|
||||
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
|
||||
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
|
||||
// 文件名匹配,复制到对应目录下
|
||||
if (docx.getName().equals(reportFile.getName())) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.njcn.gather.device.pojo.po.PqStandardDev;
|
||||
import com.njcn.gather.plan.pojo.param.AdPlanParam;
|
||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||
import com.njcn.gather.plan.pojo.vo.AdPlanVO;
|
||||
import com.njcn.gather.plan.pojo.vo.PlanStatisticsVO;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
@@ -105,6 +106,14 @@ public interface IAdPlanService extends IService<AdPlan> {
|
||||
*/
|
||||
void analyse(List<String> ids);
|
||||
|
||||
/**
|
||||
* 统计检测计划结果。
|
||||
*
|
||||
* @param planId 检测计划ID
|
||||
* @return 检测计划统计结果
|
||||
*/
|
||||
PlanStatisticsVO statistics(AdPlanParam.StatisticsParam param);
|
||||
|
||||
/**
|
||||
* 导出检测计划数据
|
||||
*
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.njcn.gather.plan.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.njcn.gather.device.pojo.vo.PqDevVO;
|
||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||
import com.njcn.gather.plan.pojo.po.PqDevCheckHistory;
|
||||
import com.njcn.gather.plan.pojo.vo.PlanStatisticsItemVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface IPqDevCheckHistoryService extends IService<PqDevCheckHistory> {
|
||||
|
||||
void saveOrUpdateDeviceHistory(AdPlan plan, PqDevVO device);
|
||||
|
||||
void backfillPlanHistoryIfEmpty(AdPlan plan, List<PqDevVO> checkedDevices);
|
||||
|
||||
List<PlanStatisticsItemVO> listItemDistributions(String planId, String manufacturer, String devType);
|
||||
}
|
||||
@@ -59,6 +59,7 @@ import com.njcn.gather.plan.service.IAdPlanService;
|
||||
import com.njcn.gather.plan.service.IAdPlanSourceService;
|
||||
import com.njcn.gather.plan.service.IAdPlanStandardDevService;
|
||||
import com.njcn.gather.plan.service.IAdPlanTestConfigService;
|
||||
import com.njcn.gather.plan.service.IPqDevCheckHistoryService;
|
||||
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
|
||||
import com.njcn.gather.report.pojo.po.PqReport;
|
||||
import com.njcn.gather.report.service.IPqReportService;
|
||||
@@ -69,11 +70,14 @@ import com.njcn.gather.script.service.IPqScriptService;
|
||||
import com.njcn.gather.source.pojo.po.PqSource;
|
||||
import com.njcn.gather.source.service.IPqSourceService;
|
||||
import com.njcn.gather.storage.pojo.param.StorageParam;
|
||||
import com.njcn.gather.storage.pojo.po.SimAndDigBaseResult;
|
||||
import com.njcn.gather.storage.service.SimAndDigHarmonicService;
|
||||
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
|
||||
import com.njcn.gather.storage.service.TableGenService;
|
||||
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
||||
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
|
||||
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
|
||||
import com.njcn.gather.system.config.PathConfig;
|
||||
import com.njcn.gather.system.dictionary.pojo.po.DictData;
|
||||
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
|
||||
import com.njcn.gather.system.dictionary.pojo.po.DictType;
|
||||
@@ -107,6 +111,8 @@ import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -133,6 +139,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
||||
private final IDevTypeService devTypeService;
|
||||
private final IDictTypeService dictTypeService;
|
||||
private final SimAndDigHarmonicService adHarmonicService;
|
||||
private final SimAndDigNonHarmonicService adNonHarmonicService;
|
||||
private final PqDevMapper pqDevMapper;
|
||||
private final IPqDevSubService pqDevSubService;
|
||||
private final IAdPlanStandardDevService adPlanStandardDevService;
|
||||
@@ -145,10 +152,12 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
||||
private final IAdPariService adPairService;
|
||||
private final IAdPlanTestConfigService adPlanTestConfigService;
|
||||
private final ISysUserService sysUserService;
|
||||
private final IPqDevCheckHistoryService pqDevCheckHistoryService;
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
@Value("${report.reportDir}")
|
||||
private String reportPath;
|
||||
// @Value("${report.reportDir}")
|
||||
// private String reportPath;
|
||||
private final PathConfig pathConfig;
|
||||
|
||||
@Override
|
||||
public List<AdPlanVO> listAdPlan(AdPlanParam.QueryParam queryParam) {
|
||||
@@ -555,6 +564,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
||||
child.put("name", adPlan.getName());
|
||||
child.put("timeCheck", adPlan.getTimeCheck());
|
||||
child.put("dataRule", adPlan.getDataRule());
|
||||
child.put("testState", adPlan.getTestState());
|
||||
|
||||
List<PqStandardDev> pqStandardDevs = adPlanStandardDevMapper.listByPlanId(Collections.singletonList(adPlan.getId()));
|
||||
List<String> devTypeIdList = pqStandardDevs.stream().map(PqStandardDev::getDevType).collect(Collectors.toList());
|
||||
@@ -809,6 +819,242 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlanStatisticsVO statistics(AdPlanParam.StatisticsParam param) {
|
||||
String planId = param.getPlanId();
|
||||
AdPlan plan = this.getById(planId);
|
||||
if (ObjectUtil.isNull(plan)) {
|
||||
throw new BusinessException(DetectionResponseEnum.PLAN_NOT_EXIST);
|
||||
}
|
||||
|
||||
List<PqDevVO> planDevices = listPlanDevices(plan.getId(), param.getManufacturer(), param.getDevType());
|
||||
List<PqDevVO> checkedDevices = planDevices.stream()
|
||||
.filter(this::isCheckedDevice)
|
||||
.collect(Collectors.toList());
|
||||
PlanStatisticsVO statistics = new PlanStatisticsVO();
|
||||
statistics.setPlanId(plan.getId());
|
||||
statistics.setPlanName(plan.getName());
|
||||
statistics.setUncheckedDeviceCount(planDevices.size() - checkedDevices.size());
|
||||
statistics.setCheckedDeviceCount(checkedDevices.size());
|
||||
statistics.setTotalCheckCount(checkedDevices.stream().mapToInt(dev -> defaultZero(dev.getRecheckNum())).sum());
|
||||
|
||||
int firstQualifiedCount = (int) checkedDevices.stream()
|
||||
.filter(dev -> Objects.equals(dev.getRecheckNum(), 1))
|
||||
.filter(dev -> Objects.equals(dev.getCheckResult(), CheckResultEnum.ACCORD.getValue()))
|
||||
.count();
|
||||
int secondQualifiedCount = (int) checkedDevices.stream()
|
||||
.filter(dev -> Objects.equals(dev.getRecheckNum(), 2))
|
||||
.filter(dev -> Objects.equals(dev.getCheckResult(), CheckResultEnum.ACCORD.getValue()))
|
||||
.count();
|
||||
int thirdOrMoreQualifiedCount = (int) checkedDevices.stream()
|
||||
.filter(dev -> defaultZero(dev.getRecheckNum()) >= 3)
|
||||
.filter(dev -> Objects.equals(dev.getCheckResult(), CheckResultEnum.ACCORD.getValue()))
|
||||
.count();
|
||||
int unqualifiedDeviceCount = (int) checkedDevices.stream()
|
||||
.filter(dev -> Objects.equals(dev.getCheckResult(), CheckResultEnum.NOT_ACCORD.getValue()))
|
||||
.count();
|
||||
|
||||
statistics.setFirstQualifiedDeviceCount(firstQualifiedCount);
|
||||
statistics.setSecondQualifiedDeviceCount(secondQualifiedCount);
|
||||
statistics.setThirdOrMoreQualifiedDeviceCount(thirdOrMoreQualifiedCount);
|
||||
statistics.setQualifiedDeviceCount(firstQualifiedCount + secondQualifiedCount + thirdOrMoreQualifiedCount);
|
||||
statistics.setUnqualifiedDeviceCount(unqualifiedDeviceCount);
|
||||
statistics.setFirstPassRate(rate(firstQualifiedCount, checkedDevices.size()));
|
||||
statistics.setSecondPassRate(rate(secondQualifiedCount, checkedDevices.size()));
|
||||
statistics.setThirdOrMorePassRate(rate(thirdOrMoreQualifiedCount, checkedDevices.size()));
|
||||
statistics.setUnqualifiedRate(rate(unqualifiedDeviceCount, checkedDevices.size()));
|
||||
|
||||
pqDevCheckHistoryService.backfillPlanHistoryIfEmpty(plan, checkedDevices);
|
||||
List<PlanStatisticsItemVO> itemDistributions = pqDevCheckHistoryService.listItemDistributions(plan.getId(), param.getManufacturer(), param.getDevType());
|
||||
statistics.setItemDistributions(itemDistributions);
|
||||
statistics.setUnqualifiedItemCount(itemDistributions.stream()
|
||||
.mapToInt(item -> defaultZero(item.getUnqualifiedCount()))
|
||||
.sum());
|
||||
return statistics;
|
||||
}
|
||||
|
||||
private List<PqDevVO> listPlanDevices(String planId, String manufacturer, String devType) {
|
||||
PqDevParam.QueryParam queryParam = new PqDevParam.QueryParam();
|
||||
queryParam.setPlanIdList(Collections.singletonList(planId));
|
||||
List<PqDevVO> pqDevVOList = pqDevMapper.selectByQueryParam(queryParam);
|
||||
if (CollUtil.isEmpty(pqDevVOList)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return pqDevVOList.stream()
|
||||
.filter(dev -> StrUtil.isBlank(manufacturer) || Objects.equals(dev.getManufacturer(), manufacturer))
|
||||
.filter(dev -> StrUtil.isBlank(devType) || Objects.equals(dev.getDevType(), devType))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private boolean isCheckedDevice(PqDevVO dev) {
|
||||
return (Objects.equals(dev.getCheckState(), CheckStateEnum.CHECKED.getValue())
|
||||
|| Objects.equals(dev.getCheckState(), CheckStateEnum.DOCUMENTED.getValue()))
|
||||
&& !Objects.equals(dev.getCheckResult(), CheckResultEnum.UNCHECKED.getValue());
|
||||
}
|
||||
|
||||
private List<PlanStatisticsItemVO> buildItemDistributions(AdPlan plan, List<PqDevVO> checkedDevices) {
|
||||
if (CollUtil.isEmpty(checkedDevices) || StrUtil.isBlank(plan.getScriptId()) || ObjectUtil.isNull(plan.getCode())) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
Map<Integer, ScriptItemInfo> scriptItemInfoMap = getScriptItemInfoMap(plan.getScriptId());
|
||||
if (CollUtil.isEmpty(scriptItemInfoMap)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
Map<String, PlanStatisticsItemAccumulator> itemAccumulatorMap = new TreeMap<>();
|
||||
for (PqDevVO device : checkedDevices) {
|
||||
List<SimAndDigBaseResult> deviceResultList = new ArrayList<>();
|
||||
deviceResultList.addAll(adNonHarmonicService.listSimAndDigBaseResult(plan.getScriptId(), plan.getCode() + "", device.getId()));
|
||||
deviceResultList.addAll(adHarmonicService.listAllResultData(plan.getScriptId(), plan.getCode() + "", device.getId()));
|
||||
if (CollUtil.isEmpty(deviceResultList)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Map<String, List<SimAndDigBaseResult>> deviceItemResultMap = deviceResultList.stream()
|
||||
.filter(result -> ObjectUtil.isNotNull(result.getSort()))
|
||||
.map(result -> new AbstractMap.SimpleEntry<>(scriptItemInfoMap.get(result.getSort()), result))
|
||||
.filter(entry -> ObjectUtil.isNotNull(entry.getKey()))
|
||||
.collect(Collectors.groupingBy(
|
||||
entry -> entry.getKey().getItemId(),
|
||||
TreeMap::new,
|
||||
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
|
||||
));
|
||||
|
||||
deviceItemResultMap.forEach((itemId, results) -> {
|
||||
boolean hasUnqualified = results.stream().anyMatch(result -> isUnqualifiedResultFlag(result.getResultFlag()));
|
||||
boolean hasQualified = results.stream().anyMatch(result -> Objects.equals(result.getResultFlag(), 1));
|
||||
if (!hasUnqualified && !hasQualified) {
|
||||
return;
|
||||
}
|
||||
|
||||
ScriptItemInfo itemInfo = scriptItemInfoMap.get(results.get(0).getSort());
|
||||
PlanStatisticsItemAccumulator accumulator = itemAccumulatorMap.computeIfAbsent(
|
||||
itemId,
|
||||
key -> new PlanStatisticsItemAccumulator(itemId, itemInfo.getItemName())
|
||||
);
|
||||
accumulator.totalCount++;
|
||||
if (hasUnqualified) {
|
||||
accumulator.unqualifiedCount++;
|
||||
} else {
|
||||
accumulator.qualifiedCount++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return itemAccumulatorMap.values().stream()
|
||||
.map(PlanStatisticsItemAccumulator::toVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Map<Integer, ScriptItemInfo> getScriptItemInfoMap(String scriptId) {
|
||||
List<PqScriptDtls> scriptDtlsList = pqScriptDtlsService.list(new LambdaQueryWrapper<PqScriptDtls>()
|
||||
.eq(PqScriptDtls::getScriptId, scriptId)
|
||||
.ne(PqScriptDtls::getScriptIndex, -1)
|
||||
.eq(PqScriptDtls::getEnable, DataStateEnum.ENABLE.getCode())
|
||||
);
|
||||
if (CollUtil.isEmpty(scriptDtlsList)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
List<String> scriptTypeIds = scriptDtlsList.stream()
|
||||
.map(PqScriptDtls::getScriptType)
|
||||
.filter(StrUtil::isNotBlank)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
Map<String, DictTree> dictTreeMap = Collections.emptyMap();
|
||||
if (CollUtil.isNotEmpty(scriptTypeIds)) {
|
||||
dictTreeMap = dictTreeService.getDictTreeById(scriptTypeIds).stream()
|
||||
.collect(Collectors.toMap(DictTree::getId, dictTree -> dictTree, (left, right) -> left));
|
||||
}
|
||||
|
||||
Map<String, DictTree> finalDictTreeMap = dictTreeMap;
|
||||
return scriptDtlsList.stream()
|
||||
.collect(Collectors.groupingBy(PqScriptDtls::getScriptIndex, TreeMap::new, Collectors.toList()))
|
||||
.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> resolveScriptItemInfo(entry.getKey(), entry.getValue(), finalDictTreeMap),
|
||||
(left, right) -> left,
|
||||
TreeMap::new
|
||||
));
|
||||
}
|
||||
|
||||
private ScriptItemInfo resolveScriptItemInfo(Integer sort, List<PqScriptDtls> dtlsList, Map<String, DictTree> dictTreeMap) {
|
||||
if (CollUtil.isEmpty(dtlsList)) {
|
||||
return new ScriptItemInfo(String.valueOf(sort), "检测项" + sort);
|
||||
}
|
||||
PqScriptDtls first = dtlsList.get(0);
|
||||
DictTree dictTree = dictTreeMap.get(first.getScriptType());
|
||||
if (ObjectUtil.isNotNull(dictTree) && StrUtil.isNotBlank(dictTree.getName())) {
|
||||
return new ScriptItemInfo(dictTree.getId(), dictTree.getName());
|
||||
}
|
||||
if (StrUtil.isNotBlank(first.getScriptType())) {
|
||||
return new ScriptItemInfo(first.getScriptType(), "检测项" + sort);
|
||||
}
|
||||
return new ScriptItemInfo(String.valueOf(sort), "检测项" + sort);
|
||||
}
|
||||
|
||||
private boolean isUnqualifiedResultFlag(Integer resultFlag) {
|
||||
return ObjectUtil.isNotNull(resultFlag)
|
||||
&& !Objects.equals(resultFlag, 1)
|
||||
&& !Objects.equals(resultFlag, 4)
|
||||
&& !Objects.equals(resultFlag, 5);
|
||||
}
|
||||
|
||||
private Integer defaultZero(Integer value) {
|
||||
return ObjectUtil.isNull(value) ? 0 : value;
|
||||
}
|
||||
|
||||
private BigDecimal rate(Integer numerator, Integer denominator) {
|
||||
if (ObjectUtil.isNull(denominator) || denominator == 0) {
|
||||
return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
return BigDecimal.valueOf(defaultZero(numerator))
|
||||
.multiply(BigDecimal.valueOf(100))
|
||||
.divide(BigDecimal.valueOf(denominator), 2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private class PlanStatisticsItemAccumulator {
|
||||
private final String itemId;
|
||||
private final String itemName;
|
||||
private int totalCount;
|
||||
private int qualifiedCount;
|
||||
private int unqualifiedCount;
|
||||
|
||||
private PlanStatisticsItemAccumulator(String itemId, String itemName) {
|
||||
this.itemId = itemId;
|
||||
this.itemName = itemName;
|
||||
}
|
||||
|
||||
private PlanStatisticsItemVO toVO() {
|
||||
PlanStatisticsItemVO itemVO = new PlanStatisticsItemVO();
|
||||
itemVO.setItemId(itemId);
|
||||
itemVO.setItemName(itemName);
|
||||
itemVO.setUnqualifiedCount(unqualifiedCount);
|
||||
return itemVO;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ScriptItemInfo {
|
||||
private final String itemId;
|
||||
private final String itemName;
|
||||
|
||||
private ScriptItemInfo(String itemId, String itemName) {
|
||||
this.itemId = itemId;
|
||||
this.itemName = itemName;
|
||||
}
|
||||
|
||||
private String getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
private String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exportPlan(AdPlanParam.QueryParam queryParam) {
|
||||
DictData dictData = dictDataService.getDictDataById(queryParam.getPatternId());
|
||||
@@ -2089,7 +2335,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
||||
if (ObjectUtil.isNotNull(report) && report.equals(1)) {
|
||||
for (PqDev dev : devList) {
|
||||
DevType devType = devTypeService.getById(dev.getDevType());
|
||||
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
|
||||
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
|
||||
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
|
||||
// 如果reportFile存在,则将reportFile中的文件添加到已有的zip文件中
|
||||
if (FileUtil.exist(reportFile)) {
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package com.njcn.gather.plan.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.njcn.common.pojo.enums.common.DataStateEnum;
|
||||
import com.njcn.gather.device.pojo.vo.PqDevVO;
|
||||
import com.njcn.gather.plan.mapper.PqDevCheckHistoryMapper;
|
||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||
import com.njcn.gather.plan.pojo.po.PqDevCheckHistory;
|
||||
import com.njcn.gather.plan.pojo.vo.PlanStatisticsItemVO;
|
||||
import com.njcn.gather.plan.service.IPqDevCheckHistoryService;
|
||||
import com.njcn.gather.script.mapper.PqScriptDtlsMapper;
|
||||
import com.njcn.gather.script.pojo.po.PqScriptDtls;
|
||||
import com.njcn.gather.storage.pojo.po.SimAndDigBaseResult;
|
||||
import com.njcn.gather.storage.service.SimAndDigHarmonicService;
|
||||
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
|
||||
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
|
||||
import com.njcn.gather.system.dictionary.service.IDictTreeService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PqDevCheckHistoryServiceImpl extends ServiceImpl<PqDevCheckHistoryMapper, PqDevCheckHistory> implements IPqDevCheckHistoryService {
|
||||
|
||||
private final SimAndDigNonHarmonicService adNonHarmonicService;
|
||||
private final SimAndDigHarmonicService adHarmonicService;
|
||||
private final PqScriptDtlsMapper pqScriptDtlsMapper;
|
||||
private final IDictTreeService dictTreeService;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void saveOrUpdateDeviceHistory(AdPlan plan, PqDevVO device) {
|
||||
if (ObjectUtil.isNull(plan)
|
||||
|| ObjectUtil.isNull(device)
|
||||
|| StrUtil.isBlank(plan.getScriptId())
|
||||
|| ObjectUtil.isNull(plan.getCode())
|
||||
|| StrUtil.isBlank(device.getId())
|
||||
|| ObjectUtil.isNull(device.getRecheckNum())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<Integer, ScriptItemInfo> scriptItemInfoMap = getScriptItemInfoMap(plan.getScriptId());
|
||||
if (CollUtil.isEmpty(scriptItemInfoMap)) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<SimAndDigBaseResult> resultList = new ArrayList<>();
|
||||
resultList.addAll(adNonHarmonicService.listSimAndDigBaseResult(plan.getScriptId(), plan.getCode() + "", device.getId()));
|
||||
resultList.addAll(adHarmonicService.listAllResultData(plan.getScriptId(), plan.getCode() + "", device.getId()));
|
||||
if (CollUtil.isEmpty(resultList)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, List<SimAndDigBaseResult>> itemResultMap = resultList.stream()
|
||||
.filter(result -> ObjectUtil.isNotNull(result.getSort()))
|
||||
.map(result -> new AbstractMap.SimpleEntry<>(scriptItemInfoMap.get(result.getSort()), result))
|
||||
.filter(entry -> ObjectUtil.isNotNull(entry.getKey()))
|
||||
.collect(Collectors.groupingBy(
|
||||
entry -> entry.getKey().getItemId(),
|
||||
TreeMap::new,
|
||||
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
|
||||
));
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
itemResultMap.forEach((itemId, results) -> {
|
||||
boolean hasUnqualified = results.stream().anyMatch(result -> isUnqualifiedResultFlag(result.getResultFlag()));
|
||||
boolean hasQualified = results.stream().anyMatch(result -> Objects.equals(result.getResultFlag(), 1));
|
||||
if (!hasUnqualified && !hasQualified) {
|
||||
return;
|
||||
}
|
||||
|
||||
ScriptItemInfo itemInfo = scriptItemInfoMap.get(results.get(0).getSort());
|
||||
PqDevCheckHistory history = this.getOne(new LambdaQueryWrapper<PqDevCheckHistory>()
|
||||
.eq(PqDevCheckHistory::getPlanId, plan.getId())
|
||||
.eq(PqDevCheckHistory::getDevId, device.getId())
|
||||
.eq(PqDevCheckHistory::getRecheckNum, device.getRecheckNum())
|
||||
.eq(PqDevCheckHistory::getItemId, itemId)
|
||||
.last("LIMIT 1"));
|
||||
|
||||
if (ObjectUtil.isNull(history)) {
|
||||
history = new PqDevCheckHistory();
|
||||
history.setId(UUID.randomUUID().toString().replaceAll("-", ""));
|
||||
history.setPlanId(plan.getId());
|
||||
history.setDevId(device.getId());
|
||||
history.setRecheckNum(device.getRecheckNum());
|
||||
history.setItemId(itemId);
|
||||
history.setCreateBy(device.getCheckBy());
|
||||
history.setCreateTime(now);
|
||||
}
|
||||
|
||||
history.setDevType(device.getDevType());
|
||||
history.setManufacturer(device.getManufacturer());
|
||||
history.setItemName(itemInfo.getItemName());
|
||||
history.setResult(hasUnqualified ? 0 : 1);
|
||||
history.setCheckTime(ObjectUtil.isNotNull(device.getCheckTime()) ? device.getCheckTime() : now);
|
||||
history.setState(DataStateEnum.ENABLE.getCode());
|
||||
history.setUpdateBy(device.getCheckBy());
|
||||
history.setUpdateTime(now);
|
||||
this.saveOrUpdate(history);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void backfillPlanHistoryIfEmpty(AdPlan plan, List<PqDevVO> checkedDevices) {
|
||||
if (ObjectUtil.isNull(plan) || CollUtil.isEmpty(checkedDevices)) {
|
||||
return;
|
||||
}
|
||||
long historyCount = this.count(new LambdaQueryWrapper<PqDevCheckHistory>()
|
||||
.eq(PqDevCheckHistory::getPlanId, plan.getId())
|
||||
.eq(PqDevCheckHistory::getState, DataStateEnum.ENABLE.getCode()));
|
||||
if (historyCount > 0) {
|
||||
return;
|
||||
}
|
||||
checkedDevices.forEach(device -> saveOrUpdateDeviceHistory(plan, device));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<PlanStatisticsItemVO> listItemDistributions(String planId, String manufacturer, String devType) {
|
||||
List<PlanStatisticsItemVO> itemDistributions = this.baseMapper.listItemDistributions(planId, manufacturer, devType);
|
||||
if (CollUtil.isEmpty(itemDistributions)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
itemDistributions.forEach(item -> item.setUnqualifiedCount(defaultZero(item.getUnqualifiedCount())));
|
||||
return itemDistributions;
|
||||
}
|
||||
|
||||
private Map<Integer, ScriptItemInfo> getScriptItemInfoMap(String scriptId) {
|
||||
List<PqScriptDtls> scriptDtlsList = pqScriptDtlsMapper.selectList(new LambdaQueryWrapper<PqScriptDtls>()
|
||||
.eq(PqScriptDtls::getScriptId, scriptId)
|
||||
.ne(PqScriptDtls::getScriptIndex, -1)
|
||||
.eq(PqScriptDtls::getEnable, DataStateEnum.ENABLE.getCode())
|
||||
);
|
||||
if (CollUtil.isEmpty(scriptDtlsList)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
List<String> scriptTypeIds = scriptDtlsList.stream()
|
||||
.map(PqScriptDtls::getScriptType)
|
||||
.filter(StrUtil::isNotBlank)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
Map<String, DictTree> dictTreeMap = Collections.emptyMap();
|
||||
if (CollUtil.isNotEmpty(scriptTypeIds)) {
|
||||
dictTreeMap = dictTreeService.getDictTreeById(scriptTypeIds).stream()
|
||||
.collect(Collectors.toMap(DictTree::getId, dictTree -> dictTree, (left, right) -> left));
|
||||
}
|
||||
|
||||
Map<String, DictTree> finalDictTreeMap = dictTreeMap;
|
||||
return scriptDtlsList.stream()
|
||||
.collect(Collectors.groupingBy(PqScriptDtls::getScriptIndex, TreeMap::new, Collectors.toList()))
|
||||
.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> resolveScriptItemInfo(entry.getKey(), entry.getValue(), finalDictTreeMap),
|
||||
(left, right) -> left,
|
||||
TreeMap::new
|
||||
));
|
||||
}
|
||||
|
||||
private ScriptItemInfo resolveScriptItemInfo(Integer sort, List<PqScriptDtls> dtlsList, Map<String, DictTree> dictTreeMap) {
|
||||
if (CollUtil.isEmpty(dtlsList)) {
|
||||
return new ScriptItemInfo(String.valueOf(sort), "检测项" + sort);
|
||||
}
|
||||
PqScriptDtls first = dtlsList.get(0);
|
||||
DictTree dictTree = dictTreeMap.get(first.getScriptType());
|
||||
if (ObjectUtil.isNotNull(dictTree) && StrUtil.isNotBlank(dictTree.getName())) {
|
||||
return new ScriptItemInfo(dictTree.getId(), dictTree.getName());
|
||||
}
|
||||
if (StrUtil.isNotBlank(first.getScriptType())) {
|
||||
return new ScriptItemInfo(first.getScriptType(), "检测项" + sort);
|
||||
}
|
||||
return new ScriptItemInfo(String.valueOf(sort), "检测项" + sort);
|
||||
}
|
||||
|
||||
private boolean isUnqualifiedResultFlag(Integer resultFlag) {
|
||||
return ObjectUtil.isNotNull(resultFlag)
|
||||
&& !Objects.equals(resultFlag, 1)
|
||||
&& !Objects.equals(resultFlag, 4)
|
||||
&& !Objects.equals(resultFlag, 5);
|
||||
}
|
||||
|
||||
private Integer defaultZero(Integer value) {
|
||||
return ObjectUtil.isNull(value) ? 0 : value;
|
||||
}
|
||||
|
||||
private static class ScriptItemInfo {
|
||||
private final String itemId;
|
||||
private final String itemName;
|
||||
|
||||
private ScriptItemInfo(String itemId, String itemName) {
|
||||
this.itemId = itemId;
|
||||
this.itemName = itemName;
|
||||
}
|
||||
|
||||
private String getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
private String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ public enum BookmarkEnum {
|
||||
|
||||
private String desc;
|
||||
|
||||
/** 书签处理顺序:1=数据项,2=结果信息,3=目录信息;由 dealDataModelScatteredByBookmark 排序时使用 */
|
||||
private Integer sort;
|
||||
|
||||
BookmarkEnum(String key, String desc, Integer sort) {
|
||||
|
||||
@@ -68,15 +68,13 @@ import com.njcn.gather.storage.service.SimAndDigHarmonicService;
|
||||
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
|
||||
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
||||
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
|
||||
import com.njcn.gather.system.config.PathConfig;
|
||||
import com.njcn.gather.system.dictionary.pojo.po.DictData;
|
||||
import com.njcn.gather.system.dictionary.service.IDictDataService;
|
||||
import com.njcn.gather.system.pojo.enums.SystemResponseEnum;
|
||||
import com.njcn.gather.tools.report.model.constant.ReportConstant;
|
||||
import com.njcn.gather.tools.report.service.IWordReportService;
|
||||
import com.njcn.gather.tools.report.util.BookmarkUtil;
|
||||
import com.njcn.gather.tools.report.util.Docx4jUtil;
|
||||
import com.njcn.gather.tools.report.util.DocxMergeUtil;
|
||||
import com.njcn.gather.tools.report.util.WordDocumentUtil;
|
||||
import com.njcn.gather.tools.report.util.*;
|
||||
import com.njcn.gather.type.pojo.po.DevType;
|
||||
import com.njcn.gather.type.service.IDevTypeService;
|
||||
import com.njcn.gather.user.user.pojo.po.SysUser;
|
||||
@@ -133,13 +131,24 @@ import java.util.stream.Collectors;
|
||||
@RequiredArgsConstructor
|
||||
public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> implements IPqReportService {
|
||||
|
||||
@Value("${report.template:D:\\template}")
|
||||
private String templatePath;
|
||||
|
||||
@Value("${report.reportDir:D:\\report}")
|
||||
private String reportPath;
|
||||
|
||||
/**
|
||||
* resultMap 内部协议:当 dealDataLine 跑完一轮但未采集到任何有效合格性数据时,
|
||||
* 在 resultMap 中塞入这个 key 作为"已尝试且无数据"的哨兵,避免后续 TEST_RESULT_*
|
||||
* 分支的 fallback 重复调用 dealDataLine 浪费资源;同时 dealTestResultLine 检测到
|
||||
* 此 key 存在时跳过结论表生成。
|
||||
* <p>
|
||||
* 故意使用明显非业务字符串,避免与任何 PqScriptDtls.scriptCode / PowerIndexEnum
|
||||
* 的真实业务取值撞车。
|
||||
*/
|
||||
private static final String RESULT_MAP_NO_DATA_FLAG = "__internal_no_data__";
|
||||
|
||||
// @Value("${report.template:D:\\template}")
|
||||
// private String templatePath;
|
||||
//
|
||||
// @Value("${report.reportDir:D:\\report}")
|
||||
// private String reportPath;
|
||||
private final PathConfig pathConfig;
|
||||
|
||||
@Value("${qr.cloud}")
|
||||
private String cloudUrl;
|
||||
|
||||
@@ -316,7 +325,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
MultipartFile baseFile = reportParam.getBaseFile();
|
||||
MultipartFile detailFile = reportParam.getDetailFile();
|
||||
String relativePath = reportParam.getName() + File.separator + reportParam.getVersion() + File.separator;
|
||||
String newDir = templatePath + File.separator + relativePath;
|
||||
String newDir = pathConfig.getReportTemplatePath() + File.separator + relativePath;
|
||||
|
||||
long FILE_SIZE_LIMIT = 5 * 1024 * 1024;
|
||||
if (isAdd) {
|
||||
@@ -393,13 +402,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
// 文件夹重命名
|
||||
String oldBasePathStr = oldPqReport.getBasePath();
|
||||
String baseName = oldBasePathStr.substring(oldBasePathStr.lastIndexOf(File.separator) + 1);
|
||||
Path oldBasePath = Paths.get(templatePath + File.separator + oldBasePathStr);
|
||||
Path oldBasePath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + oldBasePathStr);
|
||||
Path newBasePath = Paths.get(newDir + baseName);
|
||||
pqReport.setBasePath(relativePath + baseName);
|
||||
|
||||
String oldDetailPathStr = oldPqReport.getDetailPath();
|
||||
String detailName = oldDetailPathStr.substring(oldDetailPathStr.lastIndexOf(File.separator) + 1);
|
||||
Path oldDetailPath = Paths.get(templatePath + File.separator + oldDetailPathStr);
|
||||
Path oldDetailPath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + oldDetailPathStr);
|
||||
Path newDetailPath = Paths.get(newDir + detailName);
|
||||
pqReport.setDetailPath(relativePath + detailName);
|
||||
|
||||
@@ -410,13 +419,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
Files.move(oldBasePath, newBasePath);
|
||||
Files.move(oldDetailPath, newDetailPath);
|
||||
if (!oldPqReport.getName().equals(reportParam.getName()) && !this.existSameName(pqReport.getId(), oldPqReport.getName())) {
|
||||
this.recursionDeleteDirectory(templatePath + File.separator + oldPqReport.getName());
|
||||
this.recursionDeleteDirectory(pathConfig.getReportTemplatePath() + File.separator + oldPqReport.getName());
|
||||
} else {
|
||||
Paths.get(templatePath + oldDir).toFile().delete();
|
||||
Paths.get(pathConfig.getReportTemplatePath() + oldDir).toFile().delete();
|
||||
}
|
||||
} else {
|
||||
// 文件夹重命名
|
||||
Paths.get(templatePath + oldDir).toFile().renameTo(Paths.get(newDir).toFile());
|
||||
Paths.get(pathConfig.getReportTemplatePath() + oldDir).toFile().renameTo(Paths.get(newDir).toFile());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new BusinessException(ReportResponseEnum.FILE_RENAME_FAILED);
|
||||
@@ -425,13 +434,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
|
||||
if (!baseFileOriginalFilename.isEmpty()) {
|
||||
pqReport.setBasePath(relativePath + baseFileOriginalFilename);
|
||||
Paths.get(templatePath + File.separator + oldPqReport.getBasePath()).toFile().delete();
|
||||
Paths.get(pathConfig.getReportTemplatePath() + File.separator + oldPqReport.getBasePath()).toFile().delete();
|
||||
Paths.get(newDir + oldPqReport.getBasePath().substring(oldPqReport.getBasePath().lastIndexOf(File.separator) + 1)).toFile().delete();
|
||||
this.uploadFile(baseFile, newDir + baseFileOriginalFilename);
|
||||
}
|
||||
if (!detailFileOriginalFilename.isEmpty()) {
|
||||
pqReport.setDetailPath(relativePath + detailFileOriginalFilename);
|
||||
Paths.get(templatePath + File.separator + oldPqReport.getDetailPath()).toFile().delete();
|
||||
Paths.get(pathConfig.getReportTemplatePath() + File.separator + oldPqReport.getDetailPath()).toFile().delete();
|
||||
Paths.get(newDir + oldPqReport.getDetailPath().substring(oldPqReport.getDetailPath().lastIndexOf(File.separator) + 1)).toFile().delete();
|
||||
this.uploadFile(detailFile, newDir + detailFileOriginalFilename);
|
||||
}
|
||||
@@ -516,7 +525,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
private void deleteFile(List<String> ids) {
|
||||
List<PqReport> pqReports = this.listByIds(ids);
|
||||
for (PqReport pqReport : pqReports) {
|
||||
String uploadDir = templatePath + File.separator + pqReport.getName() + File.separator + pqReport.getVersion() + File.separator;
|
||||
String uploadDir = pathConfig.getReportTemplatePath() + File.separator + pqReport.getName() + File.separator + pqReport.getVersion() + File.separator;
|
||||
Path uploadPath = Paths.get(uploadDir);
|
||||
if (Files.exists(uploadPath)) {
|
||||
//清空目录下的文件
|
||||
@@ -528,7 +537,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
}
|
||||
}
|
||||
file1.delete();
|
||||
String dir = templatePath + File.separator + pqReport.getName() + File.separator;
|
||||
String dir = pathConfig.getReportTemplatePath() + File.separator + pqReport.getName() + File.separator;
|
||||
Path dirPath = Paths.get(dir);
|
||||
File dirFile = dirPath.toFile();
|
||||
File[] fileArr2 = dirFile.listFiles();
|
||||
@@ -583,6 +592,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
/**
|
||||
* 根据设备类型生成报告
|
||||
* 注:该方法目前仅支持楼下出厂检测场景,属于模板占位符替换方式,后期可能会有调整
|
||||
* <p>
|
||||
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
|
||||
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
|
||||
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
|
||||
* 而非待修复缺陷。
|
||||
*
|
||||
* @param devReportParam 被检设备信息
|
||||
*/
|
||||
@@ -617,8 +631,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
InputStream finalWordStream = DocxMergeUtil.mergeDocuments(wordFileInputStreams);
|
||||
// 处理需要输出的目录地址 基础路径+设备类型+装置编号.docx
|
||||
// 最终文件输出的路径
|
||||
// String dirPath = reportPath.concat(File.separator).concat(devType.getName());
|
||||
String dirPath = reportPath;
|
||||
// String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
|
||||
String dirPath = pathConfig.getReportPath();
|
||||
// 确保目录存在
|
||||
ensureDirectoryExists(dirPath);
|
||||
String reportFullPath = dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
||||
@@ -783,6 +797,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
/**
|
||||
* 需要支持批量生成,如果用户选择批量生成,则默认都采用测试数据的第一个合格,如果
|
||||
* 比对模式下生成检测报告,实际后期需要根据用户选择的检测数据或者某次波形数据生成报告
|
||||
* <p>
|
||||
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
|
||||
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
|
||||
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
|
||||
* 而非待修复缺陷。
|
||||
*
|
||||
* @param plan 计划信息
|
||||
* @param devReportParam 设备信息
|
||||
@@ -806,8 +825,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
if (Objects.isNull(report)) {
|
||||
throw new BusinessException(ReportResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
|
||||
}
|
||||
Path basePath = Paths.get(templatePath + File.separator + report.getBasePath());
|
||||
Path detailPath = Paths.get(templatePath + File.separator + report.getDetailPath());
|
||||
Path basePath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getBasePath());
|
||||
Path detailPath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getDetailPath());
|
||||
try (InputStream baseInputStream = Files.newInputStream(basePath);
|
||||
InputStream detailInputStream = Files.newInputStream(detailPath)) {
|
||||
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
|
||||
@@ -821,7 +840,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
MainDocumentPart detailDocumentPart = detailModelDocument.getMainDocumentPart();
|
||||
dealDataModelScatteredByBookmarkByPlanContrast(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
|
||||
// 保存新的文档
|
||||
String dirPath = reportPath.concat(File.separator).concat(plan.getName());
|
||||
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(plan.getName()));
|
||||
// 确保目录存在
|
||||
ensureDirectoryExists(dirPath);
|
||||
// 构建文件名:cityName_gdName_subName_name.docx
|
||||
@@ -861,6 +880,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
/**
|
||||
* 根据计划绑定的报告模板生成报告
|
||||
* 注:该方法目前属于同用信息占位符替换,数据页为面向对象动态填充拼凑方式
|
||||
* <p>
|
||||
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
|
||||
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
|
||||
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
|
||||
* 而非待修复缺陷。
|
||||
*
|
||||
* @param plan 计划信息
|
||||
* @param devReportParam 设备信息
|
||||
@@ -883,8 +907,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
if (Objects.isNull(report)) {
|
||||
throw new BusinessException(ReportResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
|
||||
}
|
||||
Path basePath = Paths.get(templatePath + File.separator + report.getBasePath());
|
||||
Path detailPath = Paths.get(templatePath + File.separator + report.getDetailPath());
|
||||
Path basePath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getBasePath());
|
||||
Path detailPath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getDetailPath());
|
||||
try (InputStream baseInputStream = Files.newInputStream(basePath);
|
||||
InputStream detailInputStream = Files.newInputStream(detailPath)) {
|
||||
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
|
||||
@@ -899,7 +923,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
dealDataModelScatteredByBookmark(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
|
||||
|
||||
// 保存新的文档
|
||||
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
|
||||
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName()));
|
||||
// 确保目录存在
|
||||
ensureDirectoryExists(dirPath);
|
||||
baseModelDocument.save(new File(dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX)));
|
||||
@@ -950,9 +974,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
* 1、数据项
|
||||
* 2、结果信息
|
||||
* 3、目录信息
|
||||
* 所以要先先获取的书签进行操作排序
|
||||
* 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺序
|
||||
* */
|
||||
Collections.sort(bookmarkEnums);
|
||||
bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal));
|
||||
List<Object> todoInsertList;
|
||||
BookmarkUtil.BookmarkInfo bookmarkInfo;
|
||||
Map<Integer/*回路号*/, List<ContrastTestResult>> resultMap = null;
|
||||
@@ -1230,9 +1254,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
* 1、数据项
|
||||
* 2、结果信息
|
||||
* 3、目录信息
|
||||
* 所以要先先获取的书签进行操作排序
|
||||
* 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺序
|
||||
* */
|
||||
Collections.sort(bookmarkEnums);
|
||||
bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal));
|
||||
// 定义个结果,以便存在结果信息的书签
|
||||
Map<String/*指标名称*/, List<Boolean/*以回路的顺序填充结果*/>> resultMap = new HashMap<>();
|
||||
List<Object> todoInsertList;
|
||||
@@ -1281,7 +1305,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
if (CollUtil.isEmpty(resultMap)) {
|
||||
dealDataLine(baseDocumentPart, devReportParam, pqDevVO, resultMap);
|
||||
}
|
||||
bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.TEST_RESULT_LINE.getKey(), bookmarks);
|
||||
bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.TEST_RESULT_DETAIL.getKey(), bookmarks);
|
||||
todoInsertList = dealTestResultLine(devReportParam, resultMap, DocAnchorEnum.TEST_RESULT_DETAIL);
|
||||
if (Objects.nonNull(bookmarkInfo) && CollectionUtil.isNotEmpty(todoInsertList)) {
|
||||
BookmarkUtil.insertElement(bookmarkInfo, todoInsertList);
|
||||
@@ -1306,8 +1330,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
*/
|
||||
private List<Object> dealTestResultLine(DevReportParam devReportParam, Map<String, List<Boolean>> resultMap, DocAnchorEnum docAnchorEnum) {
|
||||
List<Object> todoInsertList = new ArrayList<>();
|
||||
// 先判断数据有没有,如果没有,则不处理
|
||||
if (CollUtil.isEmpty(resultMap.get(PowerIndexEnum.UNKNOWN.getKey()))) {
|
||||
// 先判断数据有没有,如果没有,则不处理(哨兵协议详见 RESULT_MAP_NO_DATA_FLAG 注释)
|
||||
if (!resultMap.containsKey(RESULT_MAP_NO_DATA_FLAG)) {
|
||||
ObjectFactory factory = Context.getWmlObjectFactory();
|
||||
// 源文档的内容
|
||||
// 创建表格(示例为3列,列数可任意调整)
|
||||
@@ -1396,13 +1420,27 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
|
||||
|
||||
/**
|
||||
* 处理以回路为维度的数据项,书签占位符的方式
|
||||
* 以回路维度处理数据项,并填充 resultMap(指标合格性结论)。
|
||||
* <p>
|
||||
* 本方法承担双重职责:
|
||||
* <ol>
|
||||
* <li><b>返回值</b>:根据 modelPart 中的 H5 分组表格模板,灌入实测数据后生成可插入文档的元素列表;</li>
|
||||
* <li><b>副作用</b>:把每个指标在各回路上的合格性写入 resultMap,供后续 dealTestResultLine 构造结论表使用。</li>
|
||||
* </ol>
|
||||
* 调用约定(务必区分以下两条路径,避免误解形参用途):
|
||||
* <ul>
|
||||
* <li><b>常规路径</b>(DATA_LINE 分支):modelPart 传 detail 文档(数据页模板池),返回值会被插入 DATA_LINE 书签锚点。</li>
|
||||
* <li><b>fallback 路径</b>(TEST_RESULT_* 分支且 resultMap 为空时):modelPart 允许传 base 文档(封面页);此时模板池为空,返回值无业务意义,调用方应丢弃,仅借此触发 resultMap 计算。</li>
|
||||
* </ul>
|
||||
* 因此 modelPart 命名保持中性,不要改回 detailXxx 等带语义偏向的名字。
|
||||
*
|
||||
* @param detailModelDocument 数据项模板
|
||||
* @param devReportParam 测试报告参数
|
||||
* @param pqDevVO 被检设备
|
||||
* @param modelPart 文档模板部分;常规传 detail 文档,fallback 仅需算 resultMap 时可传 base 文档
|
||||
* @param devReportParam 测试报告参数
|
||||
* @param pqDevVO 被检设备
|
||||
* @param resultMap 结果性数据集合(被本方法写入;fallback 路径正是借此计算)
|
||||
* @return 待插入文档的元素列表;fallback 路径下应被调用方丢弃
|
||||
*/
|
||||
private List<Object> dealDataLine(MainDocumentPart detailModelDocument, DevReportParam devReportParam, PqDevVO pqDevVO, Map<String, List<Boolean>> resultMap) {
|
||||
private List<Object> dealDataLine(MainDocumentPart modelPart, DevReportParam devReportParam, PqDevVO pqDevVO, Map<String, List<Boolean>> resultMap) {
|
||||
List<Object> todoInsertList = new ArrayList<>();
|
||||
// 以回路维度处理数据项
|
||||
Integer devChns = pqDevVO.getDevChns();
|
||||
@@ -1410,8 +1448,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
// 读取该计划的检测大项组装数据内容
|
||||
List<PqScriptDtlDataVO> pqScriptDtlsList = pqScriptDtlsService.getScriptDtlsDataList(devReportParam.getScriptId());
|
||||
Map<String, List<PqScriptDtlDataVO>> scriptMap = pqScriptDtlsList.stream().collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptCode, LinkedHashMap::new, Collectors.toList()));
|
||||
List<Object> allContent = detailModelDocument.getContent();
|
||||
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(allContent, detailModelDocument);
|
||||
List<Object> allContent = modelPart.getContent();
|
||||
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(allContent, modelPart);
|
||||
Map<String, List<Docx4jUtil.HeadingContent>> contentMap = headingContents.stream().collect(Collectors.groupingBy(Docx4jUtil.HeadingContent::getHeadingText, Collectors.toList()));
|
||||
for (int i = 0; i < devChns; i++) {
|
||||
// 回路标题
|
||||
@@ -1479,9 +1517,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
}
|
||||
}
|
||||
}
|
||||
// 如果经过一顿处理后,结果性数据集合还是空,塞个特殊数据进去,避免嵌套循环
|
||||
// 经过一轮处理仍未采集到任何合格性数据时,塞入哨兵:
|
||||
// 一是让后续 TEST_RESULT_* 分支的 fallback 看到 resultMap 非空而跳过重复调用本方法,
|
||||
// 二是供 dealTestResultLine 据此跳过结论表生成(哨兵协议详见 RESULT_MAP_NO_DATA_FLAG 注释)。
|
||||
if (CollUtil.isEmpty(resultMap)) {
|
||||
resultMap.put(PowerIndexEnum.UNKNOWN.getKey(), Collections.singletonList(false));
|
||||
resultMap.put(RESULT_MAP_NO_DATA_FLAG, Collections.singletonList(false));
|
||||
}
|
||||
return todoInsertList;
|
||||
}
|
||||
@@ -1894,7 +1934,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
|
||||
if (SceneEnum.LEAVE_FACTORY_TEST.getValue().equals(currrentScene)) {
|
||||
// 出厂测试场景
|
||||
filePath = reportPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
||||
filePath = pathConfig.getReportPath().concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
||||
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
|
||||
} else if (plan != null) {
|
||||
// 根据计划模式确定路径结构
|
||||
@@ -1906,16 +1946,16 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
pqDevVO.getGdName() != null ? pqDevVO.getGdName() : "未知供电公司",
|
||||
pqDevVO.getSubName() != null ? pqDevVO.getSubName() : "未知电站",
|
||||
pqDevVO.getName() != null ? pqDevVO.getName() : "未知设备");
|
||||
filePath = reportPath.concat(File.separator).concat(plan.getName()).concat(File.separator).concat(fileName);
|
||||
filePath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(plan.getName())).concat(File.separator).concat(fileName);
|
||||
downloadFileName = fileName;
|
||||
} else {
|
||||
// 数字/模拟模式:使用原来的路径结构
|
||||
filePath = reportPath.concat(File.separator).concat(devType.getName()).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
||||
filePath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName())).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
||||
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
|
||||
}
|
||||
} else {
|
||||
// 兜底:使用旧的路径结构
|
||||
filePath = reportPath.concat(File.separator).concat(devType.getName()).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
||||
filePath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName())).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
||||
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
|
||||
}
|
||||
|
||||
@@ -2443,7 +2483,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
||||
return;
|
||||
}
|
||||
log.info("找到{}台设备需要上传报告", devices.size());
|
||||
String dirPath = reportPath;
|
||||
String dirPath = pathConfig.getReportPath();
|
||||
// 确保目录存在
|
||||
ensureDirectoryExists(dirPath);
|
||||
// 异步批量上传每台设备的报告
|
||||
|
||||
@@ -3140,7 +3140,7 @@ public class ResultServiceImpl implements IResultService {
|
||||
checkDataParam.setIsValueTypeName(false);
|
||||
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
|
||||
|
||||
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity());
|
||||
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,6 +34,7 @@ import com.njcn.gather.script.service.IPqScriptCheckDataService;
|
||||
import com.njcn.gather.script.service.IPqScriptDtlsService;
|
||||
import com.njcn.gather.script.util.ScriptDtlsDesc;
|
||||
import com.njcn.gather.script.util.ThreePhaseUnbalance;
|
||||
import com.njcn.gather.source.service.IPqSourceService;
|
||||
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
|
||||
import com.njcn.gather.system.dictionary.service.IDictTreeService;
|
||||
import com.njcn.gather.system.pojo.enums.DicDataEnum;
|
||||
@@ -68,20 +69,17 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
private final static String INHARM_I = "InHarm_I";
|
||||
private final static String DIP = "Dip";
|
||||
private final static String FLICKER = "Flicker";
|
||||
// @Value("${Dip.fPreTime}")
|
||||
// @Value("${Dip.fPreTime}")
|
||||
// private Double fPreTime;
|
||||
@Value("${Dip.fRampIn}")
|
||||
private Double fRampIn;
|
||||
@Value("${Dip.fRampOut}")
|
||||
private Double fRampOut;
|
||||
// @Value("${Dip.fAfterTime}")
|
||||
// @Value("${Dip.fAfterTime}")
|
||||
// private Double fAfterTime;
|
||||
@Value("${Flicker.waveFluType}")
|
||||
private String waveFluType;
|
||||
@Value("${Flicker.waveType}")
|
||||
private String waveType;
|
||||
@Value("${Flicker.fDutyCycle}")
|
||||
private Double fDutyCycle;
|
||||
private static final String waveFluType = "SQU";
|
||||
private static final String waveType = "CPM";
|
||||
private static final Double fDutyCycle = 50.0;
|
||||
|
||||
|
||||
private final IPqDevService pqDevService;
|
||||
@@ -91,6 +89,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
private final IDevTypeService devTypeService;
|
||||
private final IDictTreeService dictTreeService;
|
||||
private final AdPlanMapper adPlanMapper;
|
||||
private final IPqSourceService pqSourceService;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@@ -422,7 +421,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
|
||||
@Override
|
||||
public List<PqScriptDtlsParam.CheckData> scriptDtlsCheckDataList(PqScriptDtlsParam sourceIssue) {
|
||||
Boolean valueType = pqScriptMapper.selectScriptIsValueType(sourceIssue.getScriptId());
|
||||
// Boolean valueType = pqScriptMapper.selectScriptIsValueType(sourceIssue.getScriptId());
|
||||
|
||||
List<PqScriptDtlsParam.CheckData> info = new ArrayList<>();
|
||||
//获取所有下拉值情况
|
||||
@@ -630,9 +629,9 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
checkData.setErrorFlag(channelListDTO.getErrorFlag());
|
||||
checkData.setEnable(channelListDTO.getEnable());
|
||||
//电压*电流*cos(电压角度-电流角度)
|
||||
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 10000 * Math.cos((listDTO.getFPhase() - channelI.get(0).getFPhase()) * Math.PI / 180));
|
||||
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 100 * Math.cos((listDTO.getFPhase() - channelI.get(0).getFPhase()) * Math.PI / 180));
|
||||
// if (valueType) {
|
||||
checkData.setValue(checkData.getValue() * 57.74 * 5);
|
||||
// checkData.setValue(checkData.getValue() * 57.74 * 5);
|
||||
// }
|
||||
setCheck(info, checkData, channelListDTO, checkArchive, listDTO);
|
||||
}
|
||||
@@ -653,9 +652,9 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
checkData.setErrorFlag(channelListDTO.getErrorFlag());
|
||||
checkData.setEnable(channelListDTO.getEnable());
|
||||
//电压*电流*cos(电压角度-电流角度)
|
||||
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 10000 * Math.sin((listDTO.getFPhase() - channelI.get(0).getFPhase()) * Math.PI / 180));
|
||||
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 100 * Math.sin((listDTO.getFPhase() - channelI.get(0).getFPhase()) * Math.PI / 180));
|
||||
// if (valueType) {
|
||||
checkData.setValue(checkData.getValue() * 57.74 * 5);
|
||||
// checkData.setValue(checkData.getValue() * 57.74 * 5);
|
||||
// }
|
||||
setCheck(info, checkData, channelListDTO, checkArchive, listDTO);
|
||||
}
|
||||
@@ -676,9 +675,9 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
checkData.setErrorFlag(channelListDTO.getErrorFlag());
|
||||
checkData.setEnable(channelListDTO.getEnable());
|
||||
//电压*电流*cos(电压角度-电流角度)
|
||||
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 10000);
|
||||
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 100);
|
||||
// if (valueType) {
|
||||
checkData.setValue(checkData.getValue() * 57.74 * 5);
|
||||
// checkData.setValue(checkData.getValue() * 57.74 * 5);
|
||||
// }
|
||||
setCheck(info, checkData, channelListDTO, checkArchive, listDTO);
|
||||
}
|
||||
@@ -781,7 +780,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
@Override
|
||||
public Set<String> getScriptToIcdCheckInfo(PreDetectionParam param) {
|
||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||
issueParam.setSourceId(param.getSourceId());
|
||||
issueParam.setSourceId(param.getSourceName());
|
||||
issueParam.setDevIds(param.getDevIds());
|
||||
issueParam.setScriptId(param.getScriptId());
|
||||
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
|
||||
@@ -974,7 +973,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
for (int i = 0; i < pqScriptDtls.size(); i++) {
|
||||
PqScriptDtls scriptDtls = pqScriptDtls.get(i);
|
||||
// 注意此处scriptDtls.getValue() < 1.0,考虑到有些已经投入运行的地方,可能没有改库,避免不必要的异常
|
||||
if(scriptDtls.getValueType().equalsIgnoreCase("CUR") && scriptDtls.getValue() < 1.0){
|
||||
if (scriptDtls.getValueType().equalsIgnoreCase("CUR") && scriptDtls.getValue() < 1.0) {
|
||||
scriptDtls.setValue(devCurr * scriptDtls.getValue());
|
||||
}
|
||||
}
|
||||
@@ -1065,9 +1064,16 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
|
||||
channelListDTO.setDipData(dipDataDTO);
|
||||
//闪变数据
|
||||
SourceIssue.ChannelListDTO.FlickerDataDTO flickerDataDTO = new SourceIssue.ChannelListDTO.FlickerDataDTO();
|
||||
flickerDataDTO.setWaveFluType(waveFluType);
|
||||
flickerDataDTO.setWaveType(waveType);
|
||||
flickerDataDTO.setFDutyCycle(fDutyCycle);
|
||||
SourceIssue.ChannelListDTO.FlickerDataDTO flickerData = channelListDTO.getFlickerData();
|
||||
if (ObjectUtil.isNotNull(flickerData)) {
|
||||
flickerDataDTO.setWaveFluType(flickerData.getWaveFluType());
|
||||
flickerDataDTO.setWaveType(flickerData.getWaveType());
|
||||
flickerDataDTO.setFDutyCycle(flickerData.getFDutyCycle());
|
||||
} else {
|
||||
flickerDataDTO.setWaveFluType(waveFluType);
|
||||
flickerDataDTO.setWaveType(waveType);
|
||||
flickerDataDTO.setFDutyCycle(fDutyCycle);
|
||||
}
|
||||
|
||||
flickerDataDTO.setFChagFre(0.0);
|
||||
flickerDataDTO.setFChagValue(0.0);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.njcn.gather.plan.pojo.vo;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PlanStatisticsVOTest {
|
||||
|
||||
@Test
|
||||
public void shouldExposeQualifiedDeviceCount() {
|
||||
PlanStatisticsVO statistics = new PlanStatisticsVO();
|
||||
|
||||
statistics.setQualifiedDeviceCount(6);
|
||||
|
||||
Assert.assertEquals(Integer.valueOf(6), statistics.getQualifiedDeviceCount());
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
server:
|
||||
port: 18092
|
||||
port: 18093
|
||||
spring:
|
||||
application:
|
||||
name: entrance
|
||||
datasource:
|
||||
druid:
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
# url: jdbc:mysql://192.168.1.24:13306/pqs91002?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
|
||||
# username: root
|
||||
# password: njcnpqs
|
||||
url: jdbc:mysql://192.168.1.24:13306/pqs9100_hn?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
|
||||
url: jdbc:mysql://192.168.1.24:13306/pqs9100?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
|
||||
# username: root
|
||||
# password: njcnpqs
|
||||
# url: jdbc:mysql://127.0.0.1:3306/pqs9100?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
|
||||
username: root
|
||||
password: njcnpqs
|
||||
#初始化建立物理连接的个数、最小、最大连接数
|
||||
@@ -46,15 +46,12 @@ mybatis-plus:
|
||||
|
||||
|
||||
socket:
|
||||
source:
|
||||
ip: 127.0.0.1
|
||||
port: 62000
|
||||
device:
|
||||
ip: 127.0.0.1
|
||||
port: 61000
|
||||
source:
|
||||
ip: 127.0.0.1
|
||||
port: 63000
|
||||
freqConverter:
|
||||
ip: 127.0.0.1
|
||||
port: 63000
|
||||
# source:
|
||||
# ip: 192.168.1.121
|
||||
# port: 10086
|
||||
@@ -67,30 +64,32 @@ webSocket:
|
||||
|
||||
#源参数下发,暂态数据默认值
|
||||
Dip:
|
||||
#暂态前时间(s)
|
||||
fPreTime: 2f
|
||||
# 暂态前时间(s)
|
||||
# fPreTime: 2f
|
||||
#写入时间(s)
|
||||
fRampIn: 0.001f
|
||||
#写出时间(s)
|
||||
fRampOut: 0.001f
|
||||
#暂态后时间(s)
|
||||
fAfterTime: 3f
|
||||
# 暂态后时间(s)
|
||||
# fAfterTime: 3f
|
||||
|
||||
|
||||
Flicker:
|
||||
waveFluType: CPM
|
||||
waveType: SQU
|
||||
fDutyCycle: 50f
|
||||
#Flicker:
|
||||
# waveFluType: CPM
|
||||
# waveType: SQU
|
||||
# fDutyCycle: 50f
|
||||
|
||||
log:
|
||||
homeDir: D:\logs
|
||||
commonLevel: info
|
||||
#log:
|
||||
# homeDir: D:\logs
|
||||
# commonLevel: info
|
||||
report:
|
||||
template: D:\template
|
||||
reportDir: D:\report
|
||||
# template: D:\template
|
||||
# reportDir: D:\report
|
||||
dateFormat: yyyy年MM月dd日
|
||||
data:
|
||||
homeDir: D:\data
|
||||
#data:
|
||||
# homeDir: D:\data
|
||||
#resource:
|
||||
# videoDir: ${data.homeDir}\resources\videos
|
||||
qr:
|
||||
cloud: http://pqmcc.com:18082/api/file
|
||||
dev:
|
||||
@@ -126,11 +125,3 @@ power-quality:
|
||||
activate:
|
||||
private-key: "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCcUyYhVqczGxblL+o/xZzF/8nf+LjrfUE/dS1aRHM7uMDD0cgCArhjtfneFePrMxt+Z7W8yNBzSarub8qsfhaVNikV7Es7oaeTygfjQXTi2n4AFkir3fM07J08RpWhl5M8f8uWTCuvFUYAw00gq55typqmnbkmJa2VIUy/iQf+cMCP7abz4/jNhUzUR3qA7TV4oMRgTdIEDUp63YF8dOC+JH8XxYrCVeHXV6fLCwmesdMzl0lB2VTEKMfLbXhOmF5g7P9y/16VCcN8UBuZlbyYfn+GAxJOSbeHi5HshOKfoSuD7Jz+3WQZpNavOWjIFExKIU38/CvnJCOP7XBCqpSTAgMBAAECggEAYeWokWRE3TpvwiOZnUpR/aVMdVi75a3ROL5XIpqPV61B+t/bU3cEpl0GF9C5pUeiRi0IoStZb3mI9D1KPW/REKyUWkhabQO1gFYbTnRlkNOn6MILzKX4cwJjDaZeeo4EBPU7N+qHyOOXrU6hdH5FfxhMdV983ajm5eeuupxER1C2kAcIklTeVpTX6EKOgZb5LBp5ssOVm2P42pOauvcRozRcvZmqnErXmukv0H4l3EVNt4rHpTn9riHUC63e8JfiYzVaF6zuNUxv6nHEft0/SRMw11XSTnNfDzcKqgjz6ksFBS/6eQQYKESk+ONC53HUuYHFAknkwsPupDCT2W8FIQKBgQDLHT/xCU3nxGr4vFKBDNaO2D5oK20ECbBO4oDvLWWmQG7f+6TsMy8PgVdMnoL4RfqGlwFAKEpS6KVFHnBVqnNEhcdy9uCI7x7Xx8UnyUtxj1EDTm76uta9Ki9OrlqB6tImDM9+Ya3vGktW37ht4WOx2OsJRhG1dbf6RLwFlH7DWwKBgQDFBxvi5I1BR6hg6Tj7xd2SqOT2Y+BED3xuSYENhWbmMhLJDResaB7mjztbxlYaY2mOE0holWm2uDmVFFhMh4jYXik4hYH8nmDzq9mDpZCZ9pyjYqnAP8THoAa8EbgrUWB8A6BPH4iL3KbMnBfBKY0pIr2xrvnjQjNBAgta7KDRKQKBgCe6oe4wxrdF2TKsC2tIqpMoQxS3Icy/ZGgZr+SYuaBKTCWtoDW/UT40K3JGMxIDBhzbXphBCUCsVt9tM8Xd4EwP6tJW7dZ7B0pnve2pVwNwaAVAiz6p2yUHIle+jN+Koe5lZRSwYIg7WW81tWpwwsJfzqFyvjYDP6hJV4mz4ROvAoGAaRcdnKvjXApomShMqJ4lTPChD3q+SA8qg3jZSOj6tZXHx00gb2kp8jg7pPvpOTIFPy6x1Ha9aCRjMk0ju84fA6lVuzwa1S907wOehUVuF3Eeo1cgy9Y3k3KbpPyeixxgpkUY4JslLdSHc2NemD0dee951qhJyRmqVOZOQDUuoeECgYEAqBw2cAFk3vM97WY06TSldGA8ajVHx3BYRjj+zl62NTQthy8fw3tqxb3c5e8toOmZWKjZvDhg2TRLhsDDQWEYg3LZG87REqVIjgEPcpjNLidjygGX8n3JF2o0O5I/EMvl0s/+LVQONfduOBvhwDqr8QNisbLsyneiAq7umewMolo="
|
||||
public-key: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnFMmIVanMxsW5S/qP8Wcxf/J3/i4631BP3UtWkRzO7jAw9HIAgK4Y7X53hXj6zMbfme1vMjQc0mq7m/KrH4WlTYpFexLO6Gnk8oH40F04tp+ABZIq93zNOydPEaVoZeTPH/LlkwrrxVGAMNNIKuebcqapp25JiWtlSFMv4kH/nDAj+2m8+P4zYVM1Ed6gO01eKDEYE3SBA1Ket2BfHTgviR/F8WKwlXh11enywsJnrHTM5dJQdlUxCjHy214TpheYOz/cv9elQnDfFAbmZW8mH5/hgMSTkm3h4uR7ITin6Erg+yc/t1kGaTWrzloyBRMSiFN/Pwr5yQjj+1wQqqUkwIDAQAB"
|
||||
|
||||
freq-converter:
|
||||
schedule-period: 200 #定时器运行间隔
|
||||
tolerant: 1 #耐受状态
|
||||
dt: 200 #延迟时间ms
|
||||
direction: 0 #0为横向1为纵向
|
||||
allow-error-duration: 6 #暂态持续时间允许最大误差ms
|
||||
allow-error-residual-voltage: 2.0 #暂态幅值允许最多误差%
|
||||
|
||||
@@ -12,6 +12,4 @@ public interface TableGenMapper {
|
||||
|
||||
|
||||
void genNonHarmonicResultTable(@Param("code") String code, @Param("isContrast") boolean isContrast);
|
||||
|
||||
void genTable(@Param("tableSql") String tableSql);
|
||||
}
|
||||
|
||||
@@ -72,10 +72,6 @@
|
||||
) COMMENT='非谐波类检测结果表';
|
||||
</update>
|
||||
|
||||
<update id="genTable" parameterType="string">
|
||||
${tableSql}
|
||||
</update>
|
||||
|
||||
|
||||
</mapper>
|
||||
|
||||
|
||||
@@ -325,7 +325,7 @@ public class DetectionDataServiceImpl extends ReplenishMybatisServiceImpl<Detect
|
||||
resultFlags = resultFlags.stream().filter(x -> 4 != x && 5 != x).distinct().collect(Collectors.toList());
|
||||
if (CollUtil.isNotEmpty(resultFlags)) {
|
||||
if (resultFlags.contains(2)) {
|
||||
return 2;
|
||||
return 0;
|
||||
} else {
|
||||
switch (resultFlags.get(0)) {
|
||||
case 1:
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.njcn.gather.system.config;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2026-05-28
|
||||
*/
|
||||
@Component
|
||||
public class PathConfig {
|
||||
|
||||
private String appPath;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
// 获取程序运行目录
|
||||
appPath = System.getProperty("user.dir");
|
||||
|
||||
// 或者获取jar包所在目录
|
||||
// appPath = new File(getClass().getProtectionDomain()
|
||||
// .getCodeSource().getLocation().getPath()).getParent();
|
||||
}
|
||||
|
||||
public String getAppPath() {
|
||||
return appPath;
|
||||
}
|
||||
|
||||
public String getLogPath() {
|
||||
return appPath + File.separator + "logs";
|
||||
}
|
||||
|
||||
public String getDataPath() {
|
||||
return appPath + File.separator + "data";
|
||||
}
|
||||
|
||||
public String getReportTemplatePath() {
|
||||
return this.getDataPath() + File.separator + "template";
|
||||
}
|
||||
|
||||
public String getReportPath() {
|
||||
return this.getDataPath() + File.separator + "report";
|
||||
}
|
||||
|
||||
public String getResourcePath() {
|
||||
return this.getDataPath() + File.separator + "resource";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.njcn.gather.system.resource.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||
import com.njcn.common.pojo.constant.OperateType;
|
||||
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.LogUtil;
|
||||
import com.njcn.gather.system.resource.pojo.param.ResourceManageParam;
|
||||
import com.njcn.gather.system.resource.pojo.vo.PlayVO;
|
||||
import com.njcn.gather.system.resource.pojo.vo.ResourceManageVO;
|
||||
import com.njcn.gather.system.resource.service.IResourceManageService;
|
||||
import com.njcn.web.controller.BaseController;
|
||||
import com.njcn.web.utils.HttpResultUtil;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* 资源管理
|
||||
*/
|
||||
@Slf4j
|
||||
@Api(tags = "资源管理")
|
||||
@RestController
|
||||
@RequestMapping("/resourceManage")
|
||||
@RequiredArgsConstructor
|
||||
public class ResourceManageController extends BaseController {
|
||||
|
||||
private final IResourceManageService resourceManageService;
|
||||
|
||||
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
||||
@PostMapping("/list")
|
||||
@ApiOperation("分页查询资源列表")
|
||||
@ApiImplicitParam(name = "queryParam", value = "查询参数", required = true)
|
||||
public HttpResult<Page<ResourceManageVO>> list(@RequestBody @Validated ResourceManageParam.QueryParam queryParam) {
|
||||
String methodDescribe = getMethodDescribe("list");
|
||||
LogUtil.njcnDebug(log, "{},查询参数为:{}", methodDescribe, queryParam);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, resourceManageService.list(queryParam), methodDescribe);
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD)
|
||||
@PostMapping("/add")
|
||||
@ApiOperation("新增视频资源")
|
||||
@ApiImplicitParam(name = "resourceManageParam", value = "资源参数", required = true)
|
||||
public HttpResult<Boolean> add(ResourceManageParam resourceManageParam) {
|
||||
String methodDescribe = getMethodDescribe("add");
|
||||
LogUtil.njcnDebug(log, "{},新增资源参数为:{}", methodDescribe, resourceManageParam);
|
||||
boolean result = resourceManageService.add(resourceManageParam);
|
||||
if (result) {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
|
||||
}
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE)
|
||||
@PostMapping("/update")
|
||||
@ApiOperation("编辑资源信息")
|
||||
@ApiImplicitParam(name = "updateParam", value = "资源参数", required = true)
|
||||
public HttpResult<Boolean> update(@RequestBody @Validated ResourceManageParam.UpdateParam updateParam) {
|
||||
String methodDescribe = getMethodDescribe("update");
|
||||
LogUtil.njcnDebug(log, "{},编辑资源参数为:{}", methodDescribe, updateParam);
|
||||
boolean result = resourceManageService.update(updateParam);
|
||||
if (result) {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
|
||||
}
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
||||
@GetMapping("/play")
|
||||
@ApiOperation("获取视频播放地址")
|
||||
@ApiImplicitParam(name = "id", value = "资源id", required = true)
|
||||
public HttpResult<PlayVO> play(@RequestParam("id") String id) {
|
||||
String methodDescribe = getMethodDescribe("play");
|
||||
LogUtil.njcnDebug(log, "{},资源id为:{}", methodDescribe, id);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, resourceManageService.play(id), methodDescribe);
|
||||
}
|
||||
|
||||
@GetMapping("/stream")
|
||||
@ApiOperation("播放视频流")
|
||||
public void stream(@RequestParam("id") String id,
|
||||
@RequestParam("token") String token,
|
||||
@RequestHeader(value = "Range", required = false) String rangeHeader,
|
||||
HttpServletResponse response) {
|
||||
resourceManageService.stream(id, token, rangeHeader, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.njcn.gather.system.resource.mapper;
|
||||
|
||||
import com.github.yulichang.base.MPJBaseMapper;
|
||||
import com.njcn.gather.system.resource.pojo.po.ResourceManage;
|
||||
|
||||
/**
|
||||
* 资源管理 mapper
|
||||
*/
|
||||
public interface ResourceManageMapper extends MPJBaseMapper<ResourceManage> {
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?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.gather.system.resource.mapper.ResourceManageMapper">
|
||||
</mapper>
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.njcn.gather.system.resource.pojo.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 资源管理业务响应
|
||||
*/
|
||||
@Getter
|
||||
public enum ResourceManageResponseEnum {
|
||||
|
||||
NAME_NOT_BLANK("A013001", "资源名称不能为空"),
|
||||
REMARK_NOT_BLANK("A013002", "备注不能为空"),
|
||||
FILE_NOT_NULL("A013003", "上传的视频文件不能为空"),
|
||||
FILE_SUFFIX_ERROR("A013004", "仅支持上传 MP4 文件"),
|
||||
FILE_SIZE_ERROR("A013005", "文件大小不能超过 250MB"),
|
||||
FILE_UPLOAD_FAILED("A013006", "文件上传失败"),
|
||||
RESOURCE_NOT_EXIST("A013007", "资源不存在"),
|
||||
RESOURCE_FILE_NOT_EXIST("A013008", "资源文件不存在"),
|
||||
PLAY_TOKEN_INVALID("A013009", "播放授权无效"),
|
||||
PLAY_TOKEN_EXPIRED("A013010", "播放授权已过期"),
|
||||
RANGE_INVALID("A013011", "视频请求范围非法"),
|
||||
DISK_SPACE_NOT_ENOUGH("A013012", "磁盘空间不足"),
|
||||
ID_NOT_BLANK("A013013", "资源id不能为空");
|
||||
|
||||
private final String code;
|
||||
private final String message;
|
||||
|
||||
ResourceManageResponseEnum(String code, String message) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.njcn.gather.system.resource.pojo.param;
|
||||
|
||||
import com.njcn.web.pojo.param.BaseParam;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* 资源管理参数
|
||||
*/
|
||||
@Data
|
||||
public class ResourceManageParam {
|
||||
|
||||
@ApiModelProperty(value = "资源名称", required = true)
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "备注", required = true)
|
||||
private String remark;
|
||||
|
||||
@ApiModelProperty(value = "视频文件", required = true)
|
||||
private MultipartFile file;
|
||||
|
||||
@Data
|
||||
public static class UpdateParam {
|
||||
@ApiModelProperty(value = "资源id", required = true)
|
||||
private String id;
|
||||
|
||||
@ApiModelProperty(value = "资源名称", required = true)
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "备注", required = true)
|
||||
private String remark;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class QueryParam extends BaseParam {
|
||||
@ApiModelProperty("资源名称")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty("原始文件名")
|
||||
private String fileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.njcn.gather.system.resource.pojo.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.njcn.db.mybatisplus.bo.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 资源管理
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("sys_resource_manage")
|
||||
public class ResourceManage extends BaseEntity implements Serializable {
|
||||
private static final long serialVersionUID = 684206384930125506L;
|
||||
|
||||
private String id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String fileName;
|
||||
|
||||
private Long fileSize;
|
||||
|
||||
private String relativePath;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Integer state;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.njcn.gather.system.resource.pojo.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 播放授权信息
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PlayVO {
|
||||
private String url;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.njcn.gather.system.resource.pojo.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 资源管理列表数据
|
||||
*/
|
||||
@Data
|
||||
public class ResourceManageVO {
|
||||
private String id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String fileName;
|
||||
|
||||
private Long fileSize;
|
||||
|
||||
private String relativePath;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Integer state;
|
||||
|
||||
private String createBy;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private String updateBy;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.njcn.gather.system.resource.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.njcn.gather.system.resource.pojo.param.ResourceManageParam;
|
||||
import com.njcn.gather.system.resource.pojo.po.ResourceManage;
|
||||
import com.njcn.gather.system.resource.pojo.vo.PlayVO;
|
||||
import com.njcn.gather.system.resource.pojo.vo.ResourceManageVO;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* 资源管理服务
|
||||
*/
|
||||
public interface IResourceManageService extends IService<ResourceManage> {
|
||||
|
||||
Page<ResourceManageVO> list(ResourceManageParam.QueryParam queryParam);
|
||||
|
||||
boolean add(ResourceManageParam resourceManageParam);
|
||||
|
||||
boolean update(ResourceManageParam.UpdateParam updateParam);
|
||||
|
||||
PlayVO play(String id);
|
||||
|
||||
void stream(String id, String token, String rangeHeader, HttpServletResponse response);
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
package com.njcn.gather.system.resource.service.impl;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
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.common.pojo.enums.common.DataStateEnum;
|
||||
import com.njcn.common.pojo.exception.BusinessException;
|
||||
import com.njcn.gather.system.config.PathConfig;
|
||||
import com.njcn.gather.system.resource.mapper.ResourceManageMapper;
|
||||
import com.njcn.gather.system.resource.pojo.enums.ResourceManageResponseEnum;
|
||||
import com.njcn.gather.system.resource.pojo.param.ResourceManageParam;
|
||||
import com.njcn.gather.system.resource.pojo.po.ResourceManage;
|
||||
import com.njcn.gather.system.resource.pojo.vo.PlayVO;
|
||||
import com.njcn.gather.system.resource.pojo.vo.ResourceManageVO;
|
||||
import com.njcn.gather.system.resource.service.IResourceManageService;
|
||||
import com.njcn.web.factory.PageFactory;
|
||||
import com.njcn.web.utils.RequestUtil;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ResourceManageServiceImpl extends ServiceImpl<ResourceManageMapper, ResourceManage> implements IResourceManageService {
|
||||
|
||||
private static final long MAX_FILE_SIZE = 250L * 1024L * 1024L;
|
||||
private static final long PLAY_TOKEN_TTL_MILLIS = 30L * 60L * 1000L;
|
||||
private static final String MP4_SUFFIX = ".mp4";
|
||||
private static final String RELATIVE_VIDEO_ROOT = "resources/videos";
|
||||
private static final int BUFFER_SIZE = 8192;
|
||||
|
||||
private static final ConcurrentHashMap<String, PlayToken> PLAY_TOKEN_CACHE = new ConcurrentHashMap<>();
|
||||
|
||||
// @Value("${resource.videoDir:D:/data/resources/videos}")
|
||||
// private String videoDir;
|
||||
private final PathConfig pathConfig;
|
||||
|
||||
@Override
|
||||
public Page<ResourceManageVO> list(ResourceManageParam.QueryParam queryParam) {
|
||||
QueryWrapper<ResourceManage> wrapper = new QueryWrapper<>();
|
||||
wrapper.like(StrUtil.isNotBlank(queryParam.getName()), "Name", queryParam.getName())
|
||||
.like(StrUtil.isNotBlank(queryParam.getFileName()), "File_Name", queryParam.getFileName())
|
||||
.eq("State", DataStateEnum.ENABLE.getCode())
|
||||
.orderByDesc("Create_Time");
|
||||
|
||||
Page<ResourceManage> page = this.page(
|
||||
new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)),
|
||||
wrapper
|
||||
);
|
||||
|
||||
List<ResourceManageVO> records = page.getRecords().stream().map(resource -> {
|
||||
ResourceManageVO vo = new ResourceManageVO();
|
||||
BeanUtil.copyProperties(resource, vo);
|
||||
return vo;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
Page<ResourceManageVO> result = new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam));
|
||||
result.setTotal(page.getTotal());
|
||||
result.setPages(page.getPages());
|
||||
result.setCurrent(page.getCurrent());
|
||||
result.setSize(page.getSize());
|
||||
result.setRecords(records);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean add(ResourceManageParam resourceManageParam) {
|
||||
validateAddParam(resourceManageParam);
|
||||
|
||||
MultipartFile file = resourceManageParam.getFile();
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
|
||||
String savedFileName = UUID.randomUUID().toString().replace("-", "") + MP4_SUFFIX;
|
||||
Path rootPath = Paths.get(pathConfig.getResourcePath()).toAbsolutePath().normalize();
|
||||
Path targetDir = rootPath.resolve(dateDir).normalize();
|
||||
Path targetFile = targetDir.resolve(savedFileName).normalize();
|
||||
ensurePathInRoot(rootPath, targetFile);
|
||||
|
||||
String relativePath = RELATIVE_VIDEO_ROOT + "/" + dateDir + "/" + savedFileName;
|
||||
|
||||
try {
|
||||
Files.createDirectories(targetDir);
|
||||
long usableSpace = targetDir.toFile().getUsableSpace();
|
||||
if (usableSpace > 0 && usableSpace < file.getSize()) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.DISK_SPACE_NOT_ENOUGH);
|
||||
}
|
||||
file.transferTo(targetFile.toFile());
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.FILE_UPLOAD_FAILED);
|
||||
}
|
||||
|
||||
ResourceManage resourceManage = new ResourceManage();
|
||||
resourceManage.setId(UUID.randomUUID().toString().replace("-", ""));
|
||||
resourceManage.setName(resourceManageParam.getName().trim());
|
||||
resourceManage.setRemark(resourceManageParam.getRemark().trim());
|
||||
resourceManage.setFileName(originalFilename);
|
||||
resourceManage.setFileSize(file.getSize());
|
||||
resourceManage.setRelativePath(relativePath);
|
||||
resourceManage.setState(DataStateEnum.ENABLE.getCode());
|
||||
|
||||
try {
|
||||
boolean saved = this.save(resourceManage);
|
||||
if (!saved) {
|
||||
deleteQuietly(targetFile);
|
||||
}
|
||||
return saved;
|
||||
} catch (RuntimeException e) {
|
||||
deleteQuietly(targetFile);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean update(ResourceManageParam.UpdateParam updateParam) {
|
||||
validateUpdateParam(updateParam);
|
||||
getEnabledResource(updateParam.getId());
|
||||
return this.lambdaUpdate()
|
||||
.set(ResourceManage::getName, updateParam.getName().trim())
|
||||
.set(ResourceManage::getRemark, updateParam.getRemark().trim())
|
||||
.eq(ResourceManage::getId, updateParam.getId())
|
||||
.eq(ResourceManage::getState, DataStateEnum.ENABLE.getCode())
|
||||
.update();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayVO play(String id) {
|
||||
ResourceManage resourceManage = getEnabledResource(id);
|
||||
Path filePath = resolveResourcePath(resourceManage);
|
||||
if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.RESOURCE_FILE_NOT_EXIST);
|
||||
}
|
||||
|
||||
String token = UUID.randomUUID().toString().replace("-", "");
|
||||
PlayToken playToken = new PlayToken();
|
||||
playToken.setResourceId(id);
|
||||
playToken.setUserId(RequestUtil.getUserId());
|
||||
playToken.setExpireTime(System.currentTimeMillis() + PLAY_TOKEN_TTL_MILLIS);
|
||||
PLAY_TOKEN_CACHE.put(token, playToken);
|
||||
clearExpiredTokens();
|
||||
|
||||
return new PlayVO("/resourceManage/stream?id=" + id + "&token=" + token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stream(String id, String token, String rangeHeader, HttpServletResponse response) {
|
||||
if (!validatePlayToken(id, token)) {
|
||||
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||
return;
|
||||
}
|
||||
|
||||
ResourceManage resourceManage = getEnabledResource(id);
|
||||
Path filePath = resolveResourcePath(resourceManage);
|
||||
if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
|
||||
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
long fileLength = Files.size(filePath);
|
||||
Range range = parseRange(rangeHeader, fileLength);
|
||||
String encodedFileName = URLEncoder.encode(resourceManage.getFileName(), "UTF-8")
|
||||
.replaceAll("\\+", "%20");
|
||||
|
||||
response.setContentType("video/mp4");
|
||||
response.setHeader("Accept-Ranges", "bytes");
|
||||
response.setHeader("Content-Disposition", "inline; filename*=UTF-8''" + encodedFileName);
|
||||
response.setHeader("Content-Length", String.valueOf(range.getLength()));
|
||||
if (range.isPartial()) {
|
||||
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
response.setHeader("Content-Range", "bytes " + range.getStart() + "-" + range.getEnd() + "/" + fileLength);
|
||||
} else {
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
}
|
||||
|
||||
writeRange(filePath, range, response);
|
||||
} catch (IllegalArgumentException e) {
|
||||
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
} catch (IOException e) {
|
||||
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateAddParam(ResourceManageParam param) {
|
||||
if (param == null || StrUtil.isBlank(param.getName())) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.NAME_NOT_BLANK);
|
||||
}
|
||||
if (StrUtil.isBlank(param.getRemark())) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.REMARK_NOT_BLANK);
|
||||
}
|
||||
MultipartFile file = param.getFile();
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.FILE_NOT_NULL);
|
||||
}
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
if (StrUtil.isBlank(originalFilename) || !originalFilename.toLowerCase().endsWith(MP4_SUFFIX)) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.FILE_SUFFIX_ERROR);
|
||||
}
|
||||
String contentType = file.getContentType();
|
||||
if (StrUtil.isNotBlank(contentType) && !"video/mp4".equalsIgnoreCase(contentType)
|
||||
&& !"application/octet-stream".equalsIgnoreCase(contentType)) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.FILE_SUFFIX_ERROR);
|
||||
}
|
||||
if (file.getSize() > MAX_FILE_SIZE) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.FILE_SIZE_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateUpdateParam(ResourceManageParam.UpdateParam param) {
|
||||
if (param == null || StrUtil.isBlank(param.getId())) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.ID_NOT_BLANK);
|
||||
}
|
||||
if (StrUtil.isBlank(param.getName())) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.NAME_NOT_BLANK);
|
||||
}
|
||||
if (StrUtil.isBlank(param.getRemark())) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.REMARK_NOT_BLANK);
|
||||
}
|
||||
}
|
||||
|
||||
private ResourceManage getEnabledResource(String id) {
|
||||
ResourceManage resourceManage = this.lambdaQuery()
|
||||
.eq(ResourceManage::getId, id)
|
||||
.eq(ResourceManage::getState, DataStateEnum.ENABLE.getCode())
|
||||
.one();
|
||||
if (resourceManage == null) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.RESOURCE_NOT_EXIST);
|
||||
}
|
||||
return resourceManage;
|
||||
}
|
||||
|
||||
private Path resolveResourcePath(ResourceManage resourceManage) {
|
||||
Path rootPath = Paths.get(pathConfig.getResourcePath()).toAbsolutePath().normalize();
|
||||
String relativePath = resourceManage.getRelativePath().replace("\\", "/");
|
||||
String prefix = RELATIVE_VIDEO_ROOT + "/";
|
||||
if (!relativePath.startsWith(prefix)) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.RESOURCE_FILE_NOT_EXIST);
|
||||
}
|
||||
String relativeToVideoRoot = relativePath.substring(prefix.length());
|
||||
Path filePath = rootPath.resolve(relativeToVideoRoot).normalize();
|
||||
ensurePathInRoot(rootPath, filePath);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private void ensurePathInRoot(Path rootPath, Path targetPath) {
|
||||
if (!targetPath.startsWith(rootPath)) {
|
||||
throw new BusinessException(ResourceManageResponseEnum.RESOURCE_FILE_NOT_EXIST);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean validatePlayToken(String id, String token) {
|
||||
if (StrUtil.isBlank(id) || StrUtil.isBlank(token)) {
|
||||
return false;
|
||||
}
|
||||
PlayToken playToken = PLAY_TOKEN_CACHE.get(token);
|
||||
if (playToken == null || !id.equals(playToken.getResourceId())) {
|
||||
return false;
|
||||
}
|
||||
if (playToken.getExpireTime() < System.currentTimeMillis()) {
|
||||
PLAY_TOKEN_CACHE.remove(token);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void clearExpiredTokens() {
|
||||
long now = System.currentTimeMillis();
|
||||
PLAY_TOKEN_CACHE.entrySet().removeIf(entry -> entry.getValue().getExpireTime() < now);
|
||||
}
|
||||
|
||||
private Range parseRange(String rangeHeader, long fileLength) {
|
||||
if (StrUtil.isBlank(rangeHeader)) {
|
||||
return new Range(0, fileLength - 1, false);
|
||||
}
|
||||
if (!rangeHeader.startsWith("bytes=")) {
|
||||
throw new IllegalArgumentException("Invalid range");
|
||||
}
|
||||
String rangeValue = rangeHeader.substring("bytes=".length());
|
||||
String[] parts = rangeValue.split("-", -1);
|
||||
if (parts.length != 2) {
|
||||
throw new IllegalArgumentException("Invalid range");
|
||||
}
|
||||
|
||||
long start;
|
||||
long end;
|
||||
if (StrUtil.isBlank(parts[0])) {
|
||||
long suffixLength = Long.parseLong(parts[1]);
|
||||
if (suffixLength <= 0) {
|
||||
throw new IllegalArgumentException("Invalid range");
|
||||
}
|
||||
start = Math.max(fileLength - suffixLength, 0);
|
||||
end = fileLength - 1;
|
||||
} else {
|
||||
start = Long.parseLong(parts[0]);
|
||||
end = StrUtil.isBlank(parts[1]) ? fileLength - 1 : Long.parseLong(parts[1]);
|
||||
}
|
||||
|
||||
if (start < 0 || end < start || start >= fileLength) {
|
||||
throw new IllegalArgumentException("Invalid range");
|
||||
}
|
||||
end = Math.min(end, fileLength - 1);
|
||||
return new Range(start, end, true);
|
||||
}
|
||||
|
||||
private void writeRange(Path filePath, Range range, HttpServletResponse response) throws IOException {
|
||||
try (InputStream inputStream = Files.newInputStream(filePath);
|
||||
ServletOutputStream outputStream = response.getOutputStream()) {
|
||||
long skipped = inputStream.skip(range.getStart());
|
||||
while (skipped < range.getStart()) {
|
||||
long current = inputStream.skip(range.getStart() - skipped);
|
||||
if (current <= 0) {
|
||||
break;
|
||||
}
|
||||
skipped += current;
|
||||
}
|
||||
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
long bytesRemaining = range.getLength();
|
||||
while (bytesRemaining > 0) {
|
||||
int readLength = (int) Math.min(buffer.length, bytesRemaining);
|
||||
int read = inputStream.read(buffer, 0, readLength);
|
||||
if (read == -1) {
|
||||
break;
|
||||
}
|
||||
outputStream.write(buffer, 0, read);
|
||||
bytesRemaining -= read;
|
||||
}
|
||||
outputStream.flush();
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteQuietly(Path path) {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException e) {
|
||||
log.warn("删除资源文件失败: {}", path, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class PlayToken {
|
||||
private String resourceId;
|
||||
private String userId;
|
||||
private long expireTime;
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class Range {
|
||||
private final long start;
|
||||
private final long end;
|
||||
private final boolean partial;
|
||||
|
||||
private long getLength() {
|
||||
return end - start + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -14,10 +14,17 @@ public interface IWordReportService {
|
||||
|
||||
/**
|
||||
* 替换Word文档中的占位符
|
||||
*
|
||||
*
|
||||
* @param templateInputStream 模板文档输入流
|
||||
* @param placeholderMap 占位符替换映射表,key为占位符标识,value为替换值
|
||||
* @return 处理后的文档输入流,调用方可根据需要进行下载、上传等操作
|
||||
* @return 处理后的文档输入流,调用方可根据需要进行下载、上传等操作。
|
||||
* <p>
|
||||
* <b>资源管理契约:</b>当前实现返回 {@link java.io.ByteArrayInputStream},
|
||||
* 其 {@code close()} 为空操作、内部仅持有 byte 数组、不占用文件句柄等 native 资源,
|
||||
* 调用方<strong>不强制</strong>用 try-with-resources 包裹该返回流;
|
||||
* 若未来该方法的实现改为返回底层依赖文件 / 网络 / 临时文件的真实流,
|
||||
* 必须先改造所有调用方按 try-with-resources 关流后再合并实现,
|
||||
* 以避免句柄泄漏。
|
||||
* @throws Exception 处理异常
|
||||
*/
|
||||
InputStream replacePlaceholders(InputStream templateInputStream, Map<String, String> placeholderMap) throws Exception;
|
||||
|
||||
@@ -40,6 +40,10 @@ public class WordReportServiceImpl implements IWordReportService {
|
||||
PlaceholderUtil.replaceAllPlaceholders(mainDocumentPart, placeholderMap);
|
||||
|
||||
// 将处理后的文档转换为字节数组输入流
|
||||
// 注:返回类型必须是 ByteArrayInputStream 或 close() 为空操作的等价流,
|
||||
// 以满足 IWordReportService.replacePlaceholders 接口契约
|
||||
// (多个调用方未对返回流做 try-with-resources 兜底)。
|
||||
// 若需改为依赖文件 / 网络 / 临时文件的真实流,必须先改造所有调用方再合并。
|
||||
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
|
||||
wordPackage.save(outputStream);
|
||||
byte[] documentBytes = outputStream.toByteArray();
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.njcn.gather.tools.report.util;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
|
||||
/**
|
||||
* 文件路径片段净化工具。
|
||||
* <p>
|
||||
* 用于把外部输入(数据库中的设备型号名、计划名等)作为目录或文件名片段拼入磁盘路径前的兜底清洗,
|
||||
* 防止 {@code /} {@code \} {@code ..} {@code :} 等路径敏感字符导致:
|
||||
* <ul>
|
||||
* <li>报告文件被写到预期目录之外(路径穿越)</li>
|
||||
* <li>名字含 {@code /} 时被操作系统解释成多级子目录(即使无恶意,自然命名如"高/中压"也会触发)</li>
|
||||
* <li>Windows 上 {@code :} 触发 NTFS 备用数据流</li>
|
||||
* <li>文件创建失败抛 IO 异常</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author hongawen
|
||||
*/
|
||||
public final class FilePathSanitizer {
|
||||
|
||||
/**
|
||||
* Windows + Linux 共同非法字符 + 控制字符:替换为下划线
|
||||
*/
|
||||
private static final String UNSAFE_CHAR_PATTERN = "[\\\\/:*?\"<>|\\x00-\\x1F]";
|
||||
|
||||
private FilePathSanitizer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一段字符串净化成可安全拼入磁盘路径的片段。
|
||||
* <p>
|
||||
* 规则:
|
||||
* <ol>
|
||||
* <li>{@code null} 或全空白 → 返回 {@code "_"}(保证拼出来的路径仍合法)</li>
|
||||
* <li>{@code /} {@code \} {@code :} {@code *} {@code ?} {@code "} {@code <} {@code >} {@code |}
|
||||
* 及 ASCII 控制字符替换为 {@code _}</li>
|
||||
* <li>把 {@code ..} 折叠为 {@code _},防止路径穿越</li>
|
||||
* <li>连续 {@code _} 合并为单个 {@code _}</li>
|
||||
* <li>首尾空白与 {@code .} 去掉(Windows 不允许文件名以 {@code .} 结尾)</li>
|
||||
* </ol>
|
||||
*
|
||||
* @param raw 原始字符串
|
||||
* @return 净化后的片段;当输入合法且无危险字符时与原值一致
|
||||
*/
|
||||
public static String toSafeFileName(String raw) {
|
||||
if (StrUtil.isBlank(raw)) {
|
||||
return "_";
|
||||
}
|
||||
String result = raw.replaceAll(UNSAFE_CHAR_PATTERN, "_");
|
||||
// 折叠路径穿越序列
|
||||
while (result.contains("..")) {
|
||||
result = result.replace("..", "_");
|
||||
}
|
||||
// 合并连续下划线
|
||||
result = result.replaceAll("_+", "_");
|
||||
// 去掉首尾空白和点
|
||||
result = result.replaceAll("^[\\s.]+|[\\s.]+$", "");
|
||||
return result.isEmpty() ? "_" : result;
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ import java.util.List;
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AuthGlobalFilter implements Filter, Ordered {
|
||||
private final static List<String> IGNORE_URI = Arrays.asList("/doc.html","/v3/api-docs","/admin/login","/admin/getPublicKey", "/report/generateReport");
|
||||
private final static List<String> IGNORE_URI = Arrays.asList("/doc.html","/v3/api-docs","/admin/login","/admin/getPublicKey", "/report/generateReport", "/resourceManage/stream");
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
|
||||
Reference in New Issue
Block a user