28 Commits

Author SHA1 Message Date
caozehui
391646d416 微调 2026-05-08 13:55:48 +08:00
caozehui
4f3f0833d5 微调 2026-05-08 13:15:28 +08:00
caozehui
924c2e8f45 微调 2026-05-08 10:39:27 +08:00
caozehui
8dca7bf537 微调 2026-05-08 10:37:58 +08:00
caozehui
7e6fb2d981 特性点顺序问题 2026-05-07 19:18:42 +08:00
caozehui
ec9a0ca236 微调 2026-05-07 16:27:49 +08:00
caozehui
7ab5b9a501 横向纵向实时打特性点 2026-05-07 15:21:35 +08:00
caozehui
3959b96040 微调 2026-05-07 10:55:01 +08:00
caozehui
ae5370abdf 微调 2026-05-07 10:49:01 +08:00
caozehui
1894cb07a2 微调 2026-05-07 09:03:34 +08:00
caozehui
08dff063c9 调整脚本换行、特性点入库 2026-05-07 08:52:17 +08:00
caozehui
f640afb4ed 特性点推送 2026-05-06 13:17:12 +08:00
caozehui
503018a721 起点 2026-04-30 09:34:44 +08:00
caozehui
391fd0cf4f 最后状态清空 2026-04-23 15:37:40 +08:00
caozehui
99c7448544 Merge remote-tracking branch 'origin/hainan' into hainan
# Conflicts:
#	detection/src/main/java/com/njcn/gather/detection/util/socket/FormalTestManager.java
2026-04-23 14:08:43 +08:00
caozehui
83296d257c 微调 2026-04-23 13:59:18 +08:00
caozehui
e020aa466e 调整变频器耐受状态字段 2026-04-22 20:39:53 +08:00
caozehui
f20e2c9b32 微调 2026-04-22 09:34:53 +08:00
caozehui
e03c3e3607 状态清空 2026-04-20 09:08:25 +08:00
caozehui
27f25d2404 微调 2026-04-17 08:56:15 +08:00
caozehui
a77313171c 向前端推送暂降点 2026-04-16 15:24:00 +08:00
caozehui
a658d6e81a 向前端推送暂降点 2026-04-16 15:02:53 +08:00
caozehui
ab11c91579 关于时间精度调整 2026-04-16 14:14:38 +08:00
caozehui
a2468f1353 微调 2026-04-16 11:43:41 +08:00
caozehui
d8bcca1ede 微调 2026-04-15 18:52:14 +08:00
caozehui
c5e77ee9b1 耐受结果、变频器重新连接Socket调整 2026-04-15 09:45:53 +08:00
caozehui
2293d81b71 动态创建表结构、入库 2026-04-14 14:51:33 +08:00
caozehui
97157a5ccf 变频器 2026-04-13 16:28:25 +08:00
42 changed files with 2442 additions and 44 deletions

View File

@@ -10,6 +10,7 @@ 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.service.PreDetectionService;
import com.njcn.gather.detection.util.socket.CnSocketUtil;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
@@ -176,4 +177,26 @@ public class PreDetectionController extends BaseController {
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);
}
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
@GetMapping("/stopFreqConverter")
@ApiOperation("关闭变频器测试")
public HttpResult<String> stopFreqConverter(@RequestParam("userId") String userId) {
String methodDescribe = getMethodDescribe("stopFreqConverter");
LogUtil.njcnDebug(log, "{}", methodDescribe);
preDetectionService.stopFreqConverter(userId + CnSocketUtil.FREQ_CONVERTER_TAG, userId + CnSocketUtil.DEV_TAG);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
}

View File

@@ -0,0 +1,369 @@
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();
}
}
}

View File

@@ -0,0 +1,433 @@
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;
}
}

View File

@@ -0,0 +1,41 @@
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;
}

View File

@@ -19,7 +19,8 @@ public enum DetectionResponseEnum {
SCRIPT_CHECK_DATA_NOT_EXIST("A020040","测试脚本项暂无配置" ),
EXCEED_MAX_TIME("A020041","检测次数超出最大限制!" );
EXCEED_MAX_TIME("A020041","检测次数超出最大限制!" ),
SOCKET_CONNECT_TIMEOUT("A020042","socket连接超时");
private final String code;
private final String message;

View File

@@ -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,9 +70,6 @@ public enum SourceOperateCodeEnum {
FLICKER_DATA_CHECK("flicker_data_check","闪变数据校验"),
/**
*
*/
@@ -100,12 +97,17 @@ 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", "启动录波");
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", "关闭串口"),;
private final String value;
private final String msg;

View File

@@ -4,9 +4,6 @@ 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
@@ -55,7 +52,6 @@ public interface PreDetectionService {
void closeTestSimulate(SimulateDetectionParam param);
/**
*
* @param param
*/
void startContrastTest(ContrastDetectionParam param);
@@ -68,4 +64,8 @@ public interface PreDetectionService {
boolean getCanCoefficient();
void startCoefficient();
void startFreqConverter(String userId, String converterId, String monitorId,Boolean reset);
void stopFreqConverter(String converterId, String monitorId);
}

View File

@@ -6,9 +6,7 @@ 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.SocketContrastResponseService;
import com.njcn.gather.detection.handler.SocketDevResponseService;
import com.njcn.gather.detection.handler.SocketSourceResponseService;
import com.njcn.gather.detection.handler.*;
import com.njcn.gather.detection.pojo.constant.DetectionCommunicateConstant;
import com.njcn.gather.detection.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
@@ -76,6 +74,8 @@ 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;
@@ -393,6 +393,38 @@ 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);
}
/**
* 比对式-与通信模块进行连接
*
@@ -451,4 +483,4 @@ public class PreDetectionServiceImpl implements PreDetectionService {
}
}
}
}

View File

@@ -14,6 +14,8 @@ 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";

View File

@@ -7,12 +7,15 @@ 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;
@@ -31,6 +34,20 @@ 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_通道号)
*/
@@ -208,4 +225,27 @@ 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;
}
}
}

