32 Commits

Author SHA1 Message Date
xy
0e7d12ab93 接入冗余处理 2024-10-08 09:55:38 +08:00
xy
531a787c91 1.下载文件优化
2.设备接入调整
2024-09-29 16:08:44 +08:00
xy
45d31a05ee 获取便携式设备基础数据功能 2024-09-25 19:24:21 +08:00
xy
dfd035b908 1.手持式设备注册、接入测试联调;
2.手持式设备树功能重写;
2024-09-24 13:20:29 +08:00
ab59d870d8 调整监测点入库名称 2024-09-24 09:11:56 +08:00
xy
5a94b6d8b4 便携式设备
1.软件信息兼容;
2.监测点信息兼容
2024-09-23 20:33:50 +08:00
xy
cfc2b2b7ba Merge pull request '优化' (#1) from wireless into master
Reviewed-on: system-Backend/iot#1
2024-09-20 13:19:39 +08:00
xy
eec42f60c0 优化 2024-09-20 13:18:43 +08:00
xy
1d71006d3c 优化 2024-09-20 13:17:35 +08:00
xy
1dc16ae071 优化 2024-09-20 13:17:03 +08:00
xy
ef2ce8367d 优化 2024-09-20 11:46:40 +08:00
xy
b59c85e791 1.移植程序软件接口;
2.返回文件上传、下载进度信息
2024-09-19 14:26:29 +08:00
xy
32520907d2 下载优化 2024-09-18 20:50:33 +08:00
xy
06c8ce2e29 下载优化 2024-09-18 20:07:29 +08:00
xy
0fed84b8e0 微调 2024-09-17 11:11:17 +08:00
xy
c58f45019a 微调 2024-09-17 09:39:37 +08:00
xy
2d5feb1ef2 录波文件冗余处理 2024-09-17 09:00:10 +08:00
xy
ff188c3928 bug调整 2024-09-14 17:36:16 +08:00
xy
d5ad4a81c8 异常事件展示 2024-09-14 16:02:08 +08:00
xy
b2da20cf62 微调 2024-09-14 13:39:41 +08:00
xy
848cc9c7de 录波文件下载优化 2024-09-14 11:44:38 +08:00
dc7afcc240 Merge remote-tracking branch 'origin/master' 2024-09-13 21:27:12 +08:00
421312d4c4 优化处理,避免重复异常消息入库 2024-09-13 21:27:02 +08:00
xy
335997cdf6 1.录波文件下载处理;
2.装置异常告警事件处理
2024-09-13 20:41:18 +08:00
bb298501eb 删除报错 2024-09-12 15:04:48 +08:00
xy
9509a59f16 装置文件夹新建、删除 2024-09-11 20:41:48 +08:00
xy
b79e612595 代码注释 2024-09-11 12:55:53 +08:00
xy
b55fa84c17 设备离线判断调整 2024-09-11 12:45:06 +08:00
xy
107c6d2637 代码注释 2024-09-11 12:34:27 +08:00
xy
72e81b1b6d 文件上传下载功能 2024-09-11 11:37:58 +08:00
xy
9dab90ab88 消息推送调整 2024-09-05 17:52:54 +08:00
xy
14d79d4fe8 消息推送调整 2024-09-05 15:34:19 +08:00
74 changed files with 2791 additions and 821 deletions

View File

@@ -0,0 +1,34 @@
package com.njcn.access.api;
import com.njcn.access.api.fallback.AskDeviceDataClientFallbackFactory;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.ACCESS_BOOT, path = "/askDeviceData", fallbackFactory = AskDeviceDataClientFallbackFactory.class,contextId = "askDeviceData")
public interface AskDeviceDataFeignClient {
@PostMapping("/askDeviceRootPath")
HttpResult<String> askDeviceRootPath(@RequestParam("nDid") String nDid);
@PostMapping("/askDeviceFileOrDir")
HttpResult<String> askDeviceFileOrDir(@RequestParam("nDid") String nDid, @RequestParam("name") String name);
@PostMapping("/downloadFile")
HttpResult<Boolean> downloadFile(@RequestParam("nDid") String nDid, @RequestParam("name") String name, @RequestParam("size") Integer size, @RequestParam("fileCheck") String fileCheck);
@PostMapping("/rebootDevice")
HttpResult<String> rebootDevice(@RequestParam("nDid") String nDid);
@PostMapping("/createFolder")
HttpResult<String> createFolder(@RequestParam("nDid") String nDid, @RequestParam("path") String path);
@PostMapping("/deleteFolder")
HttpResult<String> deleteFolder(@RequestParam("nDid") String nDid, @RequestParam("path") String path);
}

View File

@@ -0,0 +1,72 @@
package com.njcn.access.api.fallback;
import com.njcn.access.api.AskDeviceDataFeignClient;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.redis.utils.RedisUtil;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author xy
*/
@Slf4j
@Component
public class AskDeviceDataClientFallbackFactory implements FallbackFactory<AskDeviceDataFeignClient> {
@Resource
private RedisUtil redisUtil;
@Override
public AskDeviceDataFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new AskDeviceDataFeignClient() {
@Override
public HttpResult<String> askDeviceRootPath(String nDid) {
log.error("{}异常,降级处理,异常为:{}","平台询问装置报文",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<String> askDeviceFileOrDir(String nDid, String name) {
log.error("{}异常,降级处理,异常为:{}","设备文件/目录信息询问",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<Boolean> downloadFile(String nDid, String name, Integer size, String fileCheck) {
log.error("{}异常,降级处理,异常为:{}","文件下载",cause.toString());
redisUtil.delete("fileDowning:" + nDid);
redisUtil.delete("fileCheck"+name);
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<String> rebootDevice(String nDid) {
log.error("{}异常,降级处理,异常为:{}","设备重启",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<String> createFolder(String nDid, String path) {
log.error("{}异常,降级处理,异常为:{}","创建文件夹",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<String> deleteFolder(String nDid, String path) {
log.error("{}异常,降级处理,异常为:{}","删除文件夹",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -14,10 +14,10 @@ public enum AccessResponseEnum {
* A0301 ~ A0399 用于用户模块的枚举 * A0301 ~ A0399 用于用户模块的枚举
* <p> * <p>
*/ */
NDID_NO_FIND("A0301", "设备未录入!"), NDID_NO_FIND("A0301", "装置未录入!"),
NDID_SAME_STEP("A0301", "设备已注册!"), NDID_SAME_STEP("A0301", "装置已注册!"),
MISSING_CLIENT("A0302","设备客户端不在线!"), MISSING_CLIENT("A0302","装置端不在线!"),
MODEL_REPEAT("A0302", "模板存在,请勿重复录入!"), MODEL_REPEAT("A0302", "模板存在,请勿重复录入!"),
MODEL_NO_FIND("A0302", "模板不存在,请先录入模板数据!"), MODEL_NO_FIND("A0302", "模板不存在,请先录入模板数据!"),
MODEL_ERROR("A0302", "模板未找到,生成监测点失败!"), MODEL_ERROR("A0302", "模板未找到,生成监测点失败!"),
@@ -30,7 +30,7 @@ public enum AccessResponseEnum {
DEV_MODEL_NOT_FIND("A0303","装置型号未找到!"), DEV_MODEL_NOT_FIND("A0303","装置型号未找到!"),
DEV_IS_NOT_ZL("A0303","注册装置不是直连装置!"), DEV_IS_NOT_ZL("A0303","注册装置不是直连装置!"),
DEV_IS_NOT_WG("A0303","注册装置不是网关!"), DEV_IS_NOT_WG("A0303","注册装置不是网关!"),
DEV_IS_NOT_PORTABLE("A0303","注册装置不是便携式设备!"), DEV_IS_NOT_PORTABLE("A0303","注册装置不是便携式装置!"),
REGISTER_RESPONSE_ERROR("A0304","装置注册,装置侧应答失败!"), REGISTER_RESPONSE_ERROR("A0304","装置注册,装置侧应答失败!"),
ACCESS_RESPONSE_ERROR("A0304","装置注册,装置侧应答失败!"), ACCESS_RESPONSE_ERROR("A0304","装置注册,装置侧应答失败!"),
@@ -62,7 +62,7 @@ public enum AccessResponseEnum {
RELOAD_UPLOAD_ERROR("A0308","平台重新上送文件异常"), RELOAD_UPLOAD_ERROR("A0308","平台重新上送文件异常"),
CLDID_IS_NULL("A0309","逻辑子设备标识为空"), CLDID_IS_NULL("A0309","逻辑子设备标识为空"),
MODULE_NUMBER_IS_NULL("A0309","设备子模块个数为空"), MODULE_NUMBER_IS_NULL("A0309","装置子模块个数为空"),
LDEVINFO_IS_NULL("A0309","逻辑设备信息为空"), LDEVINFO_IS_NULL("A0309","逻辑设备信息为空"),
SOFTINFO_IS_NULL("A0309","软件信息为空"), SOFTINFO_IS_NULL("A0309","软件信息为空"),
@@ -71,6 +71,8 @@ public enum AccessResponseEnum {
PROCESS_SAME_ERROR("A0311","当前调试已完成,请勿重复调试"), PROCESS_SAME_ERROR("A0311","当前调试已完成,请勿重复调试"),
PROCESS_MISSING_ERROR("A0311","调试流程缺失,请核查功能调试、出厂调试"), PROCESS_MISSING_ERROR("A0311","调试流程缺失,请核查功能调试、出厂调试"),
PROCESS_ERROR("A0311","调试流程异常,请先进行功能调试、出厂调试!"), PROCESS_ERROR("A0311","调试流程异常,请先进行功能调试、出厂调试!"),
FILE_CHECK_ERROR("A0312","文件校验码不一致!"),
; ;
private final String code; private final String code;

View File

@@ -44,6 +44,7 @@ public enum TypeEnum {
TYPE_28("4662","设备根目录查询应答"), TYPE_28("4662","设备根目录查询应答"),
TYPE_29("9217","设备心跳请求"), TYPE_29("9217","设备心跳请求"),
TYPE_30("4865","设备数据主动上送"), TYPE_30("4865","设备数据主动上送"),
TYPE_31("8503","设备控制命令"),
/** /**
* 数据类型 * 数据类型
@@ -63,6 +64,7 @@ public enum TypeEnum {
DATA_13("13","内部定值InSet"), DATA_13("13","内部定值InSet"),
DATA_14("14","控制Ctrl"), DATA_14("14","控制Ctrl"),
DATA_16("16","波形文件"), DATA_16("16","波形文件"),
DATA_48("48","工程信息"),
/** /**
* 数据模型列表 * 数据模型列表

View File

@@ -84,4 +84,83 @@ public class RspDataDto {
private Double capacityA; private Double capacityA;
} }
/**
* 工程信息
*/
@Data
public static class ProjectInfo {
@SerializedName("PrjName")
@ApiModelProperty("项目名称")
private String prjName;
@SerializedName("PrjTimeStart")
@ApiModelProperty("项目起始时间")
private Long prjTimeStart;
@SerializedName("PrjTimeEnd")
@ApiModelProperty("项目结束时间")
private Long prjTimeEnd;
@SerializedName("PrjDataPath")
@ApiModelProperty("文件路径")
private String prjDataPath;
@SerializedName("DevType")
@ApiModelProperty("装置型号")
private String devType;
@SerializedName("DevMac")
@ApiModelProperty("装置mac")
private String devMac;
@SerializedName("AppVersion")
@ApiModelProperty("设备应用程序版本信息")
private String appVersion;
@SerializedName("Cldid")
@ApiModelProperty("逻辑子设备ID0-逻辑设备本身)")
private Integer clDid;
@SerializedName("StatCycle")
@ApiModelProperty("分钟数据统计时间间隔1~10分钟")
private Integer statCycle;
@SerializedName("VolGrade")
@ApiModelProperty("电压等级kV")
private Double volGrade;
@SerializedName("VolConType")
@ApiModelProperty("电压接线方式 0-星型, 1-角型, 2-V型")
private Integer volConType;
@SerializedName("CurConSel")
@ApiModelProperty("电流接线方式 0-正常, 1-合成IB, 2-合成IC")
private Integer curConSel;
@SerializedName("PtRatio")
@ApiModelProperty("PT变比")
private Integer ptRatio;
@SerializedName("CtRatio")
@ApiModelProperty("CT变比")
private Integer ctRatio;
@SerializedName("CapacitySscb")
@ApiModelProperty("基准短路容量MVA")
private Double capacitySscb;
@SerializedName("CapacitySscmin")
@ApiModelProperty("最小短路容量MVA")
private Double capacitySscmin;
@SerializedName("CapacitySt")
@ApiModelProperty("供电设备容量MVA")
private Double capacitySt;
@SerializedName("CapacitySi")
@ApiModelProperty("用户协议容量MVA")
private Double capacitySi;
}
} }

View File

@@ -70,8 +70,84 @@ public class AutoDataDto {
@ApiModelProperty("数据是否参与合格率统计") @ApiModelProperty("数据是否参与合格率统计")
private Integer dataTag; private Integer dataTag;
@SerializedName("Code")
@ApiModelProperty("事件码")
private Integer code;
@SerializedName("Data") @SerializedName("Data")
private String data; private String data;
@SerializedName("PrjName")
@ApiModelProperty("工程名称")
private String prjName;
@SerializedName("PrjTimeStart")
@ApiModelProperty("装置启动时间")
private Long prjTimeStart;
@SerializedName("PrjTimeEnd")
@ApiModelProperty("装置结束时间")
private Long prjTimeEnd;
@SerializedName("PrjDataPath")
@ApiModelProperty("装置数据路径")
private String prjDataPath;
@SerializedName("DevType")
@ApiModelProperty("装置型号")
private String devType;
@SerializedName("DevMac")
@ApiModelProperty("装置mac地址")
private String devMac;
@SerializedName("AppVersion")
@ApiModelProperty("装置程序版本")
private String appVersion;
@SerializedName("Cldid")
@ApiModelProperty("逻辑子设备id")
private Integer clDid;
@SerializedName("StatCycle")
@ApiModelProperty("统计间隔")
private Integer statCycle;
@SerializedName("VolGrade")
@ApiModelProperty("电压等级")
private Float volGrade;
@SerializedName("VolConType")
@ApiModelProperty("电压接线方式0-星型, 1-角型, 2-V型")
private Integer volConType;
@SerializedName("CurConSel")
@ApiModelProperty("电流接线方式0-正常, 1-合成IB, 2-合成IC")
private Integer curConSel;
@SerializedName("PtRatio")
@ApiModelProperty("PT变比")
private Integer ptRatio;
@SerializedName("CtRatio")
@ApiModelProperty("ct变比")
private Integer ctRatio;
@SerializedName("CapacitySscb")
@ApiModelProperty("基准短路容量")
private Float capacitySscb;
@SerializedName("CapacitySscmin")
@ApiModelProperty("最小短路容量")
private Float capacitySscmin;
@SerializedName("CapacitySt")
@ApiModelProperty("供电设备容量")
private Float capacitySt;
@SerializedName("CapacitySi")
@ApiModelProperty("用户协议容量")
private Float capacitySi;
} }
} }

View File

@@ -0,0 +1,22 @@
package com.njcn.access.pojo.dto;
import com.alibaba.nacos.shaded.com.google.gson.annotations.SerializedName;
import lombok.Data;
import java.io.Serializable;
/**
* @author xy
*/
@Data
public class ControlDto implements Serializable {
@SerializedName("Cldid")
private Integer clDid;
@SerializedName("CmdType")
private String cmdType;
@SerializedName("CmdParm")
private String cmdParm;
}

View File

@@ -0,0 +1,52 @@
package com.njcn.access.pojo.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* @author xy
* 装置缓存信息
*/
@Data
public class DeviceRedisInfoDto {
@ApiModelProperty("装置id")
private String deviceId;
@ApiModelProperty("装置nDid")
private String nDid;
@ApiModelProperty("装置类型")
private String deviceType;
@ApiModelProperty("装置模板id")
private String modelId;
@ApiModelProperty("模板名称")
private String modelName;
@ApiModelProperty("模板版本")
private String modelVersion;
@ApiModelProperty("模板类型 0:治理模板 1:电能质量模板")
private Integer modelType;
@ApiModelProperty("监测点信息")
private List<LineRedisInfo> lineList;
@Data
public static class LineRedisInfo {
@ApiModelProperty("监测点id")
private String lineId;
@ApiModelProperty("监测点位置")
private String location;
@ApiModelProperty("逻辑设备编码")
private Integer clDid;
}
}

View File

@@ -76,8 +76,85 @@ public class EventDto {
@ApiModelProperty("告警故障编码一般显示为Hex") @ApiModelProperty("告警故障编码一般显示为Hex")
private String code; private String code;
@SerializedName("DataTag")
@ApiModelProperty("数据标识1-标识数据异常")
private Integer dataTag;
@SerializedName("Parm") @SerializedName("Parm")
private List<Param> param; private List<Param> param;
@SerializedName("PrjName")
@ApiModelProperty("工程名称")
private String prjName;
@SerializedName("PrjTimeStart")
@ApiModelProperty("装置启动时间")
private Long prjTimeStart;
@SerializedName("PrjTimeEnd")
@ApiModelProperty("装置结束时间")
private Long prjTimeEnd;
@SerializedName("PrjDataPath")
@ApiModelProperty("装置数据路径")
private String prjDataPath;
@SerializedName("DevType")
@ApiModelProperty("装置型号")
private String devType;
@SerializedName("DevMac")
@ApiModelProperty("装置mac地址")
private String devMac;
@SerializedName("AppVersion")
@ApiModelProperty("装置程序版本")
private String appVersion;
@SerializedName("Cldid")
@ApiModelProperty("逻辑子设备id")
private Integer clDid;
@SerializedName("StatCycle")
@ApiModelProperty("统计间隔")
private Integer statCycle;
@SerializedName("VolGrade")
@ApiModelProperty("电压等级")
private Float volGrade;
@SerializedName("VolConType")
@ApiModelProperty("电压接线方式0-星型, 1-角型, 2-V型")
private Integer volConType;
@SerializedName("CurConSel")
@ApiModelProperty("电流接线方式0-正常, 1-合成IB, 2-合成IC")
private Integer curConSel;
@SerializedName("PtRatio")
@ApiModelProperty("PT变比")
private Integer ptRatio;
@SerializedName("CtRatio")
@ApiModelProperty("ct变比")
private Integer ctRatio;
@SerializedName("CapacitySscb")
@ApiModelProperty("基准短路容量")
private Float capacitySscb;
@SerializedName("CapacitySscmin")
@ApiModelProperty("最小短路容量")
private Float capacitySscmin;
@SerializedName("CapacitySt")
@ApiModelProperty("供电设备容量")
private Float capacitySt;
@SerializedName("CapacitySi")
@ApiModelProperty("用户协议容量")
private Float capacitySi;
} }
@Data @Data

View File

@@ -0,0 +1,63 @@
package com.njcn.access.pojo.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDate;
import java.util.List;
/**
* @author xy
* 模板缓存信息
*/
@Data
public class ModelRedisInfoDto {
@ApiModelProperty("模板id")
private String modelId;
@ApiModelProperty("模板名称")
private String modelName;
@ApiModelProperty("模板时间")
private LocalDate versionDate;
@ApiModelProperty("模板版本")
private String version;
@ApiModelProperty("数据集集合")
private List<DataSet> dataSetList;
@Data
public static class DataSet {
@ApiModelProperty("数据集id")
private String dataSetId;
@ApiModelProperty("数据集名称")
private String dataSetName;
@ApiModelProperty("数据指标集合")
private List<DataArray> dataArrayList;
}
@Data
public static class DataArray {
@ApiModelProperty("数据指标id")
private String dataArrayId;
@ApiModelProperty("数据指标名称")
private String dataArrayName;
@ApiModelProperty("数据指标别名")
private String anotherName;
@ApiModelProperty("数据指标统计方式")
private String statMethod;
@ApiModelProperty("数据指标相别")
private String phase;
}
}

View File

@@ -34,4 +34,8 @@ public class UploadFileDto {
@ApiModelProperty("文件校验码") @ApiModelProperty("文件校验码")
private String fileCheck; private String fileCheck;
@SerializedName("StepFileCheck")
@ApiModelProperty("当前帧文件校验码")
private String stepFileCheck;
} }

View File

@@ -5,6 +5,7 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
import java.util.List;
/** /**
* 类的介绍: * 类的介绍:
@@ -42,7 +43,10 @@ public class FileDto implements Serializable {
private String type; private String type;
@SerializedName("FileInfo") @SerializedName("FileInfo")
private FileDto.FileInfo fileInfo; private FileInfo fileInfo;
@SerializedName("DirInfo")
private List<DirInfo> dirInfo;
@SerializedName("Data") @SerializedName("Data")
private String data; private String data;
@@ -86,4 +90,22 @@ public class FileDto implements Serializable {
private String fileChkType; private String fileChkType;
} }
@Data
public static class DirInfo{
@SerializedName("Name")
private String name;
@SerializedName("Type")
private String type;
@SerializedName("Size")
@ApiModelProperty("文件大小单位KB")
private Integer size;
@SerializedName("Time")
@ApiModelProperty("时间")
private Long time;
}
} }

View File

@@ -1,63 +0,0 @@
package com.njcn.access.pojo.po;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.bo.BaseEntity;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
/**
* <p>
* 系统软件表
* </p>
*
* @author xuyang
* @since 2023-05-17
*/
@Data
@TableName("cs_soft_info")
public class CsSoftInfoPO {
private static final long serialVersionUID = 1L;
private String id;
/**
* 读写操作属性“r”
*/
private String opAttr;
/**
* 操作系统名称裸机系统填Null
*/
private String osName;
/**
* 操作系统版本裸机系统填Null
*/
private String osVersion;
/**
* 应用程序版本号
*/
private String appVersion;
/**
* 应用程序发布日期
*/
private Date appDate;
/**
* 应用程序校验码
*/
private String appCheck;
/**
* 是否支持远程升级程序
*/
private String softUpdate;
}

View File

@@ -1,8 +1,11 @@
package com.njcn.access.utils; package com.njcn.access.utils;
import org.springframework.stereotype.Component;
/** /**
* @author xy * @author xy
*/ */
@Component
public class CRC32Utils { public class CRC32Utils {
// CRC-32/MPEG-2 多项式, x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x + 1 // CRC-32/MPEG-2 多项式, x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x + 1

View File

@@ -0,0 +1,45 @@
package com.njcn.access.utils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author xy
*/
@Component
public class ChannelObjectUtil {
/**
* 将list转成对应实体
* @param object
* @param clazz
* @return
* @param <T>
*/
public <T> List<T> objectToList(Object object, Class<T> clazz) {
List<T> resultList = new ArrayList<>();
if (object instanceof List<?>) {
for (Object o : (List<?>) object) {
resultList.add(clazz.cast(o));
}
}
return resultList;
}
/**
* 将object转成对应实体
* @param object
* @param clazz
* @return
* @param <T>
*/
public <T> T objectToSingleObject(Object object, Class<T> clazz) {
if (clazz.isInstance(object)) {
return clazz.cast(object);
}
// 或者抛出异常,根据您的需求
return null;
}
}

View File

@@ -63,7 +63,12 @@
<artifactId>common-mq</artifactId> <artifactId>common-mq</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.njcn</groupId>
<artifactId>zl-event-api</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@@ -0,0 +1,113 @@
package com.njcn.access.controller;
import com.njcn.access.service.AskDeviceDataService;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author xy
*/
@Slf4j
@RestController
@RequestMapping("/askDeviceData")
@Api(tags = "平台操作装置报文")
@AllArgsConstructor
//@ApiIgnore
public class AskDeviceDataController extends BaseController {
private final AskDeviceDataService askDeviceDataService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/askDeviceRootPath")
@ApiOperation("设备根目录询问")
@ApiImplicitParam(name = "nDid", value = "nDid", required = true)
public HttpResult<String> askDeviceRootPath(@RequestParam("nDid") String nDid){
String methodDescribe = getMethodDescribe("askDeviceRootPath");
askDeviceDataService.askDeviceRootPath(nDid);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/askDeviceFileOrDir")
@ApiOperation("设备文件/目录信息询问")
@ApiImplicitParams({
@ApiImplicitParam(name = "nDid", value = "nDid", required = true),
@ApiImplicitParam(name = "name", value = "name", required = true)
})
public HttpResult<String> askDeviceFileOrDir(@RequestParam("nDid") String nDid, @RequestParam("name") String name){
String methodDescribe = getMethodDescribe("askDeviceFileOrDir");
askDeviceDataService.askDeviceFileOrDir(nDid,name);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/downloadFile")
@ApiOperation("设备文件下载")
@ApiImplicitParams({
@ApiImplicitParam(name = "nDid", value = "nDid", required = true),
@ApiImplicitParam(name = "name", value = "文件路径名", required = true),
@ApiImplicitParam(name = "size", value = "文件大小(单位byte)", required = true),
@ApiImplicitParam(name = "fileCheck", value = "文件校验码", required = true)
})
public HttpResult<Boolean> downloadFile(@RequestParam("nDid") String nDid, @RequestParam("name") String name, @RequestParam("size") Integer size, @RequestParam("fileCheck") String fileCheck){
String methodDescribe = getMethodDescribe("downloadFile");
boolean result = askDeviceDataService.downloadFile(nDid,name,size,fileCheck);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/rebootDevice")
@ApiOperation("重启设备")
@ApiImplicitParam(name = "nDid", value = "nDid", required = true)
public HttpResult<String> rebootDevice(@RequestParam("nDid") String nDid){
String methodDescribe = getMethodDescribe("rebootDevice");
askDeviceDataService.rebootDevice(nDid);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/createFolder")
@ApiOperation("创建文件")
@ApiImplicitParams({
@ApiImplicitParam(name = "nDid", value = "nDid", required = true),
@ApiImplicitParam(name = "path", value = "文件路径", required = true)
})
public HttpResult<String> createFolder(@RequestParam("nDid") String nDid, @RequestParam("path") String path){
String methodDescribe = getMethodDescribe("createFolder");
askDeviceDataService.createFolder(nDid,path);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/deleteFolder")
@ApiOperation("删除文件")
@ApiImplicitParams({
@ApiImplicitParam(name = "nDid", value = "nDid", required = true),
@ApiImplicitParam(name = "path", value = "文件路径", required = true)
})
public HttpResult<String> deleteFolder(@RequestParam("nDid") String nDid, @RequestParam("path") String path){
String methodDescribe = getMethodDescribe("deleteFolder");
askDeviceDataService.deleteFolder(nDid,path);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
}

View File

@@ -37,7 +37,7 @@ public class CsDeviceController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON) @OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/register") @PostMapping("/register")
@ApiOperation("直连设备状态判断") @ApiOperation("直连设备注册")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "nDid", value = "设备识别码", required = true), @ApiImplicitParam(name = "nDid", value = "设备识别码", required = true),
@ApiImplicitParam(name = "type", value = "流程标识(2:功能调试 3:出厂调试 4:设备注册)", required = true) @ApiImplicitParam(name = "type", value = "流程标识(2:功能调试 3:出厂调试 4:设备注册)", required = true)
@@ -62,7 +62,7 @@ public class CsDeviceController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON) @OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/access") @PostMapping("/access")
@ApiOperation("直连设备注册") @ApiOperation("直连设备接入")
@ApiImplicitParam(name = "devAccessParam", value = "接入参数", required = true) @ApiImplicitParam(name = "devAccessParam", value = "接入参数", required = true)
public HttpResult<String> devAccess(@RequestBody @Validated DevAccessParam devAccessParam){ public HttpResult<String> devAccess(@RequestBody @Validated DevAccessParam devAccessParam){
String methodDescribe = getMethodDescribe("devAccess"); String methodDescribe = getMethodDescribe("devAccess");
@@ -96,7 +96,7 @@ public class CsDeviceController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON) @OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/wlRegister") @PostMapping("/wlRegister")
@ApiOperation("便携式设备注册") @ApiOperation("便携式设备接入")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "nDid", value = "设备识别码", required = true) @ApiImplicitParam(name = "nDid", value = "设备识别码", required = true)
}) })
@@ -109,7 +109,7 @@ public class CsDeviceController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON) @OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/wlAccess") @PostMapping("/wlAccess")
@ApiOperation("便携式设备接入") @ApiOperation("便携式设备手动接入")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "nDid", value = "设备识别码", required = true) @ApiImplicitParam(name = "nDid", value = "设备识别码", required = true)
}) })

View File

@@ -1,22 +0,0 @@
package com.njcn.access.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.njcn.web.controller.BaseController;
/**
* <p>
* 系统软件表 前端控制器
* </p>
*
* @author xuyang
* @since 2023-08-09
*/
@RestController
@RequestMapping("/csSoftInfo")
public class CsSoftInfoController extends BaseController {
}

View File

@@ -1,6 +1,5 @@
package com.njcn.access.controller; package com.njcn.access.controller;
import com.njcn.access.pojo.po.CsLineModel;
import com.njcn.access.service.ICsTopicService; import com.njcn.access.service.ICsTopicService;
import com.njcn.common.pojo.annotation.OperateInfo; import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum; import com.njcn.common.pojo.enums.common.LogEnum;
@@ -13,7 +12,10 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.annotations.ApiIgnore;
/** /**

View File

@@ -21,17 +21,16 @@ import com.njcn.access.pojo.dto.file.FileRedisDto;
import com.njcn.access.pojo.param.ReqAndResParam; import com.njcn.access.pojo.param.ReqAndResParam;
import com.njcn.access.pojo.po.CsDeviceOnlineLogs; import com.njcn.access.pojo.po.CsDeviceOnlineLogs;
import com.njcn.access.pojo.po.CsLineModel; import com.njcn.access.pojo.po.CsLineModel;
import com.njcn.access.pojo.po.CsSoftInfoPO;
import com.njcn.access.pojo.po.CsTopic; import com.njcn.access.pojo.po.CsTopic;
import com.njcn.access.service.*; import com.njcn.access.service.ICsDeviceOnlineLogsService;
import com.njcn.access.service.ICsEquipmentDeliveryService;
import com.njcn.access.service.ICsLineModelService;
import com.njcn.access.service.ICsTopicService;
import com.njcn.common.pojo.dto.DeviceLogDTO; import com.njcn.common.pojo.dto.DeviceLogDTO;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.*; import com.njcn.csdevice.api.*;
import com.njcn.csdevice.pojo.param.CsLineParam; import com.njcn.csdevice.pojo.param.CsLineParam;
import com.njcn.csdevice.pojo.po.CsDataSet; import com.njcn.csdevice.pojo.po.*;
import com.njcn.csdevice.pojo.po.CsDevCapacityPO;
import com.njcn.csdevice.pojo.po.CsDevModelPO;
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
import com.njcn.mq.message.AppAutoDataMessage; import com.njcn.mq.message.AppAutoDataMessage;
import com.njcn.mq.message.AppEventMessage; import com.njcn.mq.message.AppEventMessage;
import com.njcn.mq.message.AppFileMessage; import com.njcn.mq.message.AppFileMessage;
@@ -53,13 +52,16 @@ import org.springframework.transaction.annotation.Transactional;
import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolation;
import javax.validation.Validator; import javax.validation.Validator;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
/** /**
* @author hongawen * @author hongawen
* @version 1.0.0 * @version 1.0.0
@@ -71,39 +73,22 @@ import java.util.stream.Collectors;
public class MqttMessageHandler { public class MqttMessageHandler {
private final DevModelFeignClient devModelFeignClient; private final DevModelFeignClient devModelFeignClient;
private final ICsLineModelService csLineModelService; private final ICsLineModelService csLineModelService;
private final ICsTopicService csTopicService; private final ICsTopicService csTopicService;
private final MqttPublisher publisher; private final MqttPublisher publisher;
private final RedisUtil redisUtil; private final RedisUtil redisUtil;
private final ICsEquipmentDeliveryService csEquipmentDeliveryService; private final ICsEquipmentDeliveryService csEquipmentDeliveryService;
private final DataSetFeignClient dataSetFeignClient; private final DataSetFeignClient dataSetFeignClient;
private final AppAutoDataMessageTemplate appAutoDataMessageTemplate; private final AppAutoDataMessageTemplate appAutoDataMessageTemplate;
private final AppEventMessageTemplate appEventMessageTemplate; private final AppEventMessageTemplate appEventMessageTemplate;
private final CsLogsFeignClient csLogsFeignClient; private final CsLogsFeignClient csLogsFeignClient;
private final AppFileMessageTemplate appFileMessageTemplate; private final AppFileMessageTemplate appFileMessageTemplate;
private final AppFileStreamMessageTemplate appFileStreamMessageTemplate; private final AppFileStreamMessageTemplate appFileStreamMessageTemplate;
private final ICsDeviceOnlineLogsService onlineLogsService; private final ICsDeviceOnlineLogsService onlineLogsService;
private final CsSoftInfoFeignClient csSoftInfoFeignClient;
private final ICsSoftInfoService csSoftInfoService;
private final CsLineFeignClient csLineFeignClient; private final CsLineFeignClient csLineFeignClient;
private final DevCapacityFeignClient devCapacityFeignClient; private final DevCapacityFeignClient devCapacityFeignClient;
private final EquipmentFeignClient equipmentFeignClient; private final EquipmentFeignClient equipmentFeignClient;
@Autowired @Autowired
Validator validator; Validator validator;
@@ -350,6 +335,11 @@ public class MqttMessageHandler {
onlineLogsService.save(csDeviceOnlineLogs); onlineLogsService.save(csDeviceOnlineLogs);
} }
} }
//接入后系统模拟装置心跳
redisUtil.saveByKeyWithExpire("MQTT:" + nDid, Instant.now().toEpochMilli(),300L);
//修改redis的mid
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,1);
redisUtil.saveByKeyWithExpire("online" + nDid,"online",10L);
//询问设备软件信息 //询问设备软件信息
askDevData(nDid,version,1,mid); askDevData(nDid,version,1,mid);
//更新治理监测点信息和设备容量 //更新治理监测点信息和设备容量
@@ -374,23 +364,28 @@ public class MqttMessageHandler {
//记录设备软件信息 //记录设备软件信息
CsSoftInfoPO csSoftInfoPo = new CsSoftInfoPO(); CsSoftInfoPO csSoftInfoPo = new CsSoftInfoPO();
BeanUtils.copyProperties(softInfo,csSoftInfoPo); BeanUtils.copyProperties(softInfo,csSoftInfoPo);
try {
String id = IdUtil.fastSimpleUUID(); String id = IdUtil.fastSimpleUUID();
csSoftInfoPo.setId(id); csSoftInfoPo.setId(id);
csSoftInfoPo.setAppDate(new SimpleDateFormat("yyyy-MM-dd").parse(softInfo.getAppDate())); DateTimeFormatter formatter = new DateTimeFormatterBuilder()
csSoftInfoService.save(csSoftInfoPo); .appendPattern("yyyy-MM-dd[[HH][:mm][:ss]]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
.toFormatter();
LocalDateTime localDateTime = LocalDateTime.parse(softInfo.getAppDate(), formatter);
assertThat(localDateTime).isNotNull();
csSoftInfoPo.setAppDate(localDateTime);
csSoftInfoFeignClient.saveSoftInfo(csSoftInfoPo);
//更新设备软件id 先看是否存在软件信息,删除 然后在录入 //更新设备软件id 先看是否存在软件信息,删除 然后在录入
CsEquipmentDeliveryPO po = equipmentFeignClient.findDevByNDid(nDid).getData(); CsEquipmentDeliveryPO po = equipmentFeignClient.findDevByNDid(nDid).getData();
String soft = po.getSoftinfoId(); String soft = po.getSoftinfoId();
if (StringUtil.isNotBlank(soft)){ if (StringUtil.isNotBlank(soft)){
csSoftInfoService.removeById(soft); csSoftInfoFeignClient.removeSoftInfo(soft);
} }
equipmentFeignClient.updateSoftInfo(nDid,csSoftInfoPo.getId()); equipmentFeignClient.updateSoftInfo(nDid,csSoftInfoPo.getId());
//询问设备容量信息 //询问设备容量信息
//askDevData(nDid,version,2,(res.getMid()+1)); //askDevData(nDid,version,2,(res.getMid()+1));
} catch (ParseException e) {
e.printStackTrace();
}
break; break;
case 2: case 2:
List<RspDataDto.LdevInfo> devInfo = JSON.parseArray(JSON.toJSONString(rspDataDto.getDataArray()), RspDataDto.LdevInfo.class); List<RspDataDto.LdevInfo> devInfo = JSON.parseArray(JSON.toJSONString(rspDataDto.getDataArray()), RspDataDto.LdevInfo.class);
@@ -400,27 +395,29 @@ public class MqttMessageHandler {
List<CsDevCapacityPO> list = new ArrayList<>(); List<CsDevCapacityPO> list = new ArrayList<>();
devInfo.forEach(item->{ devInfo.forEach(item->{
//1.更新治理监测点信息 //1.更新治理监测点信息
if (Objects.equals(item.getClDid(),0)){
CsLineParam csLineParam = new CsLineParam(); CsLineParam csLineParam = new CsLineParam();
if (Objects.equals(item.getClDid(),0)){
csLineParam.setLineId(nDid.concat("0")); csLineParam.setLineId(nDid.concat("0"));
//2.录入各个模块设备容量
CsDevCapacityPO csDevCapacity = new CsDevCapacityPO();
csDevCapacity.setLineId(nDid.concat("0"));
csDevCapacity.setCldid(item.getClDid());
csDevCapacity.setCapacity(Objects.isNull(item.getCapacityA())?0.0:item.getCapacityA());
list.add(csDevCapacity);
} else {
csLineParam.setLineId(nDid.concat(item.getClDid().toString()));
}
csLineParam.setVolGrade(item.getVolGrade()); csLineParam.setVolGrade(item.getVolGrade());
csLineParam.setPtRatio(item.getPtRatio()); csLineParam.setPtRatio(item.getPtRatio());
csLineParam.setCtRatio(item.getCtRatio()); csLineParam.setCtRatio(item.getCtRatio());
csLineParam.setConType(item.getConType()); csLineParam.setConType(item.getConType());
csLineFeignClient.updateLine(csLineParam); csLineFeignClient.updateLine(csLineParam);
}
//2.录入各个模块设备容量
CsDevCapacityPO csDevCapacity = new CsDevCapacityPO();
csDevCapacity.setLineId(nDid.concat("0"));
csDevCapacity.setCldid(item.getClDid());
csDevCapacity.setCapacity(item.getCapacityA());
list.add(csDevCapacity);
}); });
if (CollectionUtil.isNotEmpty(list)) {
devCapacityFeignClient.addList(list); devCapacityFeignClient.addList(list);
//3.更新设备模块个数 //3.更新设备模块个数
equipmentFeignClient.updateModuleNumber(nDid,(devInfo.size()-1)); equipmentFeignClient.updateModuleNumber(nDid,(devInfo.size()-1));
//4.询问监测点pt/ct信息 }
//askDevData(nDid,version,3,(res.getMid()+1));
} else if (Objects.equals(res.getDid(),2)) { } else if (Objects.equals(res.getDid(),2)) {
logDto.setOperate(nDid + "更新电网侧、负载侧监测点信息"); logDto.setOperate(nDid + "更新电网侧、负载侧监测点信息");
//1.更新电网侧、负载侧监测点相关信息 //1.更新电网侧、负载侧监测点相关信息
@@ -436,10 +433,24 @@ public class MqttMessageHandler {
} }
} }
break; break;
case 48:
log.info("询问装置项目列表");
logDto.setOperate("监测点:" + (nDid + rspDataDto.getClDid()) + "询问项目列表");
List<RspDataDto.ProjectInfo> projectInfoList = JSON.parseArray(JSON.toJSONString(rspDataDto.getDataArray()), RspDataDto.ProjectInfo.class);
String key = AppRedisKey.PROJECT_INFO + nDid + rspDataDto.getClDid();
redisUtil.saveByKeyWithExpire(key,projectInfoList,60L);
break;
default: default:
break; break;
} }
break; break;
case 4663:
log.info("装置操作应答");
if (Objects.equals(res.getCode(),AccessEnum.SUCCESS.getCode())){
String key = AppRedisKey.CONTROL + nDid;
redisUtil.saveByKeyWithExpire(key,"success",10L);
}
break;
default: default:
break; break;
} }
@@ -467,7 +478,7 @@ public class MqttMessageHandler {
switch (res.getType()){ switch (res.getType()){
case 4865: case 4865:
//设置心跳时间,超时改为掉线 //设置心跳时间,超时改为掉线
redisUtil.saveByKeyWithExpire("MQTT:" + nDid, Instant.now().toEpochMilli(),180L); redisUtil.saveByKeyWithExpire("MQTT:" + nDid, Instant.now().toEpochMilli(),300L);
//有心跳,则将装置改成在线 //有心跳,则将装置改成在线
//csEquipmentDeliveryService.updateRunStatusBynDid(nDid,AccessEnum.ONLINE.getCode()); //csEquipmentDeliveryService.updateRunStatusBynDid(nDid,AccessEnum.ONLINE.getCode());
//处理心跳 //处理心跳
@@ -510,7 +521,7 @@ public class MqttMessageHandler {
} }
//判断事件类型 //判断事件类型
switch (dataDto.getMsg().getDataAttr()) { switch (dataDto.getMsg().getDataAttr()) {
//暂态事件、录波处理 //暂态事件、录波处理、工程信息
case 0: case 0:
log.info(nDid + "事件报文为:" + new String(message.getPayload(), StandardCharsets.UTF_8)); log.info(nDid + "事件报文为:" + new String(message.getPayload(), StandardCharsets.UTF_8));
EventDto eventDto = gson.fromJson(new String(message.getPayload(), StandardCharsets.UTF_8), EventDto.class); EventDto eventDto = gson.fromJson(new String(message.getPayload(), StandardCharsets.UTF_8), EventDto.class);
@@ -562,12 +573,24 @@ public class MqttMessageHandler {
//响应请求 //响应请求
switch (fileDto.getType()){ switch (fileDto.getType()){
case 4657: case 4657:
log.info("获取文件信息"); log.info("获取文件信息" + fileDto);
log.info("文件信息响应:" + fileDto); String key = AppRedisKey.PROJECT_INFO + nDid;
if (Objects.isNull(fileDto.getMsg().getType())) {
handleDefaultCase(fileDto, nDid);
} else {
if (Objects.equals("dir", fileDto.getMsg().getType())) {
saveDirectoryInfo(fileDto.getMsg().getDirInfo(), key);
} else if (Objects.equals("file", fileDto.getMsg().getType())){
saveFileInfo(fileDto.getMsg().getFileInfo(), key);
appFileMessageTemplate.sendMember(appFileMessage); appFileMessageTemplate.sendMember(appFileMessage);
}
}
break; break;
case 4658: case 4658:
log.info("获取文件流信息"); log.info("获取文件流信息");
FileRedisDto dto = new FileRedisDto();
dto.setCode(fileDto.getCode());
redisUtil.saveByKeyWithExpire(AppRedisKey.DOWNLOAD + fileDto.getMsg().getName() + fileDto.getMid(),dto,10L);
if (Objects.equals(fileDto.getCode(),AccessEnum.SUCCESS.getCode())){ if (Objects.equals(fileDto.getCode(),AccessEnum.SUCCESS.getCode())){
appFileStreamMessageTemplate.sendMember(appFileMessage); appFileStreamMessageTemplate.sendMember(appFileMessage);
} }
@@ -580,13 +603,67 @@ public class MqttMessageHandler {
log.info("装置收到系统上传的文件"); log.info("装置收到系统上传的文件");
FileRedisDto fileRedisDto = new FileRedisDto(); FileRedisDto fileRedisDto = new FileRedisDto();
fileRedisDto.setCode(fileDto.getCode()); fileRedisDto.setCode(fileDto.getCode());
redisUtil.saveByKeyWithExpire("uploadFileStep",fileRedisDto,10L); redisUtil.saveByKeyWithExpire(AppRedisKey.UPLOAD,fileRedisDto,10L);
redisUtil.saveByKeyWithExpire("uploading","uploading",20L);
break; break;
case 4660:
log.info("设备目录/文件删除应答");
redisUtil.saveByKeyWithExpire( "deleteDir"+ nDid,fileDto.getCode(),10L);
break;
case 4661:
log.info("设备目录创建应答");
redisUtil.saveByKeyWithExpire( "createDir"+ nDid,fileDto.getCode(),10L);
break;
case 4662:
log.info("装置根目录应答");
redisUtil.saveByKeyWithExpire(AppRedisKey.DEVICE_ROOT_PATH + nDid,fileDto.getMsg().getName(),10L);
default: default:
break; break;
} }
} }
/**
* 装置异常事件记录
* @param topic
* @param message
* @param version
* @param nDid
* @param payload
*/
@MqttSubscribe(value = "/Dev/Error/{edgeId}",qos = 1)
@Transactional(rollbackFor = Exception.class)
public void devErrorInfo(String topic, MqttMessage message, @NamedValue("version") String version, @NamedValue("edgeId") String nDid, @Payload String payload) {
//解析数据
Gson gson = new Gson();
log.info(nDid + "事件报文为:" + new String(message.getPayload(), StandardCharsets.UTF_8));
EventDto eventDto = gson.fromJson(new String(message.getPayload(), StandardCharsets.UTF_8), EventDto.class);
JSONObject jsonObject0 = JSONObject.parseObject(JSON.toJSONString(eventDto));
AppEventMessage appEventMessage = JSONObject.toJavaObject(jsonObject0, AppEventMessage.class);
appEventMessage.setId(nDid);
appEventMessageTemplate.sendMember(appEventMessage);
}
private void saveDirectoryInfo(List<FileDto.DirInfo> dirInfo, String key) {
if (!CollectionUtil.isEmpty(dirInfo)) {
redisUtil.saveByKeyWithExpire(key, dirInfo, 20L);
}
}
private void saveFileInfo(FileDto.FileInfo fileInfo, String key) {
if (!Objects.isNull(fileInfo)) {
redisUtil.saveByKeyWithExpire(key, fileInfo, 20L);
}
}
private void handleDefaultCase(FileDto fileDto, String nDid) {
List<FileDto.DirInfo> list = fileDto.getMsg().getDirInfo();
String keyDir = AppRedisKey.PROJECT_INFO + nDid;
saveDirectoryInfo(list, keyDir);
FileDto.FileInfo fileInfo = fileDto.getMsg().getFileInfo();
String keyFile = AppRedisKey.FILE_INFO + nDid;
saveFileInfo(fileInfo, keyFile);
}
/** /**
* type含义 * type含义
@@ -607,7 +684,7 @@ public class MqttMessageHandler {
askDataDto.setEndTime(-1); askDataDto.setEndTime(-1);
switch (type) { switch (type) {
case 1: case 1:
reqAndResParam.setDid(2); reqAndResParam.setDid(0);
askDataDto.setCldid(0); askDataDto.setCldid(0);
askDataDto.setDataType(1); askDataDto.setDataType(1);
break; break;
@@ -635,5 +712,4 @@ public class MqttMessageHandler {
publisher.send("/Pfm/DevCmd/"+version+"/"+nDid, new Gson().toJson(reqAndResParam),1,false); publisher.send("/Pfm/DevCmd/"+version+"/"+nDid, new Gson().toJson(reqAndResParam),1,false);
} }
} }

View File

@@ -1,12 +1,26 @@
package com.njcn.access.listener; package com.njcn.access.listener;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.njcn.access.enums.AccessEnum; import com.njcn.access.enums.AccessEnum;
import com.njcn.access.pojo.po.CsDeviceOnlineLogs;
import com.njcn.access.service.ICsDeviceOnlineLogsService; import com.njcn.access.service.ICsDeviceOnlineLogsService;
import com.njcn.access.service.ICsEquipmentDeliveryService; import com.njcn.access.service.ICsEquipmentDeliveryService;
import com.njcn.access.service.ICsTopicService; import com.njcn.access.service.ICsTopicService;
import com.njcn.access.service.impl.CsDeviceServiceImpl; import com.njcn.access.service.impl.CsDeviceServiceImpl;
import com.njcn.access.utils.MqttUtil;
import com.njcn.common.pojo.dto.DeviceLogDTO; import com.njcn.common.pojo.dto.DeviceLogDTO;
import com.njcn.csdevice.api.CsDeviceUserFeignClient;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.CsLogsFeignClient; import com.njcn.csdevice.api.CsLogsFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.user.api.AppUserFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import com.njcn.zlevent.pojo.dto.NoticeUserDto;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.Message;
@@ -15,11 +29,22 @@ import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/** /**
* @author xy * @author xy
@@ -32,27 +57,36 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
@Resource @Resource
private ICsTopicService csTopicService; private ICsTopicService csTopicService;
@Resource @Resource
private ICsEquipmentDeliveryService csEquipmentDeliveryService; private ICsEquipmentDeliveryService csEquipmentDeliveryService;
@Resource @Resource
private CsDeviceServiceImpl csDeviceService; private CsDeviceServiceImpl csDeviceService;
@Resource @Resource
private CsLogsFeignClient csLogsFeignClient; private CsLogsFeignClient csLogsFeignClient;
@Resource @Resource
private ICsDeviceOnlineLogsService onlineLogsService; private ICsDeviceOnlineLogsService onlineLogsService;
@Resource
private MqttUtil mqttUtil;
@Resource
private CsLedgerFeignClient csLedgerFeignclient;
@Resource
private EquipmentFeignClient equipmentFeignClient;
@Resource
private AppUserFeignClient appUserFeignClient;
@Resource
private CsDeviceUserFeignClient csDeviceUserFeignClient;
@Resource
private UserFeignClient userFeignClient;
@Resource
private RedisUtil redisUtil;
private final Object lock = new Object();
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) { public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer); super(listenerContainer);
} }
// 最大尝试次数 //最大告警次数
private static final int MAX_ATTEMPTS = 4; private static int MAX_WARNING_TIMES = 0;
// 当前尝试次数
private static int attemptCount = 1;
/** /**
* 针对redis数据失效事件进行数据处理 * 针对redis数据失效事件进行数据处理
@@ -71,69 +105,199 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
executeMainTask(scheduler,nDid,version); executeMainTask(scheduler,nDid,version);
} }
//自动接入
else if (expiredKey.startsWith("autoAccess")) {
List<CsEquipmentDeliveryPO> list = csEquipmentDeliveryService.getAll();
list.forEach(item->{
String version = csTopicService.getVersion(item.getNdid());
if (!Objects.isNull(version)){
csDeviceService.devAccessAskTemplate(item.getNdid(),version,1);
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + item.getNdid(),1);
}
});
}
} }
//主任务 //主任务
//1.装置心跳断连
//2.MQTT客户端不在线
private void executeMainTask(ScheduledExecutorService scheduler, String nDid, String version) { private void executeMainTask(ScheduledExecutorService scheduler, String nDid, String version) {
System.out.println("正在执行主任务..."); System.out.println("正在执行主任务...");
DeviceLogDTO logDto = new DeviceLogDTO(); DeviceLogDTO logDto = new DeviceLogDTO();
logDto.setUserName("装置失去心跳触发"); logDto.setUserName("装置失去心跳触发");
logDto.setOperate(nDid + "重连"); //判断mqtt
String clientName = "NJCN-" + nDid.substring(nDid.length() - 6);
boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
//心跳异常,但是客户端在线,则发送接入请求
if (mqttClient) {
csDeviceService.devAccessAskTemplate(nDid,version,1);
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,1);
try {
Thread.sleep(2000);
Object object = redisUtil.getObjectByKey("online" + nDid);
if (Objects.nonNull(object)) {
scheduler.shutdown();
logDto.setOperate("客户端在线重连成功");
} else {
//装置下线
csEquipmentDeliveryService.updateRunStatusBynDid(nDid, AccessEnum.OFFLINE.getCode());
startScheduledTask(scheduler,nDid,version);
logDto.setOperate("客户端离线进入定时任务");
//记录装置掉线时间
CsDeviceOnlineLogs record = onlineLogsService.findLastData(nDid);
record.setOfflineTime(LocalDateTime.now());
onlineLogsService.updateById(record);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//客户端不在线则修改装置状态,进入定时任务
else {
//装置下线 //装置下线
csEquipmentDeliveryService.updateRunStatusBynDid(nDid, AccessEnum.OFFLINE.getCode()); csEquipmentDeliveryService.updateRunStatusBynDid(nDid, AccessEnum.OFFLINE.getCode());
//装置没有心跳,则立马发起接入请求
csDeviceService.devAccessAskTemplate(nDid,version,1);
Integer status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
if (Objects.equals(status,AccessEnum.ONLINE.getCode())){
logDto.setResult(1);
scheduler.shutdown();
} else {
logDto.setResult(0);
startScheduledTask(scheduler,nDid,version); startScheduledTask(scheduler,nDid,version);
} }
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
} }
//启动第一次定时任务
private void startScheduledTask(ScheduledExecutorService scheduler, String nDid, String version) { private void startScheduledTask(ScheduledExecutorService scheduler, String nDid, String version) {
synchronized (lock) {
NoticeUserDto dto = sendOffLine(nDid);
sendEventToUser(dto);
addLogs(dto);
String clientName = "NJCN-" + nDid.substring(nDid.length() - 6);
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(() -> { ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(() -> {
System.out.println(nDid + "执行重连定时任务...");
DeviceLogDTO logDto = new DeviceLogDTO(); DeviceLogDTO logDto = new DeviceLogDTO();
logDto.setOperate(nDid + "第一阶段重连定时任务"); logDto.setOperate(nDid + "重连定时任务");
if (attemptCount < MAX_ATTEMPTS) { //判断客户端
System.out.println(nDid + "执行第一阶段重连定时任务,第 " + attemptCount + " 次尝试..."); boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
attemptCount++; if (mqttClient) {
csDeviceService.devAccessAskTemplate(nDid,version,attemptCount); csDeviceService.devAccessAskTemplate(nDid,version,1);
int status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus(); try {
Thread.sleep(2000);
Integer status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
if (Objects.equals(status,AccessEnum.ONLINE.getCode())){ if (Objects.equals(status,AccessEnum.ONLINE.getCode())){
logDto.setResult(1); logDto.setResult(1);
scheduler.shutdown(); scheduler.shutdown();
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,1);
return;
} else {
logDto.setResult(0);
//一个小时未连接上,则推送告警消息
MAX_WARNING_TIMES++;
if (MAX_WARNING_TIMES == 30) {
NoticeUserDto dto2 = sendConnectFail(nDid);
sendEventToUser(dto2);
addLogs(dto2);
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} }
} else { } else {
scheduler.shutdown(); //一个小时未连接上,则推送告警消息
attemptCount++; MAX_WARNING_TIMES++;
if (MAX_WARNING_TIMES == 30) {
NoticeUserDto dto2 = sendConnectFail(nDid);
sendEventToUser(dto2);
addLogs(dto2);
}
logDto.setResult(0); logDto.setResult(0);
startSecondScheduledTask(nDid,version);
} }
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
}, 0, 1, TimeUnit.MINUTES); }, 0, 2, TimeUnit.MINUTES);
}
} }
//启动第二个定时任务 //掉线通知
private void startSecondScheduledTask(String nDid, String version) { private NoticeUserDto sendOffLine(String nDid) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); NoticeUserDto dto = new NoticeUserDto();
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(() -> { dto.setTitle("设备离线");
System.out.println(nDid + "执行第二阶段重连定时任务..."); CsEquipmentDeliveryPO po = equipmentFeignClient.findDevByNDid(nDid).getData();
DeviceLogDTO logDto = new DeviceLogDTO(); DevDetailDTO devDetailDto = csLedgerFeignclient.queryDevDetail(po.getId()).getData();
logDto.setOperate(nDid + "第二阶段重连定时任务"); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
csDeviceService.devAccessAskTemplate(nDid,version,attemptCount++); LocalDateTime localDateTime = LocalDateTime.now();
int status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus(); String dateStr = localDateTime.format(fmt);
if (Objects.equals(status,AccessEnum.ONLINE.getCode())) { String content = String.format(devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName() + "" + dateStr + "离线");
logDto.setResult(1); dto.setContent(content);
scheduler.shutdown(); dto.setPushClientId(getEventUser(po.getId(),true));
} else { return dto;
logDto.setResult(0); }
//重连失败通知
private NoticeUserDto sendConnectFail(String nDid) {
NoticeUserDto dto = new NoticeUserDto();
dto.setTitle("设备接入失败");
CsEquipmentDeliveryPO po = equipmentFeignClient.findDevByNDid(nDid).getData();
DevDetailDTO devDetailDto = csLedgerFeignclient.queryDevDetail(po.getId()).getData();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now();
String dateStr = localDateTime.format(fmt);
String content = String.format(devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName() + "" + dateStr + "多次接入失败");
dto.setContent(content);
dto.setPushClientId(getEventUser(po.getId(),false));
return dto;
}
//日志记录
private void addLogs(NoticeUserDto noticeUserDto) {
DeviceLogDTO dto = new DeviceLogDTO();
dto.setUserName(noticeUserDto.getTitle());
dto.setOperate(noticeUserDto.getContent());
csLogsFeignClient.addUserLog(dto);
}
/**
* 获取所有需要推送的用户id
*/
public List<String> getEventUser(String devId, boolean isAdmin) {
List<User> adminUser = appUserFeignClient.getAdminInfo().getData();
List<String> adminList = adminUser.stream().map(User::getId).collect(Collectors.toList());
if (isAdmin) {
List<String> list = csDeviceUserFeignClient.findUserById(devId).getData();
adminList.addAll(list);
}
List<User> users = userFeignClient.appuserByIdList(adminList).getData();
return users.stream().map(User::getDevCode).filter(Objects::nonNull).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
}
public void sendEventToUser(NoticeUserDto noticeUserDto) {
try {
// 创建一个URL对象指定目标HTTPS接口地址
URL url = new URL("https://fc-mp-ff7b310f-94c9-4468-8260-109111c0a6b2.next.bspapp.com/push");
// 打开HTTPS连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求头指定Content-Type为application/json
connection.setRequestProperty("Content-Type", "application/json");
// 启用输出流以发送JSON数据
connection.setDoOutput(true);
// 将JSON数据写入输出流
OutputStream outputStream = connection.getOutputStream();
log.info(new Gson().toJson(noticeUserDto).replace("pushClientId", "push_clientid"));
outputStream.write(new Gson().toJson(noticeUserDto).replace("pushClientId", "push_clientid").getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
// 获取响应代码
int responseCode = connection.getResponseCode();
log.info("Response Code: " + responseCode);
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
// 打印响应内容
log.info("Response Content: " + response.toString());
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.getMessage();
} }
csLogsFeignClient.addUserLog(logDto);
}, 0, 10, TimeUnit.MINUTES);
} }
} }

View File

@@ -1,16 +0,0 @@
package com.njcn.access.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.access.pojo.po.CsSoftInfoPO;
/**
* <p>
* 系统软件表 Mapper 接口
* </p>
*
* @author xuyang
* @since 2023-08-09
*/
public interface CsSoftInfoMapper extends BaseMapper<CsSoftInfoPO> {
}

View File

@@ -1,47 +1,30 @@
//package com.njcn.access.runner; package com.njcn.access.runner;
//
//import com.njcn.access.service.ICsEquipmentDeliveryService; import com.njcn.redis.utils.RedisUtil;
//import com.njcn.access.service.ICsTopicService; import lombok.extern.slf4j.Slf4j;
//import com.njcn.access.service.impl.CsDeviceServiceImpl; import org.springframework.boot.ApplicationArguments;
//import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO; import org.springframework.boot.ApplicationRunner;
//import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component;
//import org.springframework.boot.ApplicationArguments;
//import org.springframework.boot.ApplicationRunner; import javax.annotation.Resource;
//import org.springframework.stereotype.Component;
// /**
//import javax.annotation.Resource; * 类的介绍:用来重新发起设备的接入,存在程序意外停止了,缓存失效导致无法更新装置的状态,所以需要在程序启动时发起设备的接入
//import java.util.List; *
//import java.util.Objects; * @author xuyang
// * @version 1.0.0
///** * @createTime 2023/8/28 13:57
// * 类的介绍:用来重新发起设备的接入,存在程序意外停止了,缓存失效导致无法更新装置的状态,所以需要在程序启动时发起设备的接入 */
// * @Component
// * @author xuyang @Slf4j
// * @version 1.0.0 public class AccessApplicationRunner implements ApplicationRunner {
// * @createTime 2023/8/28 13:57
// */ @Resource
//@Component private RedisUtil redisUtil;
//@Slf4j
//public class AccessApplicationRunner implements ApplicationRunner { @Override
// public void run(ApplicationArguments args) {
// @Resource redisUtil.saveByKeyWithExpire("autoAccess",null,60L);
// private CsDeviceServiceImpl csDeviceService; }
//
// @Resource }
// private ICsTopicService csTopicService;
//
// @Resource
// private ICsEquipmentDeliveryService csEquipmentDeliveryService;
//
// @Override
// public void run(ApplicationArguments args){
// List<CsEquipmentDeliveryPO> list = csEquipmentDeliveryService.getAll();
// list.forEach(item->{
// String version = csTopicService.getVersion(item.getNdid());
// if (!Objects.isNull(version)){
// csDeviceService.devAccess(item.getNdid(),version,1);
// }
// });
// }
//
//}

View File

@@ -0,0 +1,19 @@
package com.njcn.access.service;
/**
* @author xy
*/
public interface AskDeviceDataService {
void askDeviceRootPath(String nDid);
void askDeviceFileOrDir(String nDid, String name);
boolean downloadFile(String nDid, String name, Integer size, String fileCheck);
void rebootDevice(String nDid);
void createFolder(String nDid, String path);
void deleteFolder(String nDid, String path);
}

View File

@@ -14,6 +14,11 @@ import java.util.List;
public interface ICsDevModelService { public interface ICsDevModelService {
/**
* 初始化缓存模板信息
*/
void refreshDevModelCache();
/** /**
* 解析模板文件->入库 * 解析模板文件->入库
* @param file * @param file

View File

@@ -26,7 +26,7 @@ public interface ICsDeviceService {
Object getModel(String nDid); Object getModel(String nDid);
/** /**
* MQTT连接成功获取装置所用的模板信息 * 直连设备接入
* @param devAccessParam * @param devAccessParam
*/ */
void devAccess(DevAccessParam devAccessParam); void devAccess(DevAccessParam devAccessParam);

View File

@@ -1,17 +1,9 @@
package com.njcn.access.service; package com.njcn.access.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.access.pojo.param.DeviceStatusParam; import com.njcn.access.pojo.param.DeviceStatusParam;
import com.njcn.csdevice.pojo.param.CsEquipmentDeliveryAddParm;
import com.njcn.csdevice.pojo.param.CsEquipmentDeliveryAuditParm;
import com.njcn.csdevice.pojo.param.CsEquipmentDeliveryQueryParm;
import com.njcn.csdevice.pojo.param.ProjectEquipmentQueryParm;
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO; import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
import com.njcn.csdevice.pojo.vo.CsEquipmentDeliveryVO; import com.njcn.csdevice.pojo.vo.CsEquipmentDeliveryVO;
import com.njcn.csdevice.pojo.vo.DeviceManagerVO;
import com.njcn.csdevice.pojo.vo.ProjectEquipmentVO;
import java.util.List; import java.util.List;

View File

@@ -1,16 +0,0 @@
package com.njcn.access.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.access.pojo.po.CsSoftInfoPO;
/**
* <p>
* 系统软件表 服务类
* </p>
*
* @author xuyang
* @since 2023-08-09
*/
public interface ICsSoftInfoService extends IService<CsSoftInfoPO> {
}

View File

@@ -0,0 +1,276 @@
package com.njcn.access.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.access.api.CsTopicFeignClient;
import com.njcn.access.enums.AccessEnum;
import com.njcn.access.enums.TypeEnum;
import com.njcn.access.pojo.dto.ControlDto;
import com.njcn.access.pojo.dto.ReqAndResDto;
import com.njcn.access.pojo.dto.file.FileRedisDto;
import com.njcn.access.service.AskDeviceDataService;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.zlevent.pojo.dto.FileStreamDto;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
* @author xy
*/
@Service
@RequiredArgsConstructor
public class AskDeviceDataServiceImpl implements AskDeviceDataService {
private static final Logger log = LoggerFactory.getLogger(AskDeviceDataServiceImpl.class);
private final MqttPublisher publisher;
private final CsTopicFeignClient csTopicFeignClient;
private final RedisUtil redisUtil;
private static Integer mid = 1;
private static Integer range = 51200;
@Override
public void askDeviceRootPath(String nDid) {
Object object = getDeviceMid(nDid);
if (!Objects.isNull(object)) {
mid = (Integer) object;
}
ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
reqAndResParam.setMid(mid);
reqAndResParam.setDid(1);
reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
reqAndResParam.setExpire(-1);
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_13.getCode()));
String version = getVersion(nDid);
publisher.send("/Pfm/DevFileCmd/" + version + "/" + nDid, new Gson().toJson(reqAndResParam), 1, false);
mid = mid + 1;
if (mid > 10000) {
mid = 1;
}
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
}
@Override
public void askDeviceFileOrDir(String nDid, String name) {
Object object = getDeviceMid(nDid);
if (!Objects.isNull(object)) {
mid = (Integer) object;
}
ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
reqAndResParam.setMid(mid);
reqAndResParam.setDid(1);
reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
reqAndResParam.setExpire(-1);
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_8.getCode()));
String json = String.format("{\"Name\":\"%s\"}", name);
JSONObject jsonObject = JSONObject.fromObject(json);
reqAndResParam.setMsg(jsonObject);
String version = getVersion(nDid);
publisher.send("/Pfm/DevFileCmd/" + version + "/" + nDid, new Gson().toJson(reqAndResParam), 1, false);
mid = mid + 1;
if (mid > 10000) {
mid = 1;
}
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
}
@Override
public boolean downloadFile(String nDid, String name, Integer size, String fileCheck) {
boolean result = false;
try {
redisUtil.saveByKeyWithExpire("fileDowning:"+nDid,"fileDowning",300L);
redisUtil.saveByKeyWithExpire("fileCheck"+name,fileCheck,300L);
Object object = getDeviceMid(nDid);
if (!Objects.isNull(object)) {
mid = (Integer) object;
}
ReqAndResDto.Req reqAndResParam = getAllPojo(mid,name);
publisher.send("/Pfm/DevFileCmd/V1/"+nDid,new Gson().toJson(reqAndResParam),1,false);
//这里使用简单的轮询,但建议考虑更高效的机制
for (int i = 0; i < 120; i++) {
Thread.sleep(2000);
Object object2 = redisUtil.getObjectByKey("downloadFilePath:"+name);
if (!Objects.isNull(object2)) {
result = true;
break;
} else {
Object object3 = redisUtil.getObjectByKey(AppRedisKey.FILE_PART.concat(name));
if (!Objects.isNull(object3)) {
FileStreamDto dto = JSON.parseObject(JSON.toJSONString(object3), FileStreamDto.class);
String json = "{fileName:"+name+",allStep:"+dto.getTotal()+",nowStep:"+ (CollectionUtil.isEmpty(dto.getList())?0:dto.getList().size())+"}";
publisher.send("/Web/Progress/" + nDid, new Gson().toJson(json), 1, false);
}
}
}
mid = mid + 1;
if (mid > 10000) {
mid = 1;
}
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
} catch (Exception e) {
redisUtil.delete("fileDowning:"+nDid);
redisUtil.delete("fileCheck"+name);
throw new BusinessException(AlgorithmResponseEnum.FILE_DOWNLOAD_ERROR);
}
return result;
}
@Override
public void rebootDevice(String nDid) {
Object object = getDeviceMid(nDid);
if (!Objects.isNull(object)) {
mid = (Integer) object;
}
ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
reqAndResParam.setMid(mid);
reqAndResParam.setDid(0);
reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
reqAndResParam.setExpire(-1);
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_31.getCode()));
ControlDto controlDto = new ControlDto();
controlDto.setClDid(-1);
controlDto.setCmdType("reboot");
controlDto.setCmdParm("on");
reqAndResParam.setMsg(controlDto);
publisher.send("/Pfm/DevCmd/V1/" + nDid, new Gson().toJson(reqAndResParam), 1, false);
mid = mid + 1;
if (mid > 10000) {
mid = 1;
}
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
}
@Override
public void createFolder(String nDid, String path) {
Object object = getDeviceMid(nDid);
if (!Objects.isNull(object)) {
mid = (Integer) object;
}
ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
reqAndResParam.setMid(mid);
reqAndResParam.setDid(0);
reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
reqAndResParam.setExpire(-1);
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_12.getCode()));
String json = String.format("{\"Name\":\"%s\"}", path);
JSONObject jsonObject = JSONObject.fromObject(json);
reqAndResParam.setMsg(jsonObject);
publisher.send("/Pfm/DevFileCmd/V1/" + nDid, new Gson().toJson(reqAndResParam), 1, false);
mid = mid + 1;
if (mid > 10000) {
mid = 1;
}
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
}
@Override
public void deleteFolder(String nDid, String path) {
Object object = getDeviceMid(nDid);
if (!Objects.isNull(object)) {
mid = (Integer) object;
}
ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
reqAndResParam.setMid(mid);
reqAndResParam.setDid(0);
reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
reqAndResParam.setExpire(-1);
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_11.getCode()));
String json = String.format("{\"Name\":\"%s\"}", path);
JSONObject jsonObject = JSONObject.fromObject(json);
reqAndResParam.setMsg(jsonObject);
publisher.send("/Pfm/DevFileCmd/V1/" + nDid, new Gson().toJson(reqAndResParam), 1, false);
mid = mid + 1;
if (mid > 10000) {
mid = 1;
}
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
}
public Object getDeviceMid(String nDid) {
return redisUtil.getObjectByKey(AppRedisKey.DEVICE_MID + nDid);
}
public String getVersion(String nDid) {
return csTopicFeignClient.find(nDid).getData();
}
/**
* 全文件下载请求报文
*/
public ReqAndResDto.Req getAllPojo(Integer mid, String fileName) {
String json;
ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
reqAndResParam.setMid(mid);
reqAndResParam.setDid(0);
reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_9.getCode()));
reqAndResParam.setExpire(-1);
json = "{Name:\""+fileName+"\",TransferMode:"+(-1)+",Offset:"+(-1)+",Len:"+range+"}";
JSONObject jsonObject = JSONObject.fromObject(json);
reqAndResParam.setMsg(jsonObject);
return reqAndResParam;
}
/**
* 文件下载请求报文
*/
public ReqAndResDto.Req getPojo(Integer mid, String fileName, Integer step) {
String json;
ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
reqAndResParam.setMid(mid);
reqAndResParam.setDid(0);
reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_9.getCode()));
reqAndResParam.setExpire(-1);
json = "{Name:\""+fileName+"\",TransferMode:"+1+",Offset:"+(step*range)+",Len:"+range+"}";
JSONObject jsonObject = JSONObject.fromObject(json);
reqAndResParam.setMsg(jsonObject);
return reqAndResParam;
}
/**
* 根据装置响应来判断是否询问下一帧数据
*/
public void sendNextStep(String fileName, String id, int mid,int step) {
try {
for (int i = 1; i < 4; i++) {
if (step == 0 ){
Thread.sleep(5000);
} else {
Thread.sleep(2000);
}
FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey(AppRedisKey.DOWNLOAD + fileName + mid);
if (Objects.isNull(fileRedisDto)) {
FileRedisDto failDto = new FileRedisDto();
failDto.setCode(400);
redisUtil.saveByKeyWithExpire(AppRedisKey.DOWNLOAD + fileName + mid,failDto,10L);
} else {
if (Objects.equals(fileRedisDto.getCode(),200)) {
break;
} else {
log.info("" +i+"次尝试");
//尝试失败则设置code为400如果装置响应了则会将code置为200
FileRedisDto failDto = new FileRedisDto();
failDto.setCode(400);
redisUtil.saveByKeyWithExpire(AppRedisKey.DOWNLOAD + fileName + mid,failDto,10L);
ReqAndResDto.Req req = getPojo(mid,fileName,step);
publisher.send("/Pfm/DevFileCmd/V1/" + id, new Gson().toJson(req), 1, false);
}
}
}
} catch (Exception e) {
throw new BusinessException(AlgorithmResponseEnum.ASK_DEVICE_DIR_ERROR);
}
}
}