View File

@@ -315,4 +315,4 @@ public class SocketManager {
}

View File

@@ -56,6 +56,109 @@ 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() {

View File

@@ -0,0 +1,147 @@
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);
}
}

View File

@@ -0,0 +1,63 @@
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);
}
}

View File

@@ -18,29 +18,21 @@ import java.util.Set;
@Component
@ConfigurationProperties(prefix = "socket")
public class SocketConnectionConfig {
/**
* 被检设备配置
*/
private DeviceConfig device = new DeviceConfig();
/**
* 程控源设备配置
*/
private SourceConfig source = new SourceConfig();
/**
* 被检设备配置
*/
private DeviceConfig device = new DeviceConfig();
@Data
public static class SourceConfig {
/**
* 程控源IP地址
*/
private String ip;
/**
* 程控源端口号
*/
private Integer port;
}
/**
* 变频器配置
*/
private DeviceConfig freqConverter = new DeviceConfig();
@Data
public static class DeviceConfig {
@@ -48,13 +40,33 @@ public class SocketConnectionConfig {
* 被检设备IP地址
*/
private String ip;
/**
* 被检设备端口号
*/
private Integer port;
}
@Data
public static class SourceConfig {
/**
* 程控源IP地址
*/
private String ip;
/**
* 程控源端口号
*/
private Integer port;
}
/**
* 获取被检设备配置
*/
public DeviceConfig getDevice() {
return device;
}
/**
* 获取程控源配置
*/
@@ -63,10 +75,10 @@ public class SocketConnectionConfig {
}
/**
* 获取被检设备配置
* 获取变频器配置
*/
public DeviceConfig getDevice() {
return device;
public DeviceConfig getFreqConverter() {
return freqConverter;
}
/**

View File

@@ -189,4 +189,14 @@ 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);
}
}

View File

@@ -288,4 +288,6 @@ public interface IPqDevService extends IService<PqDev> {
* @return
*/
List<ContrastDevExcel> getExportContrastDevData(List<PqDevVO> pqDevVOList);
List<PqDevVO> listAll();
}

View File

@@ -1625,4 +1625,31 @@ 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());
}
}

View File

@@ -0,0 +1,11 @@
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> {
}

View File

@@ -0,0 +1,37 @@
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;
}

View File

@@ -0,0 +1,26 @@
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;
}

View File

@@ -0,0 +1,23 @@
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);
}

View File

@@ -0,0 +1,34 @@
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();
}
}

View File

@@ -0,0 +1,21 @@
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;
}

View File

@@ -0,0 +1,116 @@
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);
// }
}

View File

@@ -0,0 +1,11 @@
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> {
}

View File

@@ -0,0 +1,11 @@
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> {
}

View File

@@ -0,0 +1,11 @@
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> {
}

View File

@@ -0,0 +1,66 @@
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;
}
}

View File

@@ -0,0 +1,31 @@
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;
}

View File

@@ -0,0 +1,73 @@
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;
}

View File

@@ -0,0 +1,41 @@
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;
}

View File

@@ -0,0 +1,34 @@
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;
}

View File

@@ -0,0 +1,62 @@
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);
}

View File

@@ -0,0 +1,27 @@
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);
}

View File

@@ -0,0 +1,50 @@
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);
}

View File

@@ -0,0 +1,172 @@
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;
}
}

View File

@@ -0,0 +1,136 @@
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();
}
}

View File

@@ -0,0 +1,81 @@
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;
}
}

View File

@@ -6,10 +6,10 @@ spring:
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://127.0.0.1:3306/pqs9100?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
# 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
username: root
password: njcnpqs
#初始化建立物理连接的个数、最小、最大连接数
@@ -46,12 +46,15 @@ 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
@@ -60,7 +63,7 @@ socket:
# port: 61000
webSocket:
port: 7777
port: 7778
#源参数下发,暂态数据默认值
Dip:
@@ -123,3 +126,11 @@ 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 #暂态幅值允许最多误差%

View File

@@ -12,4 +12,6 @@ public interface TableGenMapper {
void genNonHarmonicResultTable(@Param("code") String code, @Param("isContrast") boolean isContrast);
void genTable(@Param("tableSql") String tableSql);
}

View File

@@ -72,6 +72,10 @@
) COMMENT='非谐波类检测结果表';
</update>
<update id="genTable" parameterType="string">
${tableSql}
</update>
</mapper>