View File

@@ -2,6 +2,7 @@ package com.njcn.access.service.impl;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson; import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.github.tocrhz.mqtt.publisher.MqttPublisher; import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.access.enums.AccessEnum; import com.njcn.access.enums.AccessEnum;
@@ -20,13 +21,16 @@ import com.njcn.access.service.*;
import com.njcn.access.utils.CRC32Utils; import com.njcn.access.utils.CRC32Utils;
import com.njcn.access.utils.JsonUtil; import com.njcn.access.utils.JsonUtil;
import com.njcn.common.pojo.dto.DeviceLogDTO; import com.njcn.common.pojo.dto.DeviceLogDTO;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLogsFeignClient; import com.njcn.csdevice.api.CsLogsFeignClient;
import com.njcn.csdevice.api.DevModelFeignClient; import com.njcn.csdevice.api.DevModelFeignClient;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.pojo.po.*; import com.njcn.csdevice.pojo.po.*;
import com.njcn.csdevice.pojo.vo.CsEquipmentDeliveryVO; import com.njcn.csdevice.pojo.vo.CsEquipmentDeliveryVO;
import com.njcn.oss.constant.OssPath; import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil; import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil; import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.api.*; import com.njcn.system.api.*;
import com.njcn.system.enums.DicDataEnum; import com.njcn.system.enums.DicDataEnum;
@@ -38,12 +42,11 @@ import com.njcn.system.pojo.vo.DictTreeVO;
import com.njcn.web.utils.RequestUtil; import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.sql.Date; import java.sql.Date;
import java.util.*; import java.util.*;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@@ -62,42 +65,27 @@ import java.util.stream.Collectors;
public class CsDevModelServiceImpl implements ICsDevModelService { public class CsDevModelServiceImpl implements ICsDevModelService {
private final FileStorageUtil fileStorageUtil; private final FileStorageUtil fileStorageUtil;
private final DevModelFeignClient devModelFeignClient; private final DevModelFeignClient devModelFeignClient;
private final EpdFeignClient epdFeignClient; private final EpdFeignClient epdFeignClient;
private final DicDataFeignClient dicDataFeignClient; private final DicDataFeignClient dicDataFeignClient;
private final EleEvtFeignClient eleEvtFeignClient; private final EleEvtFeignClient eleEvtFeignClient;
private final ICsDataSetService csDataSetService; private final ICsDataSetService csDataSetService;
private final ICsDataArrayService csDataArrayService; private final ICsDataArrayService csDataArrayService;
private final CsDevModelMapper csDevModelMapper; private final CsDevModelMapper csDevModelMapper;
private final ICsLineModelService csLineModelService; private final ICsLineModelService csLineModelService;
private final ICsGroupService csGroupService; private final ICsGroupService csGroupService;
private final ICsGroArrService csGroArrService; private final ICsGroArrService csGroArrService;
private final CsLogsFeignClient csLogsFeignClient; private final CsLogsFeignClient csLogsFeignClient;
private final EleWaveFeignClient waveFeignClient; private final EleWaveFeignClient waveFeignClient;
private final DictTreeFeignClient dictTreeFeignClient; private final DictTreeFeignClient dictTreeFeignClient;
private final MqttPublisher publisher; private final MqttPublisher publisher;
private final ICsTopicService csTopicService; private final ICsTopicService csTopicService;
private final ICsEquipmentDeliveryService csEquipmentDeliveryService;
private final RedisUtil redisUtil; private final RedisUtil redisUtil;
private final MqttMessageHandler mqttMessageHandler; @Override
public void refreshDevModelCache() {
}
@Override @Override
@Transactional(rollbackFor = {Exception.class}) @Transactional(rollbackFor = {Exception.class})
@@ -154,30 +142,22 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
} }
} }
public static void main(String[] args) {
}
@Override @Override
public void uploadDevFile(MultipartFile file,String id,String path) { public void uploadDevFile(MultipartFile file,String id,String path) {
DeviceLogDTO logDto = null; Object object = redisUtil.getObjectByKey("uploading");
if (Objects.nonNull(object)) {
throw new BusinessException(AlgorithmResponseEnum.FILE_UPLOADING);
}
Object object2 = redisUtil.getObjectByKey("fileDowning:" + id);
if (Objects.nonNull(object2)) {
throw new BusinessException(AlgorithmResponseEnum.FILE_BUSY);
}
try { try {
byte[] bytes = file.getBytes(); byte[] bytes = file.getBytes();
int length = bytes.length; int length = bytes.length;
//生成文件校验码 //生成文件校验码
int crc = CRC32Utils.calculateCRC32(bytes,length,0xffffffff); int crc = CRC32Utils.calculateCRC32(bytes,length,0xffffffff);
String hexString = String.format("%08X", crc); String hexString = String.format("%08X", crc);
//判断nDid是否存在
CsEquipmentDeliveryVO csEquipmentDeliveryVO = csEquipmentDeliveryService.queryEquipmentBynDid(id);
logDto = new DeviceLogDTO();
logDto.setUserName(RequestUtil.getUserNickname());
logDto.setLoginName(RequestUtil.getUsername());
if (Objects.isNull(csEquipmentDeliveryVO.getNdid())) {
logDto.setResult(0);
logDto.setFailReason(AccessResponseEnum.NDID_NO_FIND.getMessage());
csLogsFeignClient.addUserLog(logDto);
throw new BusinessException(AccessResponseEnum.NDID_NO_FIND);
}
//存储文件至文件服务器 //存储文件至文件服务器
fileStorageUtil.uploadMultipart(file, OssPath.SYSTEM_TO_DEV + file.getOriginalFilename() + "_"); fileStorageUtil.uploadMultipart(file, OssPath.SYSTEM_TO_DEV + file.getOriginalFilename() + "_");
//获取版本 //获取版本
@@ -188,6 +168,10 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
//需要循环的次数 //需要循环的次数
int times = bytes.length / cap + 1; int times = bytes.length / cap + 1;
for (int i = 1; i <= times; i++) { for (int i = 1; i <= times; i++) {
//发送数据给前端
String json = "{fileName:"+file.getOriginalFilename()+",allStep:"+times+",nowStep:"+i+"}";
publisher.send("/Web/Progress/" + id, new Gson().toJson(json), 1, false);
DeviceLogDTO logDto = new DeviceLogDTO();
byte[] lsBytes; byte[] lsBytes;
if (length > 50*1024) { if (length > 50*1024) {
lsBytes = Arrays.copyOfRange(bytes, (i - 1) * cap, i * cap); lsBytes = Arrays.copyOfRange(bytes, (i - 1) * cap, i * cap);
@@ -197,10 +181,11 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
logDto.setResult(1); logDto.setResult(1);
length = length - cap; length = length - cap;
//判断是否重发 //判断是否重发
sendNextStep(logDto,path,file,bytes.length,lsBytes,(i-1)*cap,version,id,i,hexString); sendNextStep(logDto,path,file,bytes.length,lsBytes,(i-1)*cap,version,id,i,hexString,false);
FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey("uploadFileStep"); FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey(AppRedisKey.UPLOAD);
//重发之后判断继续循环还是跳出循环 //重发之后判断继续循环还是跳出循环
if (!Objects.equals(fileRedisDto.getCode(),200)) { if (!Objects.isNull(fileRedisDto) && !Objects.equals(fileRedisDto.getCode(),200)) {
redisUtil.delete("uploading");
break; break;
} }
} else { } else {
@@ -210,21 +195,24 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
logDto.setOperate(id + "设备上送文件,这是最后一帧,为第" + i + ""); logDto.setOperate(id + "设备上送文件,这是最后一帧,为第" + i + "");
logDto.setResult(1); logDto.setResult(1);
//判断是否重发 //判断是否重发
sendNextStep(logDto,path,file,bytes.length,lsBytes,(i-1)*cap,version,id,i,hexString); sendNextStep(logDto,path,file,bytes.length,lsBytes,(i-1)*cap,version,id,i,hexString,true);
} }
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
} }
} else { } else {
String json = "{fileName:"+file.getOriginalFilename()+",allStep:\""+1+"\",nowStep:"+1+"}";
publisher.send("/Web/Progress", new Gson().toJson(json), 1, false);
ReqAndResDto.Req req = getPojo(1,path,file,length,bytes,0,hexString); ReqAndResDto.Req req = getPojo(1,path,file,length,bytes,0,hexString);
publisher.send("/Pfm/DevFileCmd/" + version + "/" + id, new Gson().toJson(req), 1, false); publisher.send("/Pfm/DevFileCmd/" + version + "/" + id, new Gson().toJson(req), 1, false);
DeviceLogDTO logDto = new DeviceLogDTO();
logDto.setOperate(id + "系统上送文件,当前文件只有1帧"); logDto.setOperate(id + "系统上送文件,当前文件只有1帧");
logDto.setResult(1); logDto.setResult(1);
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
//判断是否重发 //判断是否重发
sendNextStep(logDto,path,file,length,bytes,0,version,id,1,hexString); sendNextStep(logDto,path,file,length,bytes,0,version,id,1,hexString,false);
} }
} catch (Exception e) { } catch (Exception e) {
assert logDto != null; DeviceLogDTO logDto = new DeviceLogDTO();
logDto.setResult(0); logDto.setResult(0);
logDto.setFailReason(AccessResponseEnum.UPLOAD_ERROR.getMessage()); logDto.setFailReason(AccessResponseEnum.UPLOAD_ERROR.getMessage());
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
@@ -250,6 +238,10 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
uploadFileDto.setLen(bytes.length); uploadFileDto.setLen(bytes.length);
uploadFileDto.setData(Base64.getEncoder().encodeToString(bytes)); uploadFileDto.setData(Base64.getEncoder().encodeToString(bytes));
uploadFileDto.setFileCheck(fileCheck); uploadFileDto.setFileCheck(fileCheck);
//生成当前帧文件校验码
int crc = CRC32Utils.calculateCRC32(bytes,bytes.length,0xffffffff);
String hexString = String.format("%08X", crc);
uploadFileDto.setStepFileCheck(hexString);
reqAndResParam.setMsg(uploadFileDto); reqAndResParam.setMsg(uploadFileDto);
return reqAndResParam; return reqAndResParam;
} }
@@ -257,24 +249,33 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
/** /**
* 根据装置响应来判断发送的内容 * 根据装置响应来判断发送的内容
*/ */
public void sendNextStep(DeviceLogDTO logDto, String path, MultipartFile file, int length, byte[] bytes, Integer offset, String version, String id, int mid, String fileCheck) { public void sendNextStep(DeviceLogDTO logDto, String path, MultipartFile file, int length, byte[] bytes, Integer offset, String version, String id, int mid, String fileCheck, boolean result) {
try { try {
for (int i = 0; i < 3; i++) { for (int i = 0; i < 30; i++) {
Thread.sleep(300); if (result) {
FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey("uploadFileStep"); Thread.sleep(10000);
} else {
Thread.sleep(2000);
}
FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey(AppRedisKey.UPLOAD);
if (Objects.isNull(fileRedisDto)) {
FileRedisDto fileRedis = new FileRedisDto(); FileRedisDto fileRedis = new FileRedisDto();
if (Objects.nonNull(fileRedisDto.getCode()) && fileRedisDto.getCode().equals(200)) { fileRedis.setCode(400);
fileRedis.setCode(200); redisUtil.saveByKeyWithExpire(AppRedisKey.UPLOAD,fileRedis,10L);
} else {
if (Objects.equals(fileRedisDto.getCode(),200)) {
break; break;
} else { } else {
FileRedisDto fileRedis = new FileRedisDto();
fileRedis.setCode(400);
redisUtil.saveByKeyWithExpire(AppRedisKey.UPLOAD,fileRedis,10L);
ReqAndResDto.Req req = getPojo(mid,path,file,length,bytes,offset,fileCheck); ReqAndResDto.Req req = getPojo(mid,path,file,length,bytes,offset,fileCheck);
publisher.send("/Pfm/DevFileCmd/" + version + "/" + id, new Gson().toJson(req), 1, false); publisher.send("/Pfm/DevFileCmd/" + version + "/" + id, new Gson().toJson(req), 1, false);
logDto.setOperate(id + "系统上送文件,装置响应失败,重新发送,这是第" + (i+1) + ""); logDto.setOperate(id + "系统上送文件,装置响应失败,重新发送,这是第" + (i+1) + "");
logDto.setResult(1); logDto.setResult(1);
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
fileRedis.setCode(fileRedisDto.getCode());
} }
redisUtil.saveByKeyWithExpire("uploadFileStep",fileRedis,10L); }
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
assert logDto != null; assert logDto != null;
@@ -1220,14 +1221,14 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
if (Objects.equals(code, DicDataEnum.CONNECT_DEV.getCode()) || Objects.isNull(code)){ if (Objects.equals(code, DicDataEnum.CONNECT_DEV.getCode()) || Objects.isNull(code)){
showName = "电网侧数据"; showName = "电网侧数据";
} else if (Objects.equals(code, DicDataEnum.PORTABLE.getCode())){ } else if (Objects.equals(code, DicDataEnum.PORTABLE.getCode())){
showName = "监测1数据"; showName = "监测1#数据";
} }
break; break;
case "Ds$Pqd$Stat$02": case "Ds$Pqd$Stat$02":
if (Objects.equals(code, DicDataEnum.CONNECT_DEV.getCode()) || Objects.isNull(code)){ if (Objects.equals(code, DicDataEnum.CONNECT_DEV.getCode()) || Objects.isNull(code)){
showName = "负载侧数据"; showName = "负载侧数据";
} else if (Objects.equals(code, DicDataEnum.PORTABLE.getCode())){ } else if (Objects.equals(code, DicDataEnum.PORTABLE.getCode())){
showName = "监测2数据"; showName = "监测2#数据";
} }
break; break;
//波形参数名称 //波形参数名称

View File

@@ -2,7 +2,6 @@ package com.njcn.access.service.impl;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils; import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.shaded.com.google.gson.Gson; import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@@ -11,12 +10,12 @@ import com.njcn.access.enums.AccessEnum;
import com.njcn.access.enums.AccessResponseEnum; import com.njcn.access.enums.AccessResponseEnum;
import com.njcn.access.enums.TypeEnum; import com.njcn.access.enums.TypeEnum;
import com.njcn.access.param.DevAccessParam; import com.njcn.access.param.DevAccessParam;
import com.njcn.access.pojo.RspDataDto;
import com.njcn.access.pojo.dto.AccessDto; import com.njcn.access.pojo.dto.AccessDto;
import com.njcn.access.pojo.dto.CsModelDto; import com.njcn.access.pojo.dto.CsModelDto;
import com.njcn.access.pojo.dto.ReqAndResDto; import com.njcn.access.pojo.dto.ReqAndResDto;
import com.njcn.access.pojo.param.DeviceStatusParam; import com.njcn.access.pojo.param.DeviceStatusParam;
import com.njcn.access.service.*; import com.njcn.access.service.*;
import com.njcn.access.utils.ChannelObjectUtil;
import com.njcn.access.utils.MqttUtil; import com.njcn.access.utils.MqttUtil;
import com.njcn.common.pojo.dto.DeviceLogDTO; import com.njcn.common.pojo.dto.DeviceLogDTO;
import com.njcn.common.pojo.enums.response.CommonResponseEnum; import com.njcn.common.pojo.enums.response.CommonResponseEnum;
@@ -36,7 +35,6 @@ import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.SysDicTreePO; import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.web.utils.RequestUtil; import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import net.sf.cglib.core.Local;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -60,40 +58,24 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
private static final Logger logger = LoggerFactory.getLogger(CsDeviceServiceImpl.class); private static final Logger logger = LoggerFactory.getLogger(CsDeviceServiceImpl.class);
private final EquipmentFeignClient equipmentFeignClient; private final EquipmentFeignClient equipmentFeignClient;
private final ICsEquipmentDeliveryService csEquipmentDeliveryService; private final ICsEquipmentDeliveryService csEquipmentDeliveryService;
private final DictTreeFeignClient dictTreeFeignClient; private final DictTreeFeignClient dictTreeFeignClient;
private final ICsLedgerService csLedgerService; private final ICsLedgerService csLedgerService;
private final ICsDevModelRelationService csDevModelRelationService; private final ICsDevModelRelationService csDevModelRelationService;
private final ICsLineService csLineService; private final ICsLineService csLineService;
private final IAppLineTopologyDiagramService appLineTopologyDiagramService; private final IAppLineTopologyDiagramService appLineTopologyDiagramService;
private final ICsDeviceUserService csDeviceUserService; private final ICsDeviceUserService csDeviceUserService;
private final MqttPublisher publisher; private final MqttPublisher publisher;
private final RedisUtil redisUtil; private final RedisUtil redisUtil;
private final MqttUtil mqttUtil; private final MqttUtil mqttUtil;
private final ICsTopicService csTopicService; private final ICsTopicService csTopicService;
private final DicDataFeignClient dicDataFeignClient; private final DicDataFeignClient dicDataFeignClient;
private final CsLogsFeignClient csLogsFeignClient; private final CsLogsFeignClient csLogsFeignClient;
private final ProcessFeignClient processFeignClient; private final ProcessFeignClient processFeignClient;
private final CsLinePOService csLinePOService; private final CsLinePOService csLinePOService;
private final CsDeviceUserPOService csDeviceUserPOService; private final CsDeviceUserPOService csDeviceUserPOService;
private final ICsDataSetService csDataSetService; private final ICsDataSetService csDataSetService;
private final ChannelObjectUtil channelObjectUtil;
@Override @Override
@Transactional(rollbackFor = {Exception.class}) @Transactional(rollbackFor = {Exception.class})
@@ -102,7 +84,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
DeviceLogDTO logDto = new DeviceLogDTO(); DeviceLogDTO logDto = new DeviceLogDTO();
logDto.setUserName(RequestUtil.getUserNickname()); logDto.setUserName(RequestUtil.getUserNickname());
logDto.setLoginName(RequestUtil.getUsername()); logDto.setLoginName(RequestUtil.getUsername());
logDto.setOperate("当前设备"+nDid+"状态判断"); logDto.setOperate("直连设备"+nDid+"注册");
logDto.setResult(1); logDto.setResult(1);
//1.判断nDid是否存在 //1.判断nDid是否存在
CsEquipmentDeliveryVO csEquipmentDeliveryVO = csEquipmentDeliveryService.queryEquipmentBynDid(nDid); CsEquipmentDeliveryVO csEquipmentDeliveryVO = csEquipmentDeliveryService.queryEquipmentBynDid(nDid);
@@ -112,13 +94,6 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
throw new BusinessException(AccessResponseEnum.NDID_NO_FIND); throw new BusinessException(AccessResponseEnum.NDID_NO_FIND);
} }
//判断是否已经注册过
if (!Objects.isNull(csEquipmentDeliveryVO.getNdid()) && Objects.equals(type,csEquipmentDeliveryVO.getProcess()) && Objects.equals(AccessEnum.ACCESS.getCode(),csEquipmentDeliveryVO.getStatus())){
logDto.setResult(0);
logDto.setFailReason(AccessResponseEnum.NDID_SAME_STEP.getMessage());
csLogsFeignClient.addUserLog(logDto);
throw new BusinessException(AccessResponseEnum.NDID_SAME_STEP);
}
//2.判断设备是否是直连设备 //2.判断设备是否是直连设备
SysDicTreePO sysDicTreePo = dictTreeFeignClient.queryById(csEquipmentDeliveryVO.getDevType()).getData(); SysDicTreePO sysDicTreePo = dictTreeFeignClient.queryById(csEquipmentDeliveryVO.getDevType()).getData();
if (Objects.isNull(sysDicTreePo)){ if (Objects.isNull(sysDicTreePo)){
@@ -134,7 +109,14 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
throw new BusinessException(AccessResponseEnum.DEV_IS_NOT_ZL); throw new BusinessException(AccessResponseEnum.DEV_IS_NOT_ZL);
} }
//3.判断客户端是否在线 //3.判断是否已经注册过
if (!Objects.isNull(csEquipmentDeliveryVO.getNdid()) && Objects.equals(type,csEquipmentDeliveryVO.getProcess()) && Objects.equals(AccessEnum.ACCESS.getCode(),csEquipmentDeliveryVO.getStatus())){
logDto.setResult(0);
logDto.setFailReason(AccessResponseEnum.NDID_SAME_STEP.getMessage());
csLogsFeignClient.addUserLog(logDto);
throw new BusinessException(AccessResponseEnum.NDID_SAME_STEP);
}
//4.判断客户端是否在线
String clientName = "NJCN-" + nDid.substring(nDid.length() - 6); String clientName = "NJCN-" + nDid.substring(nDid.length() - 6);
boolean mqttClient = mqttUtil.judgeClientOnline(clientName); boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
if (!mqttClient){ if (!mqttClient){
@@ -143,7 +125,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
throw new BusinessException(AccessResponseEnum.MISSING_CLIENT); throw new BusinessException(AccessResponseEnum.MISSING_CLIENT);
} }
//4.判断当前流程是否是合法的 //5.判断当前流程是否是合法的
if (csEquipmentDeliveryVO.getProcess() > type){ if (csEquipmentDeliveryVO.getProcess() > type){
logDto.setResult(0); logDto.setResult(0);
logDto.setFailReason(AccessResponseEnum.PROCESS_SAME_ERROR.getMessage()); logDto.setFailReason(AccessResponseEnum.PROCESS_SAME_ERROR.getMessage());
@@ -153,10 +135,10 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
logDto.setFailReason(AccessResponseEnum.PROCESS_MISSING_ERROR.getMessage()); logDto.setFailReason(AccessResponseEnum.PROCESS_MISSING_ERROR.getMessage());
throw new BusinessException(AccessResponseEnum.PROCESS_MISSING_ERROR); throw new BusinessException(AccessResponseEnum.PROCESS_MISSING_ERROR);
} }
//5.询问设备支持的主题信息 //6.询问设备支持的主题信息
//将支持的主题入库 //将支持的主题入库
askTopic(nDid); askTopic(nDid);
//6.MQTT询问装置用的模板并判断库中是否存在模板 //7.MQTT询问装置用的模板并判断库中是否存在模板
//存在则建立关系;不存在则告警出来 //存在则建立关系;不存在则告警出来
SysDicTreePO dictData = dictTreeFeignClient.queryById(csEquipmentDeliveryVO.getDevModel()).getData(); SysDicTreePO dictData = dictTreeFeignClient.queryById(csEquipmentDeliveryVO.getDevModel()).getData();
if (Objects.isNull(dictData)){ if (Objects.isNull(dictData)){
@@ -203,7 +185,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
DeviceLogDTO logDto = new DeviceLogDTO(); DeviceLogDTO logDto = new DeviceLogDTO();
logDto.setUserName(RequestUtil.getUserNickname()); logDto.setUserName(RequestUtil.getUserNickname());
logDto.setLoginName(RequestUtil.getUsername()); logDto.setLoginName(RequestUtil.getUsername());
logDto.setOperate("设备"+devAccessParam.getNDid()+"注册"); logDto.setOperate("设备"+devAccessParam.getNDid()+"接入");
logDto.setResult(1); logDto.setResult(1);
try { try {
//获取版本 //获取版本
@@ -219,7 +201,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
csLedgerParam.setLevel(2); csLedgerParam.setLevel(2);
csLedgerParam.setSort(0); csLedgerParam.setSort(0);
csLedgerService.addLedgerTree(csLedgerParam); csLedgerService.addLedgerTree(csLedgerParam);
List<CsModelDto> modelId = objectToList(redisUtil.getObjectByKey(AppRedisKey.MODEL + devAccessParam.getNDid())); List<CsModelDto> modelId = channelObjectUtil.objectToList(redisUtil.getObjectByKey(AppRedisKey.MODEL + devAccessParam.getNDid()),CsModelDto.class);
//2.新增装置-模板关系、获取电能质量的逻辑设备id //2.新增装置-模板关系、获取电能质量的逻辑设备id
for (CsModelDto item : modelId) { for (CsModelDto item : modelId) {
CsDevModelRelationAddParm csDevModelRelationAddParm = new CsDevModelRelationAddParm(); CsDevModelRelationAddParm csDevModelRelationAddParm = new CsDevModelRelationAddParm();
@@ -240,16 +222,34 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
po.setClDid(0); po.setClDid(0);
if (Objects.equals(DicDataEnum.GRID_SIDE.getCode(),location)){ if (Objects.equals(DicDataEnum.GRID_SIDE.getCode(),location)){
po.setLineId(devAccessParam.getNDid() + "1"); po.setLineId(devAccessParam.getNDid() + "1");
String id = Objects.requireNonNull(modelId.stream().filter(it -> Objects.equals(it.getDid(), 2)).findFirst().orElse(null)).getModelId();
po.setDataModelId(id);
//获取模板下数据集
List<CsDataSet> dataSets = csDataSetService.getDataSetData(id);
String dataSetId = Objects.requireNonNull(dataSets.stream().filter(it -> Objects.equals(it.getClDev(), 1)&&Objects.equals(it.getType(), 2)).findFirst().orElse(null)).getId();
po.setDataSetId(dataSetId);
param.setId(devAccessParam.getNDid() + "1"); param.setId(devAccessParam.getNDid() + "1");
appLineTopologyDiagramPo.setLineId(devAccessParam.getNDid() + "1"); appLineTopologyDiagramPo.setLineId(devAccessParam.getNDid() + "1");
po.setClDid(1); po.setClDid(1);
} else if (Objects.equals(DicDataEnum.LOAD_SIDE.getCode(),location)){ } else if (Objects.equals(DicDataEnum.LOAD_SIDE.getCode(),location)){
po.setLineId(devAccessParam.getNDid() + "2"); po.setLineId(devAccessParam.getNDid() + "2");
String id = Objects.requireNonNull(modelId.stream().filter(it -> Objects.equals(it.getDid(), 2)).findFirst().orElse(null)).getModelId();
po.setDataModelId(id);
//获取模板下数据集
List<CsDataSet> dataSets = csDataSetService.getDataSetData(id);
String dataSetId = Objects.requireNonNull(dataSets.stream().filter(it -> Objects.equals(it.getClDev(), 2)&&Objects.equals(it.getType(), 2)).findFirst().orElse(null)).getId();
po.setDataSetId(dataSetId);
param.setId(devAccessParam.getNDid() + "2"); param.setId(devAccessParam.getNDid() + "2");
appLineTopologyDiagramPo.setLineId(devAccessParam.getNDid() + "2"); appLineTopologyDiagramPo.setLineId(devAccessParam.getNDid() + "2");
po.setClDid(2); po.setClDid(2);
} else { } else {
po.setLineId(devAccessParam.getNDid() + "0"); po.setLineId(devAccessParam.getNDid() + "0");
String id = Objects.requireNonNull(modelId.stream().filter(it -> Objects.equals(it.getDid(), 1)).findFirst().orElse(null)).getModelId();
po.setDataModelId(id);
//获取模板下数据集
List<CsDataSet> dataSets = csDataSetService.getDataSetData(id);
String dataSetId = Objects.requireNonNull(dataSets.stream().filter(it -> Objects.equals(it.getClDev(), 0)&&Objects.equals(it.getType(), 0)).findFirst().orElse(null)).getId();
po.setDataSetId(dataSetId);
param.setId(devAccessParam.getNDid() + "0"); param.setId(devAccessParam.getNDid() + "0");
appLineTopologyDiagramPo.setLineId(devAccessParam.getNDid() + "0"); appLineTopologyDiagramPo.setLineId(devAccessParam.getNDid() + "0");
} }
@@ -288,7 +288,6 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
csEquipmentDeliveryService.updateStatusBynDid(devAccessParam.getNDid(), AccessEnum.REGISTERED.getCode()); csEquipmentDeliveryService.updateStatusBynDid(devAccessParam.getNDid(), AccessEnum.REGISTERED.getCode());
//7.发起自动接入请求 //7.发起自动接入请求
devAccessAskTemplate(devAccessParam.getNDid(),version,1); devAccessAskTemplate(devAccessParam.getNDid(),version,1);
//8.删除redis监测点模板信息 //8.删除redis监测点模板信息
redisUtil.delete(AppRedisKey.MODEL + devAccessParam.getNDid()); redisUtil.delete(AppRedisKey.MODEL + devAccessParam.getNDid());
redisUtil.delete(AppRedisKey.LINE + devAccessParam.getNDid()); redisUtil.delete(AppRedisKey.LINE + devAccessParam.getNDid());
@@ -380,17 +379,25 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
DeviceLogDTO logDto = new DeviceLogDTO(); DeviceLogDTO logDto = new DeviceLogDTO();
logDto.setUserName(RequestUtil.getUserNickname()); logDto.setUserName(RequestUtil.getUserNickname());
logDto.setLoginName(RequestUtil.getUsername()); logDto.setLoginName(RequestUtil.getUsername());
logDto.setOperate("设备"+nDid+"注册"); logDto.setOperate("便携式设备"+nDid+"注册、接入");
logDto.setResult(1); logDto.setResult(1);
try { try {
Thread.sleep(1000); Thread.sleep(2000);
//获取版本 //获取版本
String version = csTopicService.getVersion(nDid); String version = csTopicService.getVersion(nDid);
CsEquipmentDeliveryVO vo = equipmentFeignClient.queryEquipmentByndid(nDid).getData(); CsEquipmentDeliveryVO vo = equipmentFeignClient.queryEquipmentByndid(nDid).getData();
List<CsLinePO> csLinePoList = new ArrayList<>(); List<CsLinePO> csLinePoList = new ArrayList<>();
//1.根据模板获取监测点个数,插入监测点表 //1.录入装置台账信息
Thread.sleep(1000); CsLedgerParam csLedgerParam = new CsLedgerParam();
List<CsModelDto> modelList = objectToList(redisUtil.getObjectByKey(AppRedisKey.MODEL + nDid)); csLedgerParam.setId(vo.getId());
csLedgerParam.setPid("0");
csLedgerParam.setName(vo.getName());
csLedgerParam.setLevel(2);
csLedgerParam.setSort(0);
csLedgerService.addLedgerTree(csLedgerParam);
//2.根据模板获取监测点个数,插入监测点表
Thread.sleep(2000);
List<CsModelDto> modelList = channelObjectUtil.objectToList(redisUtil.getObjectByKey(AppRedisKey.MODEL + nDid),CsModelDto.class);
if (CollUtil.isEmpty(modelList)){ if (CollUtil.isEmpty(modelList)){
try { try {
throwExceptionAndLog(AccessResponseEnum.MODEL_ERROR, logDto); throwExceptionAndLog(AccessResponseEnum.MODEL_ERROR, logDto);
@@ -402,31 +409,37 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
list.forEach(item->{ list.forEach(item->{
CsLinePO po = new CsLinePO(); CsLinePO po = new CsLinePO();
po.setLineId(nDid + item.getClDev().toString()); po.setLineId(nDid + item.getClDev().toString());
po.setName(item.getClDev().toString() + "监测点"); po.setName(item.getClDev().toString() + "#监测点");
po.setStatus(1); po.setStatus(1);
po.setClDid(item.getClDev()); po.setClDid(item.getClDev());
po.setDeviceId(vo.getId()); po.setDeviceId(vo.getId());
//防止主键重复 //防止主键重复
QueryWrapper<CsLinePO> qw = new QueryWrapper(); QueryWrapper<CsLinePO> qw = new QueryWrapper<>();
qw.eq("line_id",po.getLineId()); qw.eq("line_id",po.getLineId());
if(csLineService.getBaseMapper().selectList(qw).isEmpty()){ if(csLineService.getBaseMapper().selectList(qw).isEmpty()){
csLinePoList.add(po); csLinePoList.add(po);
} }
//3.生成台账树监测点数据
CsLedgerParam param = new CsLedgerParam();
param.setId(nDid + item.getClDev().toString());
param.setPid(vo.getId());
param.setName(item.getClDev().toString() + "#监测点");
param.setLevel(3);
param.setSort(0);
csLedgerService.addLedgerTree(param);
}); });
csLineService.saveBatch(csLinePoList); csLineService.saveBatch(csLinePoList);
//2.生成装置和模板的关系表 //4.生成装置和模板的关系表
CsDevModelRelationAddParm csDevModelRelationAddParm = new CsDevModelRelationAddParm(); CsDevModelRelationAddParm csDevModelRelationAddParm = new CsDevModelRelationAddParm();
csDevModelRelationAddParm.setDevId(vo.getId()); csDevModelRelationAddParm.setDevId(vo.getId());
csDevModelRelationAddParm.setModelId(modelList.get(0).getModelId()); csDevModelRelationAddParm.setModelId(modelList.get(0).getModelId());
csDevModelRelationAddParm.setDid(modelList.get(0).getDid()); csDevModelRelationAddParm.setDid(modelList.get(0).getDid());
csDevModelRelationService.addDevModelRelation(csDevModelRelationAddParm); csDevModelRelationService.addDevModelRelation(csDevModelRelationAddParm);
//3.修改装置状态为注册状态 //5.发起自动接入请求
csEquipmentDeliveryService.updateStatusBynDid(nDid, AccessEnum.REGISTERED.getCode());
//4.发起自动接入请求
devAccessAskTemplate(nDid,version,1); devAccessAskTemplate(nDid,version,1);
//5.存储日志 //6.存储日志
csLogsFeignClient.addUserLog(logDto); csLogsFeignClient.addUserLog(logDto);
//6.存储设备调试日志表 //7.存储设备调试日志表
CsEquipmentProcessPO csEquipmentProcess = new CsEquipmentProcessPO(); CsEquipmentProcessPO csEquipmentProcess = new CsEquipmentProcessPO();
csEquipmentProcess.setDevId(nDid); csEquipmentProcess.setDevId(nDid);
csEquipmentProcess.setOperator(RequestUtil.getUserIndex()); csEquipmentProcess.setOperator(RequestUtil.getUserIndex());
@@ -435,7 +448,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
csEquipmentProcess.setProcess(4); csEquipmentProcess.setProcess(4);
csEquipmentProcess.setStatus(1); csEquipmentProcess.setStatus(1);
processFeignClient.add(csEquipmentProcess); processFeignClient.add(csEquipmentProcess);
//7.删除redis监测点模板信息 //8.删除redis监测点模板信息
redisUtil.delete(AppRedisKey.MODEL + nDid); redisUtil.delete(AppRedisKey.MODEL + nDid);
redisUtil.delete(AppRedisKey.LINE + nDid); redisUtil.delete(AppRedisKey.LINE + nDid);
} catch (Exception e) { } catch (Exception e) {
@@ -531,7 +544,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
publisher.send("/Pfm/DevCmd/"+version+"/"+nDid,new Gson().toJson(reqAndResParam),1,false); publisher.send("/Pfm/DevCmd/"+version+"/"+nDid,new Gson().toJson(reqAndResParam),1,false);
//接收到模板,判断模板是否存在,替换模板,发起接入 //接收到模板,判断模板是否存在,替换模板,发起接入
Thread.sleep(2000); Thread.sleep(2000);
List<CsModelDto> modelId = objectToList(redisUtil.getObjectByKey(AppRedisKey.MODEL + nDid)); List<CsModelDto> modelId = channelObjectUtil.objectToList(redisUtil.getObjectByKey(AppRedisKey.MODEL + nDid),CsModelDto.class);
if (CollUtil.isNotEmpty(modelId)) { if (CollUtil.isNotEmpty(modelId)) {
CsEquipmentDeliveryVO vo = equipmentFeignClient.queryEquipmentByndid(nDid).getData(); CsEquipmentDeliveryVO vo = equipmentFeignClient.queryEquipmentByndid(nDid).getData();
//重新录入装置和模板关系信息 //重新录入装置和模板关系信息
@@ -543,9 +556,13 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
po.setUpdateTime(LocalDateTime.now()); po.setUpdateTime(LocalDateTime.now());
csDevModelRelationService.addRelation(po); csDevModelRelationService.addRelation(po);
} }
//fixme 修改监测点使用的模板和数据集
//发起接入 //发起接入
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_5.getCode())); reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_5.getCode()));
publisher.send("/Pfm/DevCmd/"+version+"/"+nDid, new Gson().toJson(reqAndResParam),1,false); publisher.send("/Pfm/DevCmd/"+version+"/"+nDid, new Gson().toJson(reqAndResParam),1,false);
//录波任务倒计时
redisUtil.saveByKeyWithExpire("startFile",null,120L);
result = true; result = true;
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
@@ -587,28 +604,4 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
logger.info("注册报文为:{}", new Gson().toJson(reqAndResParam)); logger.info("注册报文为:{}", new Gson().toJson(reqAndResParam));
publisher.send("/Pfm/DevReg/"+nDid, new Gson().toJson(reqAndResParam),1,false); publisher.send("/Pfm/DevReg/"+nDid, new Gson().toJson(reqAndResParam),1,false);
} }
public List<CsModelDto> objectToList(Object object) {
List<CsModelDto> urlList = new ArrayList<>();
if (object != null) {
if (object instanceof ArrayList<?>) {
for (Object o : (List<?>) object) {
urlList.add((CsModelDto) o);
}
}
}
return urlList;
}
public List<RspDataDto.LdevInfo> objectToList2(Object object) {
List<RspDataDto.LdevInfo> urlList = new ArrayList<>();
if (object != null) {
if (object instanceof ArrayList<?>) {
for (Object o : (List<?>) object) {
urlList.add((RspDataDto.LdevInfo) o);
}
}
}
return urlList;
}
} }

View File

@@ -32,9 +32,13 @@ public class CsLedgerServiceImpl extends ServiceImpl<CsLedgerMapper, CsLedger> i
if (Objects.equals(csLedgerParam.getPid(),"9999999")){ if (Objects.equals(csLedgerParam.getPid(),"9999999")){
csLedger.setPid("0"); csLedger.setPid("0");
csLedger.setPids("0"); csLedger.setPids("0");
} else {
if (Objects.isNull(fatherCsLedger)) {
csLedger.setPids("0");
} else { } else {
csLedger.setPids(fatherCsLedger.getPids() + "," + csLedgerParam.getPid()); csLedger.setPids(fatherCsLedger.getPids() + "," + csLedgerParam.getPid());
} }
}
this.save(csLedger); this.save(csLedger);
return csLedger; return csLedger;
} }

View File

@@ -1,20 +0,0 @@
package com.njcn.access.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.access.mapper.CsSoftInfoMapper;
import com.njcn.access.pojo.po.CsSoftInfoPO;
import com.njcn.access.service.ICsSoftInfoService;
import org.springframework.stereotype.Service;
/**
* <p>
* 系统软件表 服务实现类
* </p>
*
* @author xuyang
* @since 2023-08-09
*/
@Service
public class CsSoftInfoServiceImpl extends ServiceImpl<CsSoftInfoMapper, CsSoftInfoPO> implements ICsSoftInfoService {
}

View File

@@ -0,0 +1,48 @@
//package com.njcn.stat.controller;
//
//import com.njcn.common.pojo.annotation.OperateInfo;
//import com.njcn.common.pojo.enums.common.LogEnum;
//import com.njcn.common.pojo.enums.response.CommonResponseEnum;
//import com.njcn.common.pojo.response.HttpResult;
//import com.njcn.common.utils.HttpResultUtil;
//import com.njcn.mq.message.AppAutoDataMessage;
//import com.njcn.stat.service.IWlRecordService;
//import com.njcn.web.controller.BaseController;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiImplicitParam;
//import io.swagger.annotations.ApiOperation;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.validation.annotation.Validated;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
///**
// * 类的介绍:
// *
// * @author xuyang
// * @version 1.0.0
// * @createTime 2024/9/10 9:23
// */
//@Slf4j
//@RestController
//@RequestMapping("/record")
//@Api(tags = "便携式基础数据录入")
//@AllArgsConstructor
//public class WlRecordController extends BaseController {
//
// private final IWlRecordService wlRecordService;
//
// @OperateInfo(info = LogEnum.BUSINESS_COMMON)
// @PostMapping("/addOrUpdateBaseData")
// @ApiOperation("新增或更新装置基础数据")
// @ApiImplicitParam(name = "appAutoDataMessage", value = "数据实体", required = true)
// public HttpResult<String> addOrUpdateBaseData(@RequestBody @Validated AppAutoDataMessage appAutoDataMessage){
// String methodDescribe = getMethodDescribe("addOrUpdateBaseData");
// wlRecordService.addOrUpdateBaseData(appAutoDataMessage);
// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
// }
//
//}

View File

@@ -1,67 +1,67 @@
package com.njcn.stat.listener; //package com.njcn.stat.listener;
//
import cn.hutool.core.collection.CollectionUtil; //import cn.hutool.core.collection.CollectionUtil;
import com.njcn.common.pojo.exception.BusinessException; //import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.redis.pojo.enums.AppRedisKey; //import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil; //import com.njcn.redis.utils.RedisUtil;
import com.njcn.stat.enums.StatResponseEnum; //import com.njcn.stat.enums.StatResponseEnum;
import com.njcn.system.api.EpdFeignClient; //import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.pojo.dto.EpdDTO; //import com.njcn.system.pojo.dto.EpdDTO;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; //import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order; //import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.Message; //import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener; //import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer; //import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
//
import javax.annotation.Resource; //import javax.annotation.Resource;
import java.util.HashMap; //import java.util.HashMap;
import java.util.List; //import java.util.List;
import java.util.Map; //import java.util.Map;
//
/** ///**
* @author hongawen // * @author hongawen
* @version 1.0.0 // * @version 1.0.0
* @date 2022年04月02日 14:31 // * @date 2022年04月02日 14:31
*/ // */
@Slf4j //@Slf4j
@Component //@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener { //public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
//
@Resource // @Resource
private EpdFeignClient epdFeignClient; // private EpdFeignClient epdFeignClient;
//
@Resource // @Resource
private RedisUtil redisUtil; // private RedisUtil redisUtil;
//
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) { // public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer); // super(listenerContainer);
} // }
//
//
/** // /**
* 针对redis数据失效事件进行数据处理 // * 针对redis数据失效事件进行数据处理
* 注意message.toString()可以获取失效的key // * 注意message.toString()可以获取失效的key
*/ // */
@Override // @Override
@Order(0) // @Order(0)
public void onMessage(Message message, byte[] pattern) { // public void onMessage(Message message, byte[] pattern) {
if (StringUtils.isBlank(message.toString())) { // if (StringUtils.isBlank(message.toString())) {
return; // return;
} // }
//判断失效的key // //判断失效的key
String expiredKey = message.toString(); // String expiredKey = message.toString();
if(expiredKey.equals(AppRedisKey.ELE_EPD_PQD)){ // if(expiredKey.equals(AppRedisKey.ELE_EPD_PQD)){
Map<String,String> map = new HashMap<>(); // Map<String,String> map = new HashMap<>();
List<EpdDTO> list = epdFeignClient.findAll().getData(); // List<EpdDTO> list = epdFeignClient.findAll().getData();
if (CollectionUtil.isEmpty(list)){ // if (CollectionUtil.isEmpty(list)){
throw new BusinessException(StatResponseEnum.DICT_NULL); // throw new BusinessException(StatResponseEnum.DICT_NULL);
} // }
list.forEach(item->{ // list.forEach(item->{
map.put(item.getDictName(),item.getTableName()); // map.put(item.getDictName(),item.getTableName());
}); // });
redisUtil.saveByKeyWithExpire(AppRedisKey.ELE_EPD_PQD,map,3600L); // redisUtil.saveByKeyWithExpire(AppRedisKey.ELE_EPD_PQD,map,3600L);
} // }
} // }
} //}

View File

@@ -0,0 +1,12 @@
//package com.njcn.stat.service;
//
//import com.njcn.mq.message.AppAutoDataMessage;
//
///**
// * @author xy
// */
//public interface IWlRecordService {
//
// void addOrUpdateBaseData(AppAutoDataMessage appAutoDataMessage);
//
//}

View File

@@ -99,36 +99,36 @@ public class StatServiceImpl implements IStatService {
lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appAutoDataMessage.getId())), Map.class).get(appAutoDataMessage.getMsg().getClDid().toString()).toString(); lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appAutoDataMessage.getId())), Map.class).get(appAutoDataMessage.getMsg().getClDid().toString()).toString();
} }
} }
//缓存指标和influxDB表关系 // //缓存指标和influxDB表关系
Object object2 = redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD); // Object object2 = redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD);
if(Objects.isNull(object2)) { // if(Objects.isNull(object2)) {
saveData(); // saveData();
} // }
//获取当前设备信息 //获取当前设备信息
if (CollectionUtil.isNotEmpty(list)){ if (CollectionUtil.isNotEmpty(list)){
List<String> recordList = new ArrayList<>(); List<String> recordList = new ArrayList<>();
for (AppAutoDataMessage.DataArray item : list) { for (AppAutoDataMessage.DataArray item : list) {
switch (item.getDataAttr()) { switch (item.getDataAttr()) {
case 1: case 1:
log.info("{}-->处理最大值", po.getNdid()); log.info("{}-->处理最大值", po.getNdid() + appAutoDataMessage.getDid() + appAutoDataMessage.getMsg().getClDid());
dataArrayParam.setStatMethod("max"); dataArrayParam.setStatMethod("max");
break; break;
case 2: case 2:
log.info("{}-->处理最小值", po.getNdid()); log.info("{}-->处理最小值", po.getNdid() + appAutoDataMessage.getDid() + appAutoDataMessage.getMsg().getClDid());
dataArrayParam.setStatMethod("min"); dataArrayParam.setStatMethod("min");
break; break;
case 3: case 3:
log.info("{}-->处理avg", po.getNdid()); log.info("{}-->处理avg", po.getNdid() + appAutoDataMessage.getDid() + appAutoDataMessage.getMsg().getClDid());
dataArrayParam.setStatMethod("avg"); dataArrayParam.setStatMethod("avg");
break; break;
case 4: case 4:
log.info("{}-->处理cp95", po.getNdid()); log.info("{}-->处理cp95", po.getNdid() + appAutoDataMessage.getDid() + appAutoDataMessage.getMsg().getClDid());
dataArrayParam.setStatMethod("cp95"); dataArrayParam.setStatMethod("cp95");
break; break;
default: default:
break; break;
} }
Object object = redisUtil.getObjectByKey(appAutoDataMessage.getId() + appAutoDataMessage.getDid() + appAutoDataMessage.getMsg().getClDid()); Object object = redisUtil.getObjectByKey(appAutoDataMessage.getId() + appAutoDataMessage.getDid() + appAutoDataMessage.getMsg().getClDid() + dataArrayParam.getStatMethod());
List<CsDataArray> dataArrayList; List<CsDataArray> dataArrayList;
if (Objects.isNull(object)){ if (Objects.isNull(object)){
dataArrayList = saveModelData(dataArrayParam); dataArrayList = saveModelData(dataArrayParam);
@@ -168,29 +168,29 @@ public class StatServiceImpl implements IStatService {
} }
} }
} }
redisUtil.saveByKeyWithExpire(AppRedisKey.LINE_POSITION+id,map,600L); redisUtil.saveByKey(AppRedisKey.LINE_POSITION+id,map);
} }
/** // /**
* 缓存字典和influxDB表关系 // * 缓存字典和influxDB表关系
*/ // */
public void saveData() { // public void saveData() {
Map<String,String> map = new HashMap<>(); // Map<String,String> map = new HashMap<>();
List<EpdDTO> list = epdFeignClient.findAll().getData(); // List<EpdDTO> list = epdFeignClient.findAll().getData();
if (CollectionUtil.isEmpty(list)){ // if (CollectionUtil.isEmpty(list)){
throw new BusinessException(StatResponseEnum.DICT_NULL); // throw new BusinessException(StatResponseEnum.DICT_NULL);
} // }
list.forEach(item->{ // list.forEach(item->{
map.put(item.getDictName(),item.getTableName()); // map.put(item.getDictName(),item.getTableName());
}); // });
redisUtil.saveByKeyWithExpire(AppRedisKey.ELE_EPD_PQD,map,3600L); // redisUtil.saveByKeyWithExpire(AppRedisKey.ELE_EPD_PQD,map,3600L);
} // }
/** /**
* 缓存设备模板信息 * 缓存设备模板信息
*/ */
public List<CsDataArray> saveModelData(DataArrayParam dataArrayParam) { public List<CsDataArray> saveModelData(DataArrayParam dataArrayParam) {
String key = dataArrayParam.getId() + dataArrayParam.getDid() + dataArrayParam.getCldId(); String key = dataArrayParam.getId() + dataArrayParam.getDid() + dataArrayParam.getCldId() + dataArrayParam.getStatMethod();
List<CsDataArray> dataArrayList = dataArrayFeignClient.findListByParam(dataArrayParam).getData(); List<CsDataArray> dataArrayList = dataArrayFeignClient.findListByParam(dataArrayParam).getData();
if (CollectionUtil.isEmpty(dataArrayList)){ if (CollectionUtil.isEmpty(dataArrayList)){
throw new BusinessException(StatResponseEnum.DATA_ARRAY_NULL); throw new BusinessException(StatResponseEnum.DATA_ARRAY_NULL);
@@ -214,10 +214,10 @@ public class StatServiceImpl implements IStatService {
if (!Objects.equals(dataArrayList.size(),floats.size())){ if (!Objects.equals(dataArrayList.size(),floats.size())){
throw new BusinessException(StatResponseEnum.ARRAY_DATA_NOT_MATCH); throw new BusinessException(StatResponseEnum.ARRAY_DATA_NOT_MATCH);
} }
//判断字典数据是否存在 // //判断字典数据是否存在
if (Objects.isNull(redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD))){ // if (Objects.isNull(redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD))){
saveData(); // saveData();
} // }
Map<String,String> map = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD)), Map.class); Map<String,String> map = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD)), Map.class);
for (int i = 0; i < dataArrayList.size(); i++) { for (int i = 0; i < dataArrayList.size(); i++) {
String tableName = map.get(dataArrayList.get(i).getName()); String tableName = map.get(dataArrayList.get(i).getName());

View File

@@ -0,0 +1,44 @@
//package com.njcn.stat.service.impl;
//
//import com.njcn.csdevice.api.EquipmentFeignClient;
//import com.njcn.csdevice.api.WlRecordFeignClient;
//import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
//import com.njcn.csdevice.pojo.po.WlRecord;
//import com.njcn.mq.message.AppAutoDataMessage;
//import com.njcn.stat.service.IWlRecordService;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.BeanUtils;
//import org.springframework.stereotype.Service;
//
///**
// * 类的介绍:
// *
// * @author xuyang
// * @version 1.0.0
// * @createTime 2023/8/14 9:32
// */
//@Service
//@Slf4j
//@AllArgsConstructor
//public class WlRecordServiceImpl implements IWlRecordService{
//
// private final EquipmentFeignClient equipmentFeignClient;
//
// private final WlRecordFeignClient wlRecordFeignClient;
//
// @Override
// public void addOrUpdateBaseData(AppAutoDataMessage appAutoDataMessage) {
// WlRecord wlRecord = new WlRecord();
// CsEquipmentDeliveryPO po = equipmentFeignClient.findDevByNDid(appAutoDataMessage.getId()).getData();
// AppAutoDataMessage.DataArray dataArray = appAutoDataMessage.getMsg().getDataArray().get(0);
// BeanUtils.copyProperties(dataArray, wlRecord);
// wlRecord.setDevId(po.getId());
// wlRecord.setLineId(po.getNdid() + appAutoDataMessage.getMsg().getClDid());
// wlRecord.setGcDataPath(dataArray.getPrjDataPath());
// if (dataArray.getPrjTimeEnd() == -1) {
// wlRecord.setEndTime(null);
// }
// wlRecordFeignClient.addBaseData(wlRecord);
// }
//}

View File

@@ -6,6 +6,7 @@ import com.njcn.mq.message.AppEventMessage;
import com.njcn.zlevent.api.fallback.EventClientFallbackFactory; import com.njcn.zlevent.api.fallback.EventClientFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/** /**
* @author xy * @author xy
@@ -15,4 +16,8 @@ public interface EventFeignClient {
@PostMapping("/analysis") @PostMapping("/analysis")
HttpResult<String> analysis(AppEventMessage appEventMessage); HttpResult<String> analysis(AppEventMessage appEventMessage);
@PostMapping("/portableData")
HttpResult<String> getPortableData(@RequestBody AppEventMessage appEventMessage);
} }

View File

@@ -0,0 +1,19 @@
package com.njcn.zlevent.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.mq.message.AppEventMessage;
import com.njcn.zlevent.api.fallback.EvtErrorClientFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.CS_ZL_EVENT_BOOT, path = "/csDevErrEvt", fallbackFactory = EvtErrorClientFallbackFactory.class,contextId = "csDevErrEvt")
public interface EvtErrorFeignClient {
@PostMapping("/errorEvent")
HttpResult<String> insertErrorEvent(AppEventMessage appEventMessage);
}

View File

@@ -3,14 +3,14 @@ package com.njcn.zlevent.api;
import com.njcn.common.pojo.constant.ServerInfo; import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult; import com.njcn.common.pojo.response.HttpResult;
import com.njcn.mq.message.AppEventMessage; import com.njcn.mq.message.AppEventMessage;
import com.njcn.zlevent.api.fallback.EventClientFallbackFactory; import com.njcn.zlevent.api.fallback.WaveClientFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
/** /**
* @author xy * @author xy
*/ */
@FeignClient(value = ServerInfo.CS_ZL_EVENT_BOOT, path = "/wave", fallbackFactory = EventClientFallbackFactory.class,contextId = "wave") @FeignClient(value = ServerInfo.CS_ZL_EVENT_BOOT, path = "/wave", fallbackFactory = WaveClientFallbackFactory.class,contextId = "wave")
public interface WaveFeignClient { public interface WaveFeignClient {
@PostMapping("/analysis") @PostMapping("/analysis")

View File

@@ -30,6 +30,13 @@ public class EventClientFallbackFactory implements FallbackFactory<EventFeignCli
log.error("{}异常,降级处理,异常为:{}","数据解析",cause.toString()); log.error("{}异常,降级处理,异常为:{}","数据解析",cause.toString());
throw new BusinessException(finalExceptionEnum); throw new BusinessException(finalExceptionEnum);
} }
@Override
public HttpResult<String> getPortableData(AppEventMessage appEventMessage) {
log.error("{}异常,降级处理,异常为:{}","便携式设备数据记录动作",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
}; };
} }
} }

View File

@@ -0,0 +1,35 @@
package com.njcn.zlevent.api.fallback;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.mq.message.AppEventMessage;
import com.njcn.zlevent.api.EvtErrorFeignClient;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author xy
*/
@Slf4j
@Component
public class EvtErrorClientFallbackFactory implements FallbackFactory<EvtErrorFeignClient> {
@Override
public EvtErrorFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new EvtErrorFeignClient() {
@Override
public HttpResult<String> insertErrorEvent(AppEventMessage appEventMessage) {
log.error("{}异常,降级处理,异常为:{}","异常事件统计",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -5,6 +5,7 @@ import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult; import com.njcn.common.pojo.response.HttpResult;
import com.njcn.mq.message.AppEventMessage; import com.njcn.mq.message.AppEventMessage;
import com.njcn.zlevent.api.EventFeignClient; import com.njcn.zlevent.api.EventFeignClient;
import com.njcn.zlevent.api.WaveFeignClient;
import feign.hystrix.FallbackFactory; import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -14,16 +15,16 @@ import org.springframework.stereotype.Component;
*/ */
@Slf4j @Slf4j
@Component @Component
public class WaveClientFallbackFactory implements FallbackFactory<EventFeignClient> { public class WaveClientFallbackFactory implements FallbackFactory<WaveFeignClient> {
@Override @Override
public EventFeignClient create(Throwable cause) { public WaveFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常 //判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK; Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) { if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause(); BusinessException businessException = (BusinessException) cause.getCause();
} }
Enum<?> finalExceptionEnum = exceptionEnum; Enum<?> finalExceptionEnum = exceptionEnum;
return new EventFeignClient() { return new WaveFeignClient() {
@Override @Override
public HttpResult<String> analysis(AppEventMessage appEventMessage) { public HttpResult<String> analysis(AppEventMessage appEventMessage) {

View File

@@ -5,6 +5,7 @@ import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
/** /**
* 类的介绍: * 类的介绍:
@@ -22,6 +23,6 @@ public class FileStreamDto implements Serializable {
private Integer frameLen; private Integer frameLen;
private List<Integer> list; private Set<Integer> list;
} }

View File

@@ -12,8 +12,15 @@ import lombok.Data;
@Data @Data
public class WaveTimeDto { public class WaveTimeDto {
/**
* 文件名
*/
private String fileName;
private String deviceId; private String deviceId;
private String nDid;
private String lineId; private String lineId;
private String startTime; private String startTime;
@@ -22,4 +29,9 @@ public class WaveTimeDto {
private String location; private String location;
/**
* 等级
*/
private String level;
} }

View File

@@ -0,0 +1,18 @@
package com.njcn.zlevent.pojo.param;
import com.njcn.web.pojo.param.BaseParam;
import lombok.Data;
/**
* @author xy
*/
@Data
public class ErrorEventParam extends BaseParam {
private String nDid;
private String startTime;
private String endTime;
}

View File

@@ -0,0 +1,46 @@
package com.njcn.zlevent.pojo.po;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
* 装置异常事件统计
* </p>
*
* @author xy
* @since 2024-09-12
*/
@Data
@TableName("cs_dev_err_evt")
public class CsDevErrEvt implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
private String id;
/**
* 设备识别码
*/
private String ndid;
/**
* 事件发生时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime evtTime;
/**
* 事件code编码
*/
private String code;
}

View File

@@ -0,0 +1,66 @@
package com.njcn.zlevent.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.common.utils.LogUtil;
import com.njcn.mq.message.AppEventMessage;
import com.njcn.web.controller.BaseController;
import com.njcn.zlevent.pojo.param.ErrorEventParam;
import com.njcn.zlevent.pojo.po.CsDevErrEvt;
import com.njcn.zlevent.service.ICsDevErrEvtService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 装置异常事件统计 前端控制器
* </p>
*
* @author xy
* @since 2024-09-12
*/
@RestController
@Slf4j
@RequestMapping("/csDevErrEvt")
@Api(tags = "装置异常事件处理")
@AllArgsConstructor
public class CsDevErrEvtController extends BaseController {
private final ICsDevErrEvtService csDevErrEvtService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/errorEvent")
@ApiOperation("异常事件统计")
@ApiImplicitParam(name = "appEventMessage", value = "数据实体", required = true)
public HttpResult<String> insertErrorEvent(@RequestBody AppEventMessage appEventMessage){
String methodDescribe = getMethodDescribe("insertErrorEvent");
csDevErrEvtService.insertErrorEvent(appEventMessage);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/list")
@ApiOperation("查询异常事件列表分页")
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
public HttpResult<Page<CsDevErrEvt>> getList(@RequestBody @Validated ErrorEventParam param) {
String methodDescribe = getMethodDescribe("getList");
LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, param);
Page<CsDevErrEvt> list = csDevErrEvtService.getList(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
}

View File

@@ -28,7 +28,7 @@ import org.springframework.web.bind.annotation.RestController;
@Slf4j @Slf4j
@RestController @RestController
@RequestMapping("/event") @RequestMapping("/event")
@Api(tags = "暂态事件处理") @Api(tags = "事件处理")
@AllArgsConstructor @AllArgsConstructor
public class EventController extends BaseController { public class EventController extends BaseController {
@@ -44,4 +44,14 @@ public class EventController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
} }
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/portableData")
@ApiOperation("便携式数据事件")
@ApiImplicitParam(name = "appEventMessage", value = "数据实体", required = true)
public HttpResult<String> getPortableData(@RequestBody AppEventMessage appEventMessage){
String methodDescribe = getMethodDescribe("getPortableData");
eventService.getPortableData(appEventMessage);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
} }

View File

@@ -36,7 +36,7 @@ public class WaveController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON) @OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/analysis") @PostMapping("/analysis")
@ApiOperation("录波解析") @ApiOperation("录波事件")
@ApiImplicitParam(name = "appEventMessage", value = "数据实体", required = true) @ApiImplicitParam(name = "appEventMessage", value = "数据实体", required = true)
public HttpResult<String> analysis(@RequestBody AppEventMessage appEventMessage){ public HttpResult<String> analysis(@RequestBody AppEventMessage appEventMessage){
String methodDescribe = getMethodDescribe("analysis"); String methodDescribe = getMethodDescribe("analysis");

View File

@@ -0,0 +1,26 @@
package com.njcn.zlevent.init;
import com.njcn.redis.utils.RedisUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @author xy
*
* 程序重启设置任务,消费历史录波文件
*/
@Slf4j
@Component
@AllArgsConstructor
public class InitEventFiles implements CommandLineRunner {
private final RedisUtil redisUtil;
@Override
public void run(String... args) {
redisUtil.saveByKeyWithExpire("startFile",null,120L);
}
}

View File

@@ -4,18 +4,22 @@ import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.gson.Gson; import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.github.tocrhz.mqtt.publisher.MqttPublisher; import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.access.api.CsTopicFeignClient;
import com.njcn.access.enums.AccessEnum; import com.njcn.access.enums.AccessEnum;
import com.njcn.access.enums.TypeEnum; import com.njcn.access.enums.TypeEnum;
import com.njcn.access.pojo.dto.ReqAndResDto; import com.njcn.access.pojo.dto.ReqAndResDto;
import com.njcn.access.pojo.dto.file.FileRedisDto;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
import com.njcn.redis.pojo.enums.AppRedisKey; import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil; import com.njcn.redis.utils.RedisUtil;
import com.njcn.stat.enums.StatResponseEnum; import com.njcn.stat.enums.StatResponseEnum;
import com.njcn.system.api.EpdFeignClient; import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.pojo.dto.EpdDTO; import com.njcn.system.pojo.dto.EpdDTO;
import com.njcn.zlevent.pojo.dto.FileStreamDto; import com.njcn.zlevent.pojo.dto.FileStreamDto;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import com.njcn.zlevent.service.ICsWaveAnalysisService;
import com.njcn.zlevent.utils.RemoveInfoUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -26,10 +30,7 @@ import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream; import java.util.stream.IntStream;
/** /**
@@ -43,21 +44,23 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
@Resource @Resource
private EpdFeignClient epdFeignClient; private EpdFeignClient epdFeignClient;
@Resource @Resource
private RedisUtil redisUtil; private RedisUtil redisUtil;
@Resource
private CsTopicFeignClient csTopicFeignClient;
@Resource @Resource
private MqttPublisher publisher; private MqttPublisher publisher;
@Resource
private RemoveInfoUtils removeInfoUtils;
@Resource
private ICsWaveAnalysisService csWaveAnalysisService;
@Resource
private EquipmentFeignClient equipmentFeignClient;
private static Integer mid = 1;
private static Integer range = 51200;
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) { public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer); super(listenerContainer);
} }
/** /**
* 针对redis数据失效事件进行数据处理 * 针对redis数据失效事件进行数据处理
* 注意message.toString()可以获取失效的key * 注意message.toString()可以获取失效的key
@@ -91,35 +94,180 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
int end = dto.getTotal(); int end = dto.getTotal();
IntStream.rangeClosed(start, end) IntStream.rangeClosed(start, end)
.filter(i -> !dto.getList().contains(i)) .filter(i -> !dto.getList().contains(i))
.forEach(missingNumber -> { .forEach(missingList::add);
log.info("缺失的数字:{}",missingNumber); if (CollectionUtil.isNotEmpty(missingList)) {
missingList.add(missingNumber); downloadFile(missingList,dto.getNDid(),fileName);
}
}
//项目重启或者接入经过120s开始处理历史录波文件
else if (expiredKey.startsWith("startFile")) {
List<CsEquipmentDeliveryPO> list = equipmentFeignClient.getAll().getData();
if (CollectionUtil.isNotEmpty(list)) {
list.forEach(item->{
redisUtil.delete("handleEvent:" + item.getNdid());
//处理缓存数据
csWaveAnalysisService.channelWave(item.getNdid());
}); });
redisUtil.saveByKey(AppRedisKey.FILE_PART_MISSING.concat(fileName), missingList); }
Integer offset = (missingList.get(0) - 1) * dto.getFrameLen(); }
askMissingFileStream(dto.getNDid(),missingList.get(0),fileName,offset,dto.getFrameLen()); //手动文件下载
else if (expiredKey.startsWith(AppRedisKey.FILE_DOWN_TIME)) {
List<Integer> missingList = new ArrayList<>();
String fileName = expiredKey.split(AppRedisKey.FILE_DOWN_TIME)[1];
Object object1 = redisUtil.getObjectByKey(AppRedisKey.FILE_PART.concat(fileName));
FileStreamDto dto = JSON.parseObject(JSON.toJSONString(object1), FileStreamDto.class);
int start = 1;
int end = dto.getTotal();
IntStream.rangeClosed(start, end)
.filter(i -> !dto.getList().contains(i))
.forEach(missingList::add);
if (CollectionUtil.isNotEmpty(missingList)) {
webDownloadFile(missingList,dto.getNDid(),fileName);
}
} }
} }
//界面请求缺失的数据
public void webDownloadFile( List<Integer> missingList, String nDid, String name) {
for (Integer missingNumber : missingList) {
int i = missingNumber - 1;
Object object = getDeviceMid(nDid);
if (!Objects.isNull(object)) {
mid = (Integer) object;
}
ReqAndResDto.Req reqAndResParam = getPojo(mid,name,i);
publisher.send("/Pfm/DevFileCmd/V1/"+nDid,new Gson().toJson(reqAndResParam),1,false);
//判断是否重发
webSendNextStep(name,nDid,mid,i);
FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey(AppRedisKey.DOWNLOAD + name + mid);
//重发之后判断继续循环还是跳出循环
if (!Objects.isNull(fileRedisDto) && !Objects.equals(fileRedisDto.getCode(),200)) {
break;
}
mid = mid + 1;
if (mid > 10000) {
mid = 1;
}
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
}
}
public void askMissingFileStream(String nDid, Integer mid, String fileName, Integer offset, Integer len) { //录波文件请求缺失的数据
String version = csTopicFeignClient.find(nDid).getData(); public void downloadFile( List<Integer> missingList, String nDid, String name) {
for (Integer missingNumber : missingList) {
int i = missingNumber - 1;
Object object = getDeviceMid(nDid);
if (!Objects.isNull(object)) {
mid = (Integer) object;
}
ReqAndResDto.Req reqAndResParam = getPojo(mid,name,i);
publisher.send("/Pfm/DevFileCmd/V1/"+nDid,new Gson().toJson(reqAndResParam),1,false);
//判断是否重发
sendNextStep(name,nDid,mid,i);
FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey(AppRedisKey.DOWNLOAD + name + mid);
//重发之后判断继续循环还是跳出循环
if (!Objects.isNull(fileRedisDto) && !Objects.equals(fileRedisDto.getCode(),200)) {
//判断重读还是丢弃
removeInfoUtils.retryEventInfo(nDid,name);
break;
}
mid = mid + 1;
if (mid > 10000) {
mid = 1;
}
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
}
}
public Object getDeviceMid(String nDid) {
return redisUtil.getObjectByKey(AppRedisKey.DEVICE_MID + nDid);
}
/**
* 文件下载请求报文
*/
public ReqAndResDto.Req getPojo(Integer mid, String fileName, Integer step) {
String json;
ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req(); ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
reqAndResParam.setMid(mid); reqAndResParam.setMid(mid);
reqAndResParam.setDid(0); reqAndResParam.setDid(0);
reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode()); reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_9.getCode())); reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_9.getCode()));
reqAndResParam.setExpire(-1); reqAndResParam.setExpire(-1);
String json = "{Name:\""+fileName+"\",Offset:"+offset+",Len:"+len+"}"; json = "{Name:\""+fileName+"\",TransferMode:"+1+",Offset:"+(step*range)+",Len:"+range+"}";
JSONObject jsonObject = JSONObject.fromObject(json); JSONObject jsonObject = JSONObject.fromObject(json);
reqAndResParam.setMsg(jsonObject); reqAndResParam.setMsg(jsonObject);
publisher.send("/Pfm/DevFileCmd/"+version+"/"+nDid,new Gson().toJson(reqAndResParam),1,false); return reqAndResParam;
log.info("请求文件流报文:" + new Gson().toJson(reqAndResParam));
} }
/**
* web端根据装置响应来判断是否询问下一帧数据
*/
public void webSendNextStep(String fileName, String id, int mid,int step) {
try {
for (int i = 1; i <= 30; i++) {
if (step == 0 ){
Thread.sleep(5000);
} else {
Thread.sleep(2000);
}
FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey(AppRedisKey.DOWNLOAD + fileName + mid);
if (Objects.isNull(fileRedisDto)) {
FileRedisDto failDto = new FileRedisDto();
failDto.setCode(400);
redisUtil.saveByKeyWithExpire(AppRedisKey.DOWNLOAD + fileName + mid,failDto,10L);
} else {
if (Objects.equals(fileRedisDto.getCode(),200)) {
break;
} else {
log.info("" +i+"次尝试");
//尝试失败则设置code为400如果装置响应了则会将code置为200
FileRedisDto failDto = new FileRedisDto();
failDto.setCode(400);
redisUtil.saveByKeyWithExpire(AppRedisKey.DOWNLOAD + fileName + mid,failDto,10L);
ReqAndResDto.Req req = getPojo(mid,fileName,step);
publisher.send("/Pfm/DevFileCmd/V1/" + id, new Gson().toJson(req), 1, false);
}
}
}
} catch (Exception e) {
throw new BusinessException(AlgorithmResponseEnum.FILE_DOWNLOAD_ERROR);
}
}
/**
* 根据装置响应来判断是否询问下一帧数据
*/
public void sendNextStep(String fileName, String id, int mid,int step) {
try {
for (int i = 1; i <= 11; i++) {
if (step == 0 ){
Thread.sleep(5000 * i);
} else {
Thread.sleep(2000 * i);
}
FileRedisDto fileRedisDto = (FileRedisDto) redisUtil.getObjectByKey(AppRedisKey.DOWNLOAD + fileName + mid);
if (Objects.isNull(fileRedisDto)) {
FileRedisDto failDto = new FileRedisDto();
failDto.setCode(400);
redisUtil.saveByKeyWithExpire(AppRedisKey.DOWNLOAD + fileName + mid,failDto,10L);
} else {
if (Objects.equals(fileRedisDto.getCode(),200)) {
break;
} else {
log.info("" +i+"次尝试");
//尝试失败则设置code为400如果装置响应了则会将code置为200
FileRedisDto failDto = new FileRedisDto();
failDto.setCode(400);
redisUtil.saveByKeyWithExpire(AppRedisKey.DOWNLOAD + fileName + mid,failDto,4L*i);
ReqAndResDto.Req req = getPojo(mid,fileName,step);
publisher.send("/Pfm/DevFileCmd/V1/" + id, new Gson().toJson(req), 1, false);
}
}
}
} catch (Exception e) {
throw new BusinessException(AlgorithmResponseEnum.FILE_DOWNLOAD_ERROR);
}
}
} }

View File

@@ -0,0 +1,22 @@
package com.njcn.zlevent.mapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.user.pojo.vo.RoleVO;
import com.njcn.zlevent.pojo.po.CsDevErrEvt;
import org.apache.ibatis.annotations.Param;
/**
* <p>
* 装置异常事件统计 Mapper 接口
* </p>
*
* @author xy
* @since 2024-09-12
*/
public interface CsDevErrEvtMapper extends BaseMapper<CsDevErrEvt> {
Page<CsDevErrEvt> page(@Param("page")Page<CsDevErrEvt> page, @Param("ew") QueryWrapper<CsDevErrEvt> queryWrapper);
}

View File

@@ -0,0 +1,10 @@
<?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.zlevent.mapper.CsDevErrEvtMapper">
<select id="page" resultType="CsDevErrEvt">
SELECT
evt.*
FROM cs_dev_err_evt evt
WHERE ${ew.sqlSegment}
</select>
</mapper>

View File

@@ -0,0 +1,27 @@
package com.njcn.zlevent.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.mq.message.AppEventMessage;
import com.njcn.zlevent.pojo.param.ErrorEventParam;
import com.njcn.zlevent.pojo.po.CsDevErrEvt;
/**
* <p>
* 装置异常事件统计 服务类
* </p>
*
* @author xy
* @since 2024-09-12
*/
public interface ICsDevErrEvtService extends IService<CsDevErrEvt> {
/**
* 将装置推送的异常事件统计,目前先入库
* @param appEventMessage
*/
void insertErrorEvent(AppEventMessage appEventMessage);
Page<CsDevErrEvt> getList(ErrorEventParam param);
}

View File

@@ -20,4 +20,6 @@ public interface ICsWaveAnalysisService {
*/ */
void analysis(AppEventMessage appEventMessage); void analysis(AppEventMessage appEventMessage);
void channelWave(String nDid);
} }

View File

@@ -18,7 +18,7 @@ public interface ICsWaveService extends IService<CsWave> {
* @param fileName 文件名称 * @param fileName 文件名称
* @return * @return
*/ */
int findCountByName(String fileName); boolean findCountByName(String fileName);
/** /**
* 修改文件状态 * 修改文件状态

View File

@@ -17,4 +17,12 @@ public interface IEventService {
*/ */
void analysis(AppEventMessage appEventMessage); void analysis(AppEventMessage appEventMessage);
/**
* 便携式设备基础数据
* 1.装置发起数据记录开始动作,库中新增数据;
* 2.装置发起数据记录结束动作,库中更新数据;
* @param appEventMessage
*/
void getPortableData(AppEventMessage appEventMessage);
} }

View File

@@ -56,13 +56,13 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsEventMapper, CsEventPO> im
try { try {
List<AppEventMessage.DataArray> dataArray = appEventMessage.getMsg().getDataArray(); List<AppEventMessage.DataArray> dataArray = appEventMessage.getMsg().getDataArray();
for (AppEventMessage.DataArray item : dataArray) { for (AppEventMessage.DataArray item : dataArray) {
eventTime = eventService.timeFormat(item.getDataTimeSec(),item.getDataTimeUSec());
//事件入库 //事件入库
CsEventPO csEvent = new CsEventPO(); CsEventPO csEvent = new CsEventPO();
csEvent.setId(id); csEvent.setId(id);
csEvent.setDeviceId(po.getId()); csEvent.setDeviceId(po.getId());
csEvent.setProcess(po.getProcess()); csEvent.setProcess(po.getProcess());
csEvent.setCode(item.getCode()); csEvent.setCode(item.getCode());
eventTime = eventService.timeFormat(item.getDataTimeSec(),item.getDataTimeUSec());
csEvent.setStartTime(eventTime); csEvent.setStartTime(eventTime);
tag = item.getName(); tag = item.getName();
csEvent.setTag(tag); csEvent.setTag(tag);
@@ -74,7 +74,6 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsEventMapper, CsEventPO> im
} }
if (CollectionUtil.isNotEmpty(list1)){ if (CollectionUtil.isNotEmpty(list1)){
csEventService.saveBatch(list1); csEventService.saveBatch(list1);
}
//推送事件逻辑处理 && cs_event_user入库 && 修改字典中告警事件的编码 //推送事件逻辑处理 && cs_event_user入库 && 修改字典中告警事件的编码
for (AppEventMessage.DataArray item : dataArray) { for (AppEventMessage.DataArray item : dataArray) {
if (Objects.isNull(item.getCode())){ if (Objects.isNull(item.getCode())){
@@ -89,6 +88,7 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsEventMapper, CsEventPO> im
epdFeignClient.update(updateParam); epdFeignClient.update(updateParam);
} }
} }
}
} catch (Exception e) { } catch (Exception e) {
CsEventLogs csEventLogs = new CsEventLogs(); CsEventLogs csEventLogs = new CsEventLogs();
csEventLogs.setDeviceId(po.getId()); csEventLogs.setDeviceId(po.getId());

View File

@@ -0,0 +1,88 @@
package com.njcn.zlevent.service.impl;
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.db.constant.DbConstant;
import com.njcn.mq.message.AppEventMessage;
import com.njcn.user.pojo.vo.RoleVO;
import com.njcn.web.factory.PageFactory;
import com.njcn.zlevent.mapper.CsDevErrEvtMapper;
import com.njcn.zlevent.pojo.param.ErrorEventParam;
import com.njcn.zlevent.pojo.po.CsDevErrEvt;
import com.njcn.zlevent.service.ICsDevErrEvtService;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 装置异常事件统计 服务实现类
* </p>
*
* @author xy
* @since 2024-09-12
*/
@Service
public class CsDevErrEvtServiceImpl extends ServiceImpl<CsDevErrEvtMapper, CsDevErrEvt> implements ICsDevErrEvtService {
@Override
public void insertErrorEvent(AppEventMessage appEventMessage) {
List<CsDevErrEvt> list = new ArrayList<>();
List<AppEventMessage.DataArray> dataArrayList = appEventMessage.getMsg().getDataArray();
for (AppEventMessage.DataArray dataArray : dataArrayList) {
CsDevErrEvt evt = new CsDevErrEvt();
evt.setNdid(appEventMessage.getId());
evt.setEvtTime(timeFormat(dataArray.getDataTimeSec(),dataArray.getDataTimeUSec()));
evt.setCode(dataArray.getCode());
list.add(evt);
}
this.saveBatch(list);
}
@Override
public Page<CsDevErrEvt> getList(ErrorEventParam param) {
// 构造时间字符串
QueryWrapper<CsDevErrEvt> queryWrapper = new QueryWrapper<>();
queryWrapper.between("evt.evt_time",param.getStartTime() + " 00:00:00",param.getEndTime() + " 23:59:59");
queryWrapper.orderBy(true, false, "evt.evt_time");
if (ObjectUtil.isNotNull(param)) {
//查询参数不为空,进行条件填充
if (StrUtil.isNotBlank(param.getSearchValue())) {
//用户表提供用户名、登录名 模糊查询
queryWrapper
.and(par -> par.like("evt.ndid", param.getSearchValue()));
}
}
return this.baseMapper.page(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), queryWrapper);
}
/**
* 时间转换
*/
public LocalDateTime timeFormat(Long time1, Long time2) {
String time;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
time1 = time1 - 8*3600;
long t1 = time1 * 1000000 + time2;
String time1String = String.valueOf(t1);
String time11 = time1String.substring(time1String.length() - 6);
String time111 = time1String.substring(0,time1String.length() - 6);
String formatTime1 = format.format(Long.parseLong(time111) * 1000);
if (time2 == 0){
time = formatTime1 + ".000000";
} else {
time = formatTime1 + "." + time11;
}
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
return LocalDateTime.parse(time, fmt);
}
}

View File

@@ -7,9 +7,12 @@ import com.njcn.access.api.CsTopicFeignClient;
import com.njcn.access.enums.AccessEnum; import com.njcn.access.enums.AccessEnum;
import com.njcn.access.enums.TypeEnum; import com.njcn.access.enums.TypeEnum;
import com.njcn.access.pojo.dto.ReqAndResDto; import com.njcn.access.pojo.dto.ReqAndResDto;
import com.njcn.access.utils.ChannelObjectUtil;
import com.njcn.access.utils.MqttUtil;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLineFeignClient; import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient; import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.pojo.po.CsLinePO; import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.mq.message.AppEventMessage; import com.njcn.mq.message.AppEventMessage;
import com.njcn.redis.pojo.enums.AppRedisKey; import com.njcn.redis.pojo.enums.AppRedisKey;
@@ -24,6 +27,7 @@ import com.njcn.zlevent.service.ICsWaveAnalysisService;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@@ -43,22 +47,18 @@ import java.util.stream.Collectors;
public class CsWaveAnalysisServiceImpl implements ICsWaveAnalysisService { public class CsWaveAnalysisServiceImpl implements ICsWaveAnalysisService {
private final EquipmentFeignClient equipmentFeignClient; private final EquipmentFeignClient equipmentFeignClient;
private final MqttPublisher publisher; private final MqttPublisher publisher;
private final CsTopicFeignClient csTopicFeignClient; private final CsTopicFeignClient csTopicFeignClient;
private final RedisUtil redisUtil; private final RedisUtil redisUtil;
private final CsLineFeignClient csLineFeignClient; private final CsLineFeignClient csLineFeignClient;
private final DicDataFeignClient dicDataFeignClient; private final DicDataFeignClient dicDataFeignClient;
private final ChannelObjectUtil channelObjectUtil;
private final MqttUtil mqttUtil;
@Override @Override
public void analysis(AppEventMessage appEventMessage) { public void analysis(AppEventMessage appEventMessage) {
int mid = 1; try {
//获取监测点 List<WaveTimeDto> list = new ArrayList<>();
String lineId = null;
Object object1 = redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appEventMessage.getId()); Object object1 = redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appEventMessage.getId());
if (Objects.isNull(object1)){ if (Objects.isNull(object1)){
lineInfo(appEventMessage.getId()); lineInfo(appEventMessage.getId());
@@ -69,29 +69,54 @@ public class CsWaveAnalysisServiceImpl implements ICsWaveAnalysisService {
List<AppEventMessage.DataArray> dataArrayList = appEventMessage.getMsg().getDataArray(); List<AppEventMessage.DataArray> dataArrayList = appEventMessage.getMsg().getDataArray();
if (CollectionUtil.isNotEmpty(dataArrayList)){ if (CollectionUtil.isNotEmpty(dataArrayList)){
for (AppEventMessage.DataArray item : dataArrayList) { for (AppEventMessage.DataArray item : dataArrayList) {
//处理mid
if (Objects.equals(mid,10000)){
mid = 1;
}
List<AppEventMessage.Param> paramList = item.getParam(); List<AppEventMessage.Param> paramList = item.getParam();
Object object = paramList.stream().filter(item2 -> ZlConstant.WAVE_NAME.equals(item2.getName())).findFirst().get().getData(); Object object = paramList.stream().filter(item2 -> ZlConstant.WAVE_NAME.equals(item2.getName())).findFirst().get().getData();
Object object2 = paramList.stream().filter(item2 -> ZlConstant.WAVE_PARAM_RCDKEEPTIME.equals(item2.getName())).findFirst().get().getData(); Object object2 = paramList.stream().filter(item2 -> ZlConstant.WAVE_PARAM_RCDKEEPTIME.equals(item2.getName())).findFirst().get().getData();
Object object3 = paramList.stream().filter(item2 -> ZlConstant.WAVE_POSITION.equals(item2.getName())).findFirst().get().getData(); Object object3 = paramList.stream().filter(item2 -> ZlConstant.WAVE_POSITION.equals(item2.getName())).findFirst().get().getData();
if (Objects.equals(object3.toString(),ZlConstant.GRID)){ String lineId = appEventMessage.getId() + appEventMessage.getMsg().getClDid();
lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appEventMessage.getId())), Map.class).get("1").toString();
} else if (Objects.equals(object3.toString(),ZlConstant.LOAD)){
lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appEventMessage.getId())), Map.class).get("2").toString();
} else {
lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appEventMessage.getId())), Map.class).get("0").toString();
}
String fileName = object.toString().replaceAll("\\[","").replaceAll("]",""); String fileName = object.toString().replaceAll("\\[","").replaceAll("]","");
List<String> fileList = Arrays.stream(fileName.split(",")).collect(Collectors.toList()); List<String> fileList = Arrays.stream(fileName.split(",")).collect(Collectors.toList());
//获取到录波文件,将文件信息存储起来
for (String file : fileList) { for (String file : fileList) {
file = file.trim(); file = file.trim();
askFileInfo(appEventMessage.getId(),mid,file); WaveTimeDto dto = channelTimeRange(file,appEventMessage.getId(),item.getDataTimeSec(),item.getDataTimeUSec(),(Double)object2,deviceId,lineId,object3.toString());
mid++; list.add(dto);
channelTimeRange(file,item.getDataTimeSec(),item.getDataTimeUSec(),(Double)object2,deviceId,lineId,object3.toString());
} }
Object obj = redisUtil.getObjectByKey("eventFile:" + appEventMessage.getId());
if (!Objects.isNull(obj)) {
List<WaveTimeDto> oldList = channelObjectUtil.objectToList(obj,WaveTimeDto.class);
oldList.addAll(list);
redisUtil.saveByKey("eventFile:" + appEventMessage.getId(), oldList);
} else {
redisUtil.saveByKey("eventFile:" + appEventMessage.getId(), list);
}
}
//处理缓存数据
channelWave(appEventMessage.getId());
}
} catch (Exception e) {
//发生异常,清理标识
redisUtil.delete("handleEvent:" + appEventMessage.getId());
}
}
@Override
@Async("asyncExecutor")
public void channelWave(String nDid) {
//判断客户端是否在线,在线再处理文件
String clientName = "NJCN-" + nDid.substring(nDid.length() - 6);
boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
if (mqttClient){
//有相同文件处理时,则不进行数据处理
Object obj = redisUtil.getObjectByKey("handleEvent:" + nDid);
if (Objects.isNull(obj)) {
List<WaveTimeDto> list = channelObjectUtil.objectToList( redisUtil.getObjectByKey("eventFile:" + nDid),WaveTimeDto.class);
if (CollectionUtil.isNotEmpty(list)) {
WaveTimeDto dto = list.get(0);
askFileInfo(nDid,1,dto.getFileName());
}
} else {
throw new BusinessException(AlgorithmResponseEnum.FILE_DOWNLOADING);
} }
} }
} }
@@ -114,10 +139,11 @@ public class CsWaveAnalysisServiceImpl implements ICsWaveAnalysisService {
publisher.send("/Pfm/DevFileCmd/"+version+"/"+nDid,new Gson().toJson(reqAndResParam),1,false); publisher.send("/Pfm/DevFileCmd/"+version+"/"+nDid,new Gson().toJson(reqAndResParam),1,false);
} }
/** /**
* 时间处理 * 时间处理
*/ */
public void channelTimeRange(String fileName, long time, long subtleTime, Double millisecond, String deviceId, String lineId, String location) { public WaveTimeDto channelTimeRange(String fileName,String nDid, long time, long subtleTime, Double millisecond, String deviceId, String lineId, String location) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
time = time - 8*3600; time = time - 8*3600;
// 将millisecond转换为长整型并乘以1000以获取微秒 // 将millisecond转换为长整型并乘以1000以获取微秒
@@ -136,12 +162,14 @@ public class CsWaveAnalysisServiceImpl implements ICsWaveAnalysisService {
String formatTime2 = format.format(Long.parseLong(time222) * 1000); String formatTime2 = format.format(Long.parseLong(time222) * 1000);
WaveTimeDto waveTimeDto = new WaveTimeDto(); WaveTimeDto waveTimeDto = new WaveTimeDto();
waveTimeDto.setFileName(fileName);
waveTimeDto.setStartTime(formatTime1 + "." + time11); waveTimeDto.setStartTime(formatTime1 + "." + time11);
waveTimeDto.setEndTime(formatTime2 + "." + time22); waveTimeDto.setEndTime(formatTime2 + "." + time22);
waveTimeDto.setDeviceId(deviceId); waveTimeDto.setDeviceId(deviceId);
waveTimeDto.setNDid(nDid);
waveTimeDto.setLineId(lineId); waveTimeDto.setLineId(lineId);
waveTimeDto.setLocation(location); waveTimeDto.setLocation(location);
redisUtil.saveByKeyWithExpire(AppRedisKey.TIME+fileName,waveTimeDto,600L); return waveTimeDto;
} }
/** /**

View File

@@ -1,5 +1,6 @@
package com.njcn.zlevent.service.impl; package com.njcn.zlevent.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -8,6 +9,9 @@ import com.njcn.zlevent.pojo.po.CsWave;
import com.njcn.zlevent.service.ICsWaveService; import com.njcn.zlevent.service.ICsWaveService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
/** /**
* <p> * <p>
* 治理波形文件记录表 服务实现类 * 治理波形文件记录表 服务实现类
@@ -20,10 +24,11 @@ import org.springframework.stereotype.Service;
public class CsWaveServiceImpl extends ServiceImpl<CsWaveMapper, CsWave> implements ICsWaveService { public class CsWaveServiceImpl extends ServiceImpl<CsWaveMapper, CsWave> implements ICsWaveService {
@Override @Override
public int findCountByName(String fileName) { public boolean findCountByName(String fileName) {
LambdaQueryWrapper<CsWave> lambdaQueryWrapper = new LambdaQueryWrapper<>(); List<CsWave> csWaveDat = selectCsWave(".dat",fileName);
lambdaQueryWrapper.like(CsWave::getRcdName,fileName).eq(CsWave::getStatus,1); List<CsWave> csWaveCfg = selectCsWave(".cfg",fileName);
return this.baseMapper.selectCount(lambdaQueryWrapper); // 判断两个查询结果是否都不为空
return CollectionUtil.isNotEmpty(csWaveDat) && CollectionUtil.isNotEmpty(csWaveCfg);
} }
@Override @Override
@@ -32,4 +37,11 @@ public class CsWaveServiceImpl extends ServiceImpl<CsWaveMapper, CsWave> impleme
lambdaQueryWrapper.eq(CsWave::getRcdName,fileName).set(CsWave::getStatus,1); lambdaQueryWrapper.eq(CsWave::getRcdName,fileName).set(CsWave::getStatus,1);
this.update(lambdaQueryWrapper); this.update(lambdaQueryWrapper);
} }
public List<CsWave> selectCsWave(String suffix, String fileName) {
LambdaQueryWrapper<CsWave> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.like(CsWave::getRcdName, fileName.concat(suffix)).eq(CsWave::getStatus, 1);
return this.baseMapper.selectList(lambdaQueryWrapper);
}
} }

View File

@@ -6,8 +6,12 @@ import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLineFeignClient; import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient; import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.api.WlRecordFeignClient;
import com.njcn.csdevice.pojo.param.WlRecordParam;
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO; import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
import com.njcn.csdevice.pojo.po.CsLinePO; import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.pojo.po.WlRecord;
import com.njcn.csdevice.pojo.vo.CsEquipmentDeliveryVO;
import com.njcn.csharmonic.pojo.po.CsEventPO; import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.influx.pojo.constant.InfluxDBTableConstant; import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
import com.njcn.influx.utils.InfluxDbUtils; import com.njcn.influx.utils.InfluxDbUtils;
@@ -31,11 +35,15 @@ import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB; import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints; import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point; import org.influxdb.dto.Point;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -53,22 +61,15 @@ import java.util.concurrent.TimeUnit;
public class EventServiceImpl implements IEventService { public class EventServiceImpl implements IEventService {
private final CsLineFeignClient csLineFeignClient; private final CsLineFeignClient csLineFeignClient;
private final DicDataFeignClient dicDataFeignClient; private final DicDataFeignClient dicDataFeignClient;
private final EpdFeignClient epdFeignClient; private final EpdFeignClient epdFeignClient;
private final RedisUtil redisUtil; private final RedisUtil redisUtil;
private final ICsEventService csEventService; private final ICsEventService csEventService;
private final EquipmentFeignClient equipmentFeignClient; private final EquipmentFeignClient equipmentFeignClient;
private final InfluxDbUtils influxDbUtils; private final InfluxDbUtils influxDbUtils;
private final ICsEventLogsService csEventLogsService; private final ICsEventLogsService csEventLogsService;
private final SendEventUtils sendEventUtils; private final SendEventUtils sendEventUtils;
private final WlRecordFeignClient wlRecordFeignClient;
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@@ -92,6 +93,7 @@ public class EventServiceImpl implements IEventService {
//处理事件数据 //处理事件数据
List<AppEventMessage.DataArray> dataArray = appEventMessage.getMsg().getDataArray(); List<AppEventMessage.DataArray> dataArray = appEventMessage.getMsg().getDataArray();
for (AppEventMessage.DataArray item : dataArray) { for (AppEventMessage.DataArray item : dataArray) {
eventTime = timeFormat(item.getDataTimeSec(),item.getDataTimeUSec());
id = IdUtil.fastSimpleUUID(); id = IdUtil.fastSimpleUUID();
//事件入库 //事件入库
CsEventPO csEvent = new CsEventPO(); CsEventPO csEvent = new CsEventPO();
@@ -137,6 +139,10 @@ public class EventServiceImpl implements IEventService {
if (Objects.equals(param.getName(),ZlConstant.EVT_PARAM_TM)){ if (Objects.equals(param.getName(),ZlConstant.EVT_PARAM_TM)){
csEvent.setPersistTime(Double.parseDouble(param.getData().toString())); csEvent.setPersistTime(Double.parseDouble(param.getData().toString()));
} }
lineId = appEventMessage.getId() + appEventMessage.getMsg().getClDid();
fields.put(param.getName(),appEventMessage.getMsg().getClDid()==1?"电网侧":"负载侧");
csEvent.setLocation(appEventMessage.getMsg().getClDid()==1?ZlConstant.GRID:ZlConstant.LOAD);
csEvent.setClDid(appEventMessage.getMsg().getClDid());
fields.put(param.getName(),param.getData()); fields.put(param.getName(),param.getData());
} }
//fixme 这边前置传递的应该是UTC时间,但是前置说是传递的北京时间,讨论了一下没太理解。这边暂时先这样处理,influx入库处理成北京时间,减去8小时。 //fixme 这边前置传递的应该是UTC时间,但是前置说是传递的北京时间,讨论了一下没太理解。这边暂时先这样处理,influx入库处理成北京时间,减去8小时。
@@ -161,15 +167,15 @@ public class EventServiceImpl implements IEventService {
//cs_event入库 //cs_event入库
if (CollectionUtil.isNotEmpty(list1)){ if (CollectionUtil.isNotEmpty(list1)){
csEventService.saveBatch(list1); csEventService.saveBatch(list1);
//推送事件逻辑处理 && cs_event_user入库
for (AppEventMessage.DataArray item : dataArray) {
sendEventUtils.sendUser(1,item.getType(),po.getId(),item.getName(),eventTime,id);
}
} }
//evt_data入库 //evt_data入库
if (CollectionUtil.isNotEmpty(records)) { if (CollectionUtil.isNotEmpty(records)) {
influxDbUtils.batchInsert(influxDbUtils.getDbName(), "", InfluxDB.ConsistencyLevel.ALL, TimeUnit.MILLISECONDS, records); influxDbUtils.batchInsert(influxDbUtils.getDbName(), "", InfluxDB.ConsistencyLevel.ALL, TimeUnit.MILLISECONDS, records);
} }
//推送事件逻辑处理 && cs_event_user入库
for (AppEventMessage.DataArray item : dataArray) {
sendEventUtils.sendUser(1,item.getType(),po.getId(),item.getName(),eventTime,id);
}
} catch (Exception e) { } catch (Exception e) {
CsEventLogs csEventLogs = new CsEventLogs(); CsEventLogs csEventLogs = new CsEventLogs();
csEventLogs.setLineId(lineId); csEventLogs.setLineId(lineId);
@@ -183,6 +189,93 @@ public class EventServiceImpl implements IEventService {
} }
} }
@Override
@Transactional(rollbackFor = Exception.class)
public void getPortableData(AppEventMessage appEventMessage) {
CsEquipmentDeliveryVO vo = equipmentFeignClient.queryEquipmentByndid(appEventMessage.getId()).getData();
//根据报文判断是新增还是更新
List<AppEventMessage.DataArray> dataArrays = appEventMessage.getMsg().getDataArray();
dataArrays.forEach(item->{
WlRecordParam.Record param = new WlRecordParam.Record();
param.setDevId(vo.getId());
param.setLineId(appEventMessage.getId() + item.getClDid().toString());
param.setProName(item.getPrjName());
param.setProStartTime(timestampToDatetime((item.getPrjTimeStart() - 8*3600)));
WlRecord record = wlRecordFeignClient.findDevBaseData(param).getData();
if (!Objects.isNull(record)) {
if (!Objects.equals(item.getPrjTimeEnd(),-1L)) {
WlRecordParam.UpdateRecord wlRecord = new WlRecordParam.UpdateRecord();
wlRecord.setId(record.getId());
wlRecord.setProEndTime(timestampToDatetime((item.getPrjTimeEnd() - 8*3600)));
wlRecordFeignClient.updateTestRecord(wlRecord);
}
} else {
//新项目入库
WlRecord wlRecord = new WlRecord();
wlRecord.setId(IdUtil.simpleUUID());
wlRecord.setItemName("基础数据");
wlRecord.setGcName(item.getPrjName());
wlRecord.setDevId(vo.getId());
wlRecord.setLineId(appEventMessage.getId() + item.getClDid().toString());
wlRecord.setStatisticalInterval(item.getStatCycle());
wlRecord.setPt(item.getPtRatio());
wlRecord.setCt(item.getCtRatio());
//电压等级
DictData dictData = dicDataFeignClient.getDicDataByCodeAndType(channelVol(item.getVolGrade()) + "kV","Dev_Voltage_Stand").getData();
wlRecord.setVoltageLevel(Objects.isNull(dictData)?null:dictData.getId());
wlRecord.setCapacitySscb(item.getCapacitySscb());
wlRecord.setCapacitySscmin(item.getCapacitySscmin());
wlRecord.setCapacitySt(item.getCapacitySt());
wlRecord.setCapacitySi(item.getCapacitySi());
//电压接线方式
wlRecord.setVolConType(getVolConType(item.getVolConType()));
//fixme 电流接线方式 这边系统没有字典,录入字典通用性不强,采用装置上送值存储
wlRecord.setCurConSel(item.getCurConSel().toString());
wlRecord.setStartTime(timestampToDatetime((item.getPrjTimeStart() - 8*3600)));
wlRecord.setType(1);
wlRecord.setState(1);
wlRecord.setGcDataPath(item.getPrjDataPath());
wlRecordFeignClient.addBaseData(wlRecord);
}
});
}
/**
* 处理电压
* @param vol
* @return
*/
public String channelVol(Float vol) {
BigDecimal value = new BigDecimal(vol);
BigDecimal noZeros = value.stripTrailingZeros();
return noZeros.toPlainString();
}
// 0-星型, 1-角型, 2-V型
// star-星型、Star_Triangle-星三角、Open_Delta-开口三角
public String getVolConType(Integer volConType) {
String result = null;
String dictDataCode = null;
switch (volConType) {
case 0:
dictDataCode = "star";
break;
case 1:
dictDataCode = "Star_Triangle";
break;
case 2:
dictDataCode = "Open_Delta";
break;
default:
break;
}
if (!Objects.isNull(dictDataCode)) {
DictData dictData = dicDataFeignClient.getDicDataByCodeAndType(dictDataCode,"Dev_Connect").getData();
result = dictData.getId();
}
return Objects.isNull(result)?null:result;
}
/** /**
* 缓存监测点相关信息 * 缓存监测点相关信息
*/ */
@@ -243,4 +336,9 @@ public class EventServiceImpl implements IEventService {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
return LocalDateTime.parse(time, fmt); return LocalDateTime.parse(time, fmt);
} }
public LocalDateTime timestampToDatetime(long timestamp){
Instant instant = Instant.ofEpochSecond(timestamp);
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
} }

View File

@@ -4,15 +4,15 @@ import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrPool; import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import com.alibaba.nacos.shaded.com.google.gson.Gson; import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.GsonBuilder;
import com.github.tocrhz.mqtt.publisher.MqttPublisher; import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.access.api.CsTopicFeignClient; import com.njcn.access.api.CsTopicFeignClient;
import com.njcn.access.enums.AccessEnum; import com.njcn.access.enums.AccessEnum;
import com.njcn.access.enums.AccessResponseEnum; import com.njcn.access.enums.AccessResponseEnum;
import com.njcn.access.enums.TypeEnum; import com.njcn.access.enums.TypeEnum;
import com.njcn.access.pojo.dto.ReqAndResDto; import com.njcn.access.pojo.dto.ReqAndResDto;
import com.njcn.access.utils.CRC32Utils;
import com.njcn.access.utils.ChannelObjectUtil;
import com.njcn.common.config.GeneralInfo; import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csharmonic.api.WavePicFeignClient; import com.njcn.csharmonic.api.WavePicFeignClient;
@@ -28,10 +28,8 @@ import com.njcn.zlevent.pojo.dto.FileStreamDto;
import com.njcn.zlevent.pojo.dto.WaveTimeDto; import com.njcn.zlevent.pojo.dto.WaveTimeDto;
import com.njcn.zlevent.pojo.po.CsEventFileLogs; import com.njcn.zlevent.pojo.po.CsEventFileLogs;
import com.njcn.zlevent.pojo.po.CsWave; import com.njcn.zlevent.pojo.po.CsWave;
import com.njcn.zlevent.service.ICsEventFileLogsService; import com.njcn.zlevent.service.*;
import com.njcn.zlevent.service.ICsEventService; import com.njcn.zlevent.utils.RemoveInfoUtils;
import com.njcn.zlevent.service.ICsWaveService;
import com.njcn.zlevent.service.IFileService;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
@@ -41,7 +39,6 @@ import java.io.*;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit;
/** /**
* 类的介绍: * 类的介绍:
@@ -56,22 +53,17 @@ import java.util.concurrent.TimeUnit;
public class FileServiceImpl implements IFileService { public class FileServiceImpl implements IFileService {
private final RedisUtil redisUtil; private final RedisUtil redisUtil;
private final CsTopicFeignClient csTopicFeignClient; private final CsTopicFeignClient csTopicFeignClient;
private final MqttPublisher publisher; private final MqttPublisher publisher;
private final FileStorageUtil fileStorageUtil; private final FileStorageUtil fileStorageUtil;
private final ICsEventService csEventService; private final ICsEventService csEventService;
private final ICsEventFileLogsService csEventLogsService; private final ICsEventFileLogsService csEventLogsService;
private final WavePicFeignClient wavePicFeignClient; private final WavePicFeignClient wavePicFeignClient;
private final ICsWaveService csWaveService; private final ICsWaveService csWaveService;
private final GeneralInfo generalInfo; private final GeneralInfo generalInfo;
private final ICsWaveAnalysisService iCsWaveAnalysisService;
private final ChannelObjectUtil channelObjectUtil;
private final RemoveInfoUtils removeInfoUtils;
@Override @Override
public void analysisFileInfo(AppFileMessage appFileMessage) { public void analysisFileInfo(AppFileMessage appFileMessage) {
@@ -82,12 +74,9 @@ public class FileServiceImpl implements IFileService {
String fileName = appFileMessage.getMsg().getFileInfo().getName(); String fileName = appFileMessage.getMsg().getFileInfo().getName();
//缓存文件信息用于文件流拼接 //缓存文件信息用于文件流拼接
FileInfoDto fileInfoDto = new FileInfoDto(); FileInfoDto fileInfoDto = new FileInfoDto();
//获取波形文件起始结束时间 List<WaveTimeDto> list = channelObjectUtil.objectToList(redisUtil.getObjectByKey("eventFile:" + appFileMessage.getId()),WaveTimeDto.class);
Object fileInfo = redisUtil.getObjectByKey(AppRedisKey.TIME+fileName); if (CollectionUtil.isNotEmpty(list)) {
if (Objects.isNull(fileInfo)){ WaveTimeDto waveTimeDto = channelObjectUtil.objectToList(redisUtil.getObjectByKey("eventFile:" + appFileMessage.getId()),WaveTimeDto.class).get(0);
throw new BusinessException(AccessResponseEnum.WAVE_INFO_MISSING);
}
WaveTimeDto waveTimeDto = JSON.parseObject(JSON.toJSONString(fileInfo), WaveTimeDto.class);
fileInfoDto.setStartTime(waveTimeDto.getStartTime()); fileInfoDto.setStartTime(waveTimeDto.getStartTime());
fileInfoDto.setEndTime(waveTimeDto.getEndTime()); fileInfoDto.setEndTime(waveTimeDto.getEndTime());
fileInfoDto.setDeviceId(waveTimeDto.getDeviceId()); fileInfoDto.setDeviceId(waveTimeDto.getDeviceId());
@@ -115,6 +104,7 @@ public class FileServiceImpl implements IFileService {
askFileStream(appFileMessage.getId(),mid,fileName,-1,range); askFileStream(appFileMessage.getId(),mid,fileName,-1,range);
redisUtil.saveByKey(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileInfoDto.getName()), fileInfoDto); redisUtil.saveByKey(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileInfoDto.getName()), fileInfoDto);
redisUtil.delete(AppRedisKey.TIME+fileName); redisUtil.delete(AppRedisKey.TIME+fileName);
}
} else { } else {
throw new BusinessException(AccessResponseEnum.RESPONSE_ERROR); throw new BusinessException(AccessResponseEnum.RESPONSE_ERROR);
} }
@@ -123,8 +113,8 @@ public class FileServiceImpl implements IFileService {
@Override @Override
public void analysisFileStream(AppFileMessage appFileMessage) { public void analysisFileStream(AppFileMessage appFileMessage) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
String filePath; String filePath = null;
List<Integer> list = new ArrayList<>(); Set<Integer> list = new HashSet<>();
FileStreamDto fileStreamDto = new FileStreamDto(); FileStreamDto fileStreamDto = new FileStreamDto();
//波形文件上传成功后,将文件信息存储一下,方便后期查看 //波形文件上传成功后,将文件信息存储一下,方便后期查看
CsWave csWave = new CsWave(); CsWave csWave = new CsWave();
@@ -138,18 +128,105 @@ public class FileServiceImpl implements IFileService {
try { try {
//todo 目前文件先只处理波形事件的,后续有其他文件再做处理 //todo 目前文件先只处理波形事件的,后续有其他文件再做处理
String fileName = appFileMessage.getMsg().getName(); String fileName = appFileMessage.getMsg().getName();
//String lsFileName =fileName.split(StrUtil.SLASH)[fileName.split(StrUtil.SLASH).length - 1];
String lsFileName = generalInfo.getBusinessTempPath() + File.separator + fileName.split(StrUtil.SLASH)[fileName.split(StrUtil.SLASH).length - 1]; String lsFileName = generalInfo.getBusinessTempPath() + File.separator + fileName.split(StrUtil.SLASH)[fileName.split(StrUtil.SLASH).length - 1];
File lsFile =new File(generalInfo.getBusinessTempPath());
//如果文件夹不存在则创建
if (!lsFile.exists() && !lsFile.isDirectory()) {
lsFile .mkdirs();
}
//获取缓存的文件信息 //获取缓存的文件信息
Object fileInfo = redisUtil.getObjectByKey(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileName)); Object fileInfo = redisUtil.getObjectByKey(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileName));
FileInfoDto fileInfoDto = JSON.parseObject(JSON.toJSONString(fileInfo), FileInfoDto.class); FileInfoDto fileInfoDto = JSON.parseObject(JSON.toJSONString(fileInfo), FileInfoDto.class);
//1.判断当前文件是否之前缓存过,没缓存,则先缓存(这边缓存两条记录,一条是用来判断超时的,还有一条记录文件数据,文件数据目前没有过期时间,文件数据收完才会删除) if (Objects.isNull(fileInfoDto)) {
//2.缓存了判断收到的报文个数是否和总个数一致,一致则解析文件;不一致则更新缓存 String fileCheck = redisUtil.getObjectByKey("fileCheck"+fileName).toString();
//3.超时判断: 30s分钟未收到相关文件信息核查文件个数看丢失哪些帧重新请求
if(fileName.contains(".cfg") || fileName.contains(".dat")) {
if (appFileMessage.getMsg().getFrameTotal() == 1) { if (appFileMessage.getMsg().getFrameTotal() == 1) {
//解析文件入库 //解析文件入库
filePath = fileStream(1,null,appFileMessage.getMsg().getData(),fileName,appFileMessage.getId()); filePath = fileStream(1,null,appFileMessage.getMsg().getData(),fileName,appFileMessage.getId(),fileCheck,"download");
csEventLogs.setStatus(1);
csEventLogs.setRemark("当前文件1帧,全部收到,解析成功!");
csEventLogs.setNowStep(1);
csEventLogs.setAllStep(1);
csEventLogs.setIsAll(1);
redisUtil.delete(AppRedisKey.FILE_PART_TIME.concat(appFileMessage.getMsg().getName()));
redisUtil.delete(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()));
redisUtil.delete(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileName));
} else {
//收到数据就刷新缓存值
redisUtil.saveByKeyWithExpire(AppRedisKey.FILE_DOWN_TIME.concat(appFileMessage.getMsg().getName()), null, 60L);
Object object1 = redisUtil.getObjectByKey(AppRedisKey.FILE_PART.concat(fileName));
if (Objects.isNull(object1)){
fileStreamDto.setTotal(appFileMessage.getMsg().getFrameTotal());
fileStreamDto.setNDid(appFileMessage.getId());
fileStreamDto.setFrameLen(appFileMessage.getMsg().getFrameLen());
list.add(appFileMessage.getMsg().getFrameCurr());
fileStreamDto.setList(list);
csEventLogs.setStatus(1);
csEventLogs.setRemark("当前文件"+appFileMessage.getMsg().getFrameTotal()+"帧,这是第"+appFileMessage.getMsg().getFrameCurr()+"帧,记录成功!");
csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr());
csEventLogs.setAllStep(appFileMessage.getMsg().getFrameTotal());
csEventLogs.setIsAll(0);
redisUtil.saveByKey(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()), fileStreamDto);
//将数据写入临时文件
appendFile(lsFileName,appFileMessage.getMsg().getFrameCurr(),appFileMessage.getMsg().getData());
log.info("当前文件 {} 帧,这是第 {} 帧报文,记录成功", appFileMessage.getMsg().getFrameTotal(), appFileMessage.getMsg().getFrameCurr());
} else {
FileStreamDto dto = JSON.parseObject(JSON.toJSONString(object1), FileStreamDto.class);
//防止出现录入重复数据,做个判断
if (!dto.getList().contains(appFileMessage.getMsg().getFrameCurr())) {
dto.getList().add(appFileMessage.getMsg().getFrameCurr());
if (Objects.equals(dto.getTotal(), dto.getList().size())) {
Map<Integer, String> filePartMap = readFile(lsFileName);
filePartMap.put(appFileMessage.getMsg().getFrameCurr(), appFileMessage.getMsg().getData());
//解析文件入库
filePath = fileStream(dto.getTotal(), filePartMap, null, fileName, appFileMessage.getId(),fileCheck,"download");
csEventLogs.setStatus(1);
csEventLogs.setRemark("当前文件" + appFileMessage.getMsg().getFrameTotal() + "帧,这是第" + appFileMessage.getMsg().getFrameCurr() + "帧,全部收到,解析成功!");
csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr());
csEventLogs.setAllStep(appFileMessage.getMsg().getFrameTotal());
csEventLogs.setIsAll(1);
log.info("当前文件 {} 帧,这是第 {} 帧报文,全部收到,解析成功!", appFileMessage.getMsg().getFrameTotal(), appFileMessage.getMsg().getFrameCurr());
//删除临时文件
File file = new File(lsFileName);
if (file.exists()) {
file.delete();
}
redisUtil.delete(AppRedisKey.FILE_PART_TIME.concat(appFileMessage.getMsg().getName()));
redisUtil.delete(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()));
redisUtil.delete(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileName));
redisUtil.delete(AppRedisKey.FILE_DOWN_TIME.concat(appFileMessage.getMsg().getName()));
} else {
csEventLogs.setStatus(1);
csEventLogs.setRemark("当前文件" + appFileMessage.getMsg().getFrameTotal() + "帧,这是第" + appFileMessage.getMsg().getFrameCurr() + "帧,记录成功!");
csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr());
csEventLogs.setAllStep(appFileMessage.getMsg().getFrameTotal());
csEventLogs.setIsAll(0);
redisUtil.saveByKey(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()), dto);
//将数据写入临时文件
appendFile(lsFileName, appFileMessage.getMsg().getFrameCurr(), appFileMessage.getMsg().getData());
log.info("当前文件 {} 帧,这是第 {} 帧报文,记录成功", appFileMessage.getMsg().getFrameTotal(), appFileMessage.getMsg().getFrameCurr());
}
} else {
csEventLogs.setStatus(1);
csEventLogs.setRemark("当前文件为重复帧,这是第" + appFileMessage.getMsg().getFrameCurr() + "帧,不做记录!");
csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr());
csEventLogs.setAllStep(appFileMessage.getMsg().getFrameTotal());
csEventLogs.setIsAll(0);
}
}
}
if (!Objects.isNull(filePath)){
redisUtil.saveByKey("downloadFilePath:"+appFileMessage.getMsg().getName(),filePath);
}
}
//录波文件下载
//1.判断当前文件是否之前缓存过,没缓存,则先缓存(这边缓存两条记录,一条是用来判断超时的,还有一条记录文件数据,文件数据目前没有过期时间,文件数据收完才会删除)
//2.缓存了判断收到的报文个数是否和总个数一致,一致则解析文件;不一致则更新缓存
//3.超时判断: 30s未收到相关文件信息核查文件个数看丢失哪些帧重新请求
else {
redisUtil.saveByKey("handleEvent:" + appFileMessage.getId(),"doing");
if (appFileMessage.getMsg().getFrameTotal() == 1){
//解析文件入库
filePath = fileStream(1,null,appFileMessage.getMsg().getData(),fileName,appFileMessage.getId(),fileInfoDto.getFileCheck(),"event");
csEventLogs.setStatus(1); csEventLogs.setStatus(1);
csEventLogs.setRemark("当前文件1帧,全部收到,解析成功!"); csEventLogs.setRemark("当前文件1帧,全部收到,解析成功!");
csEventLogs.setNowStep(1); csEventLogs.setNowStep(1);
@@ -164,8 +241,11 @@ public class FileServiceImpl implements IFileService {
if (CollectionUtil.isNotEmpty(eventList)){ if (CollectionUtil.isNotEmpty(eventList)){
eventList.forEach(wavePicFeignClient::getWavePics); eventList.forEach(wavePicFeignClient::getWavePics);
} }
redisUtil.delete(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileInfoDto.getName())); //解析完删除、处理缓存
removeInfoUtils.deleteEventInfo(appFileMessage.getId(),fileName);
} else { } else {
//收到数据就刷新缓存值
redisUtil.saveByKeyWithExpire(AppRedisKey.FILE_PART_TIME.concat(appFileMessage.getMsg().getName()), null, 60L);
Object object1 = redisUtil.getObjectByKey(AppRedisKey.FILE_PART.concat(fileName)); Object object1 = redisUtil.getObjectByKey(AppRedisKey.FILE_PART.concat(fileName));
if (Objects.isNull(object1)){ if (Objects.isNull(object1)){
fileStreamDto.setTotal(appFileMessage.getMsg().getFrameTotal()); fileStreamDto.setTotal(appFileMessage.getMsg().getFrameTotal());
@@ -178,7 +258,6 @@ public class FileServiceImpl implements IFileService {
csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr()); csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr());
csEventLogs.setAllStep(appFileMessage.getMsg().getFrameTotal()); csEventLogs.setAllStep(appFileMessage.getMsg().getFrameTotal());
csEventLogs.setIsAll(0); csEventLogs.setIsAll(0);
redisUtil.saveByKeyWithExpire(AppRedisKey.FILE_PART_TIME.concat(appFileMessage.getMsg().getName()), null, 30L);
redisUtil.saveByKey(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()), fileStreamDto); redisUtil.saveByKey(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()), fileStreamDto);
//将数据写入临时文件 //将数据写入临时文件
appendFile(lsFileName,appFileMessage.getMsg().getFrameCurr(),appFileMessage.getMsg().getData()); appendFile(lsFileName,appFileMessage.getMsg().getFrameCurr(),appFileMessage.getMsg().getData());
@@ -192,7 +271,7 @@ public class FileServiceImpl implements IFileService {
Map<Integer, String> filePartMap = readFile(lsFileName); Map<Integer, String> filePartMap = readFile(lsFileName);
filePartMap.put(appFileMessage.getMsg().getFrameCurr(), appFileMessage.getMsg().getData()); filePartMap.put(appFileMessage.getMsg().getFrameCurr(), appFileMessage.getMsg().getData());
//解析文件 //解析文件
filePath = fileStream(appFileMessage.getMsg().getFrameTotal(), filePartMap, null, fileName, appFileMessage.getId()); filePath = fileStream(appFileMessage.getMsg().getFrameTotal(), filePartMap, null, fileName, appFileMessage.getId(),fileInfoDto.getFileCheck(),"event");
csEventLogs.setStatus(1); csEventLogs.setStatus(1);
csEventLogs.setRemark("当前文件" + appFileMessage.getMsg().getFrameTotal() + "帧,这是第" + appFileMessage.getMsg().getFrameCurr() + "帧,全部收到,解析成功!"); csEventLogs.setRemark("当前文件" + appFileMessage.getMsg().getFrameTotal() + "帧,这是第" + appFileMessage.getMsg().getFrameCurr() + "帧,全部收到,解析成功!");
csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr()); csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr());
@@ -208,27 +287,21 @@ public class FileServiceImpl implements IFileService {
if (CollectionUtil.isNotEmpty(eventList)) { if (CollectionUtil.isNotEmpty(eventList)) {
eventList.forEach(wavePicFeignClient::getWavePics); eventList.forEach(wavePicFeignClient::getWavePics);
} }
redisUtil.delete(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileInfoDto.getName()));
redisUtil.delete(AppRedisKey.FILE_PART_TIME.concat(appFileMessage.getMsg().getName())); redisUtil.delete(AppRedisKey.FILE_PART_TIME.concat(appFileMessage.getMsg().getName()));
redisUtil.delete(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName())); redisUtil.delete(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()));
redisUtil.delete(AppRedisKey.FILE_PART_MISSING.concat(appFileMessage.getMsg().getName())); //解析完删除、处理缓存
removeInfoUtils.deleteEventInfo(appFileMessage.getId(),fileName);
//删除临时文件 //删除临时文件
File file = new File(lsFileName); File file = new File(lsFileName);
if (file.exists()) { if (file.exists()) {
file.delete(); file.delete();
} }
} else { } else {
Object object2 = redisUtil.getObjectByKey(AppRedisKey.FILE_PART_MISSING.concat(fileName));
csEventLogs.setStatus(1); csEventLogs.setStatus(1);
csEventLogs.setRemark("当前文件" + appFileMessage.getMsg().getFrameTotal() + "帧,这是第" + appFileMessage.getMsg().getFrameCurr() + "帧,记录成功!"); csEventLogs.setRemark("当前文件" + appFileMessage.getMsg().getFrameTotal() + "帧,这是第" + appFileMessage.getMsg().getFrameCurr() + "帧,记录成功!");
csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr()); csEventLogs.setNowStep(appFileMessage.getMsg().getFrameCurr());
csEventLogs.setAllStep(appFileMessage.getMsg().getFrameTotal()); csEventLogs.setAllStep(appFileMessage.getMsg().getFrameTotal());
csEventLogs.setIsAll(0); csEventLogs.setIsAll(0);
if (Objects.isNull(object2)) {
redisUtil.saveByKeyWithExpire(AppRedisKey.FILE_PART_TIME.concat(appFileMessage.getMsg().getName()), null, 30L);
} else {
redisUtil.saveByKeyWithExpire(AppRedisKey.FILE_PART_TIME.concat(appFileMessage.getMsg().getName()), null, 1L);
}
redisUtil.saveByKey(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()), dto); redisUtil.saveByKey(AppRedisKey.FILE_PART.concat(appFileMessage.getMsg().getName()), dto);
//将数据写入临时文件 //将数据写入临时文件
appendFile(lsFileName, appFileMessage.getMsg().getFrameCurr(), appFileMessage.getMsg().getData()); appendFile(lsFileName, appFileMessage.getMsg().getFrameCurr(), appFileMessage.getMsg().getData());
@@ -249,9 +322,6 @@ public class FileServiceImpl implements IFileService {
csEventLogs.setLocation(fileInfoDto.getLocation()); csEventLogs.setLocation(fileInfoDto.getLocation());
//记录日志 //记录日志
csEventLogsService.save(csEventLogs); csEventLogsService.save(csEventLogs);
} else {
//todo 处理其他文件
log.info("暂未做其他文件处理");
} }
} catch (Exception e){ } catch (Exception e){
csEventLogs.setStatus(0); csEventLogs.setStatus(0);
@@ -283,10 +353,10 @@ public class FileServiceImpl implements IFileService {
/** /**
* 组装文件 * 组装文件
*/ */
public String fileStream(Integer number, Map<Integer,String> map, String data, String fileName, String nDid) { public String fileStream(Integer number, Map<Integer,String> map, String data, String fileName, String nDid, String fileCheck,String type) {
String filePath; String filePath;
if (number == 1){ if (number == 1){
filePath = stream(true,data,nDid,fileName,null); filePath = stream(true,data,nDid,fileName,null,fileCheck,type);
} else { } else {
int lengthByte = 0; int lengthByte = 0;
for (int i = 1; i <= number; i++) { for (int i = 1; i <= number; i++) {
@@ -300,7 +370,7 @@ public class FileServiceImpl implements IFileService {
System.arraycopy(byteArray, 0, allByte, countLength, byteArray.length); System.arraycopy(byteArray, 0, allByte, countLength, byteArray.length);
countLength += byteArray.length; countLength += byteArray.length;
} }
filePath = stream(false,null,nDid,fileName,allByte); filePath = stream(false,null,nDid,fileName,allByte,fileCheck,type);
} }
return filePath; return filePath;
} }
@@ -308,7 +378,8 @@ public class FileServiceImpl implements IFileService {
/** /**
* 解析存储文件信息 * 解析存储文件信息
*/ */
public String stream(boolean bool, String stream, String folder, String fileName, byte[] bytes) { public String stream(boolean bool, String stream, String folder, String fileName, byte[] bytes, String fileCheck, String type) {
String path;
byte[] byteArray = null; byte[] byteArray = null;
//将文件后缀替换成大写 //将文件后缀替换成大写
String[] parts = fileName.split(StrUtil.SLASH); String[] parts = fileName.split(StrUtil.SLASH);
@@ -321,9 +392,18 @@ public class FileServiceImpl implements IFileService {
} else { } else {
byteArray = bytes; byteArray = bytes;
} }
//todo 此处需要做文件crc校验或者md5校验目前不知道怎么处理先放一下 //文件校验
int crc = CRC32Utils.calculateCRC32(byteArray,byteArray.length,0xffffffff);
String hexString = String.format("%08X", crc);
if (!Objects.equals(hexString,fileCheck)) {
throw new BusinessException(AccessResponseEnum.FILE_CHECK_ERROR);
}
InputStream inputStream = new ByteArrayInputStream(byteArray); InputStream inputStream = new ByteArrayInputStream(byteArray);
String path = fileStorageUtil.uploadStreamSpecifyName(inputStream, OssPath.WAVE_DIR + folder + StrUtil.SLASH,fileName); if (Objects.equals(type,"download")) {
path = fileStorageUtil.uploadStreamSpecifyName(inputStream, OssPath.DOWNLOAD_DIR + folder + StrUtil.SLASH,fileName);
} else {
path = fileStorageUtil.uploadStreamSpecifyName(inputStream, OssPath.WAVE_DIR + folder + StrUtil.SLASH,fileName);
}
try { try {
inputStream.close(); inputStream.close();
} catch (IOException e) { } catch (IOException e) {
@@ -363,8 +443,8 @@ public class FileServiceImpl implements IFileService {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
String[] parts = fileName.split(StrUtil.SLASH); String[] parts = fileName.split(StrUtil.SLASH);
fileName = parts[parts.length - 1].split("\\.")[0]; fileName = parts[parts.length - 1].split("\\.")[0];
int fileCounts = csWaveService.findCountByName(fileName); boolean result = csWaveService.findCountByName(fileName);
if (fileCounts >= 2){ if (result){
CsEventParam csEventParam = new CsEventParam(); CsEventParam csEventParam = new CsEventParam();
csEventParam.setLineId(fileInfoDto.getLineId()); csEventParam.setLineId(fileInfoDto.getLineId());
csEventParam.setDeviceId(fileInfoDto.getDeviceId()); csEventParam.setDeviceId(fileInfoDto.getDeviceId());

View File

@@ -1,59 +0,0 @@
package com.njcn.zlevent.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.CRC32;
/**
* 类的介绍:用于文件校验
*
* @author xuyang
* @version 1.0.0
* @createTime 2023/9/8 13:32
*/
public class FileCheckUtils {
/**
* 32位CRC检验
* @param inputStream 文件流
* @return
* @throws IOException
*/
public static long calculateCRC32Checksum(InputStream inputStream) throws IOException {
CRC32 crc32 = new CRC32();
// 用于读取文件内容的缓冲区
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
crc32.update(buffer, 0, bytesRead);
}
return crc32.getValue();
}
/**
* MD5检验
* @param inputStream 文件流
* @return
* @throws IOException
*/
public static String calculateMD5Checksum(InputStream inputStream) throws IOException, NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
// 用于读取文件内容的缓冲区
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
md5.update(buffer, 0, bytesRead);
}
byte[] digest = md5.digest();
// 将MD5摘要转换为十六进制字符串
StringBuilder md5Checksum = new StringBuilder();
for (byte b : digest) {
md5Checksum.append(String.format("%02x", b));
}
return md5Checksum.toString();
}
}

View File

@@ -0,0 +1,90 @@
package com.njcn.zlevent.utils;
import cn.hutool.core.collection.CollectionUtil;
import com.njcn.access.utils.ChannelObjectUtil;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.zlevent.pojo.dto.WaveTimeDto;
import com.njcn.zlevent.service.ICsWaveAnalysisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
/**
* 类的介绍:
* @author xuyang
*/
@Slf4j
@Component
public class RemoveInfoUtils {
@Resource
private RedisUtil redisUtil;
@Resource
private ChannelObjectUtil channelObjectUtil;
@Resource
private ICsWaveAnalysisService iCsWaveAnalysisService;
public void deleteEventInfo(String nDid, String fileName) {
redisUtil.delete("handleEvent:" + nDid);
redisUtil.delete(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileName));
//删除已经处理完的文件,之后再判断还有是否需要下载的文件
List<WaveTimeDto> fileDto = channelObjectUtil.objectToList(redisUtil.getObjectByKey("eventFile:" + nDid),WaveTimeDto.class);
fileDto.removeIf(item -> item.getFileName().equals(fileName));
redisUtil.saveByKey("eventFile:" + nDid, fileDto);
if (CollectionUtil.isNotEmpty(fileDto)) {
iCsWaveAnalysisService.channelWave(nDid);
}
}
public void retryEventInfo(String nDid, String fileName) {
// 尝试获取重试次数
Object retryObject = redisUtil.getObjectByKey("retryEvent:" + nDid + fileName);
int retryTimes = retryObject != null ? Integer.parseInt(retryObject.toString()) : 0;
// 删除相关的 Redis 键
deleteRelatedKeys(nDid, fileName);
// 处理重试逻辑
if (retryTimes < 3) {
// 增加重试次数并保存
redisUtil.saveByKey(("retryEvent:" + nDid + fileName), retryTimes + 1);
// 重排文件列表
//updateFileList(nDid, fileName);
} else {
// 从列表中移除文件
removeFileFromList(nDid, fileName);
}
// 检查是否还有其他文件需要处理
List<WaveTimeDto> fileDto = channelObjectUtil.objectToList(redisUtil.getObjectByKey("eventFile:" + nDid), WaveTimeDto.class);
if (CollectionUtil.isNotEmpty(fileDto)) {
iCsWaveAnalysisService.channelWave(nDid);
}
}
private void deleteRelatedKeys(String nDid, String fileName) {
redisUtil.delete("handleEvent:" + nDid);
redisUtil.delete(AppRedisKey.RMQ_FILE_CONSUME_KEY.concat(fileName));
}
private void updateFileList(String nDid, String fileName) {
List<WaveTimeDto> fileDto = channelObjectUtil.objectToList(redisUtil.getObjectByKey("eventFile:" + nDid), WaveTimeDto.class);
WaveTimeDto dto = fileDto.stream()
.filter(item -> item.getFileName().equals(fileName))
.findFirst()
.orElse(null);
if (dto != null) {
fileDto.removeIf(item -> item.getFileName().equals(fileName));
fileDto.add(dto);
}
redisUtil.saveByKey("eventFile:" + nDid, fileDto);
}
private void removeFileFromList(String nDid, String fileName) {
List<WaveTimeDto> fileDto = channelObjectUtil.objectToList(redisUtil.getObjectByKey("eventFile:" + nDid), WaveTimeDto.class);
fileDto.removeIf(item -> item.getFileName().equals(fileName));
redisUtil.saveByKey("eventFile:" + nDid, fileDto);
redisUtil.delete(AppRedisKey.FILE_PART.concat(fileName));
}
}

View File

@@ -31,7 +31,6 @@ import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -86,6 +85,7 @@ public class SendEventUtils {
List<User> users = new ArrayList<>(); List<User> users = new ArrayList<>();
List<String> eventUser; List<String> eventUser;
List<String> devCodeList; List<String> devCodeList;
List<String> userList = new ArrayList<>();
List<CsEventSendMsg> csEventSendMsgList = new ArrayList<>(); List<CsEventSendMsg> csEventSendMsgList = new ArrayList<>();
NoticeUserDto noticeUserDto = new NoticeUserDto(); NoticeUserDto noticeUserDto = new NoticeUserDto();
NoticeUserDto.Payload payload = new NoticeUserDto.Payload(); NoticeUserDto.Payload payload = new NoticeUserDto.Payload();
@@ -111,9 +111,10 @@ public class SendEventUtils {
users = getSendUser(eventUser,2); users = getSendUser(eventUser,2);
if (CollectionUtil.isNotEmpty(users)){ if (CollectionUtil.isNotEmpty(users)){
for (User user : users){ for (User user : users){
noticeUserDto.setPushClientId(Collections.singletonList(user.getDevCode())); userList.add(user.getDevCode());
noticeUserDto.setTitle("设备事件");
} }
noticeUserDto.setPushClientId(userList);
noticeUserDto.setTitle("设备事件");
} }
} }
break; break;
@@ -224,12 +225,14 @@ public class SendEventUtils {
} }
if (CollectionUtil.isNotEmpty(noticeUserDto.getPushClientId())) { if (CollectionUtil.isNotEmpty(noticeUserDto.getPushClientId())) {
List<String> filteredList = noticeUserDto.getPushClientId().stream() List<String> filteredList = noticeUserDto.getPushClientId().stream()
//过滤掉null
.filter(Objects::nonNull) .filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList()); .collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(filteredList)) {
noticeUserDto.setPushClientId(filteredList); noticeUserDto.setPushClientId(filteredList);
sendEventToUser(noticeUserDto); sendEventToUser(noticeUserDto);
} }
}
//记录推送日志 //记录推送日志
for (User item : users) { for (User item : users) {
CsEventSendMsg csEventSendMsg = new CsEventSendMsg(); CsEventSendMsg csEventSendMsg = new CsEventSendMsg();
@@ -294,18 +297,17 @@ public class SendEventUtils {
} }
} }
/** /**
* 获取所有需要推送的用户id * 获取所有需要推送的用户id
*/ */
public List<String> getEventUser(String devId,boolean isAdmin) { public List<String> getEventUser(String devId,boolean isAdmin) {
List<String> list = csDeviceUserFeignClient.findUserById(devId).getData();
if (isAdmin) {
List<User> adminUser = appUserFeignClient.getAdminInfo().getData(); List<User> adminUser = appUserFeignClient.getAdminInfo().getData();
List<String> adminList = adminUser.stream().map(User::getId).collect(Collectors.toList()); List<String> adminList = adminUser.stream().map(User::getId).collect(Collectors.toList());
list.addAll(adminList); if (isAdmin) {
List<String> list = csDeviceUserFeignClient.findUserById(devId).getData();
adminList.addAll(list);
} }
return list; return adminList;
} }

View File

@@ -71,6 +71,11 @@
<artifactId>zl-event-api</artifactId> <artifactId>zl-event-api</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@@ -45,6 +45,8 @@ public class AppAutoDataConsumer extends EnhanceConsumerMessageHandler<AppAutoDa
@Resource @Resource
private RocketMqLogFeignClient rocketMqLogFeignClient; private RocketMqLogFeignClient rocketMqLogFeignClient;
// @Resource
// private WlRecordFeignClient wlRecordFeignClient;
@Override @Override
protected void handleMessage(AppAutoDataMessage appAutoDataMessage) { protected void handleMessage(AppAutoDataMessage appAutoDataMessage) {

View File

@@ -11,6 +11,7 @@ import com.njcn.system.api.RocketMqLogFeignClient;
import com.njcn.system.pojo.po.RocketmqMsgErrorLog; import com.njcn.system.pojo.po.RocketmqMsgErrorLog;
import com.njcn.zlevent.api.AlarmFeignClient; import com.njcn.zlevent.api.AlarmFeignClient;
import com.njcn.zlevent.api.EventFeignClient; import com.njcn.zlevent.api.EventFeignClient;
import com.njcn.zlevent.api.EvtErrorFeignClient;
import com.njcn.zlevent.api.WaveFeignClient; import com.njcn.zlevent.api.WaveFeignClient;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
@@ -40,17 +41,16 @@ public class AppEventConsumer extends EnhanceConsumerMessageHandler<AppEventMess
@Resource @Resource
private RedisUtil redisUtil; private RedisUtil redisUtil;
@Resource @Resource
private RocketMqLogFeignClient rocketMqLogFeignClient; private RocketMqLogFeignClient rocketMqLogFeignClient;
@Resource @Resource
private EventFeignClient eventFeignClient; private EventFeignClient eventFeignClient;
@Resource @Resource
private WaveFeignClient waveFeignClient; private WaveFeignClient waveFeignClient;
@Resource @Resource
private AlarmFeignClient alarmFeignClient; private AlarmFeignClient alarmFeignClient;
@Resource
private EvtErrorFeignClient evtErrorFeignClient;
@Override @Override
protected void handleMessage(AppEventMessage appEventMessage) { protected void handleMessage(AppEventMessage appEventMessage) {
@@ -68,6 +68,14 @@ public class AppEventConsumer extends EnhanceConsumerMessageHandler<AppEventMess
log.info("分发至录波报文处理"); log.info("分发至录波报文处理");
waveFeignClient.analysis(appEventMessage); waveFeignClient.analysis(appEventMessage);
break; break;
case 32:
log.info("分发至便携式基础数据处理");
eventFeignClient.getPortableData(appEventMessage);
break;
case 241:
log.info("分发装置异常事件统计");
evtErrorFeignClient.insertErrorEvent(appEventMessage);
break;
default: default:
break; break;
} }