diff --git a/user-service/pom.xml b/user-service/pom.xml
index b676a6d..aaefc8a 100644
--- a/user-service/pom.xml
+++ b/user-service/pom.xml
@@ -74,11 +74,11 @@
mssql-jdbc
runtime
-
- io.netty
- netty-all
- 5.0.0.Alpha2
-
+
+
+
+
+
com.github.penggle
diff --git a/user-service/src/main/java/com/mh/user/controller/SerialPortController.java b/user-service/src/main/java/com/mh/user/controller/SerialPortController.java
index 283dfa6..06eef65 100644
--- a/user-service/src/main/java/com/mh/user/controller/SerialPortController.java
+++ b/user-service/src/main/java/com/mh/user/controller/SerialPortController.java
@@ -42,181 +42,181 @@ public class SerialPortController {
NowDataService nowDataService;
//操作设备
- @SysLogger(title="控制管理",optDesc = "设置设备参数值")
- @PostMapping(value="/operate")
- public HttpResult operateDevice(@RequestBody List params){
- try{
+ @SysLogger(title = "控制管理", optDesc = "设置设备参数值")
+ @PostMapping(value = "/operate")
+ public HttpResult operateDevice(@RequestBody List params) {
+ try {
SerialPortSingle serialPortSingle = new SerialPortSingle(); //发送接收类
- DeviceCodeParamEntity deviceCodeParam=new DeviceCodeParamEntity();//参数实体类
+ DeviceCodeParamEntity deviceCodeParam = new DeviceCodeParamEntity();//参数实体类
- Constant.WEB_FLAG=true; //单抄,暂时停止采集
+ Constant.WEB_FLAG = true; //单抄,暂时停止采集
for (SerialPortModel serialPortModel :
params) {
- String deviceAddr=serialPortModel.getDeviceAddr();//设备通讯地址
- String deviceType=serialPortModel.getDeviceType();//设备类型
- String buildingId=serialPortModel.getBuildingId();//楼栋
- String param=serialPortModel.getParam();//操作参数
- if (deviceAddr==null || deviceAddr=="" ){
- List list=deviceInstallService.selectDevices(buildingId,deviceType);
- deviceAddr=list.get(0).getDeviceAddr();
+ String deviceAddr = serialPortModel.getDeviceAddr();//设备通讯地址
+ String deviceType = serialPortModel.getDeviceType();//设备类型
+ String buildingId = serialPortModel.getBuildingId();//楼栋
+ String param = serialPortModel.getParam();//操作参数
+ if (deviceAddr == null || deviceAddr.equals("")) {
+ List list = deviceInstallService.selectDevices(buildingId, deviceType);
+ deviceAddr = list.get(0).getDeviceAddr();
}
- if(deviceAddr!=null && deviceAddr.length()>0){
- DeviceInstallEntity deviceInstallEntity=deviceInstallService.selectDevice(deviceAddr,deviceType,buildingId);
- //发送指令实体类
- deviceCodeParam.setDeviceAddr(deviceAddr); //传入通讯编号
- deviceCodeParam.setDeviceType(deviceType);
- deviceCodeParam.setDataCom(deviceInstallEntity.getDataCom());
- deviceCodeParam.setBaudrate(deviceInstallEntity.getBaudRate());
- deviceCodeParam.setParity(deviceInstallEntity.getParity());
- deviceCodeParam.setDataValue(serialPortModel.getDataValue());//传入相关参数值
- deviceCodeParam.setBuildingId(buildingId);
- String brand=deviceInstallEntity.getBrand();//品牌
- deviceCodeParam.setBrand(brand);
+ if (deviceAddr == null || deviceAddr.length() == 0) {
+ Constant.WEB_FLAG = false;
+ return HttpResult.error("通讯ID为空!");
+ }
+ DeviceInstallEntity deviceInstallEntity = deviceInstallService.selectDevice(deviceAddr, deviceType, buildingId);
+ //发送指令实体类
+ deviceCodeParam.setDeviceAddr(deviceAddr); //传入通讯编号
+ deviceCodeParam.setDeviceType(deviceType);
+ deviceCodeParam.setDataCom(deviceInstallEntity.getDataCom());
+ deviceCodeParam.setBaudrate(deviceInstallEntity.getBaudRate());
+ deviceCodeParam.setParity(deviceInstallEntity.getParity());
+ deviceCodeParam.setDataValue(serialPortModel.getDataValue());//传入相关参数值
+ deviceCodeParam.setBuildingId(buildingId);
+ String brand = deviceInstallEntity.getBrand();//品牌
+ deviceCodeParam.setBrand(brand);
- ControlSetEntity controlData=new ControlSetEntity();
- //设置设备实体对象
- controlData.setBuildingId(deviceInstallEntity.getBuildingId());
+ ControlSetEntity controlData = new ControlSetEntity();
+ //设置设备实体对象
+ controlData.setBuildingId(deviceInstallEntity.getBuildingId());
- if (deviceType==null || deviceType.equals("") || deviceType.equals("热泵")){
- //设置热泵实体对象
- PumpSetEntity pumpData=new PumpSetEntity();
- pumpData.setBuildingId(deviceInstallEntity.getBuildingId());
- pumpData.setPumpId(deviceAddr);
- if (param==null || param.equals("") || param.equals("温度设定")){
+ if (deviceType == null || deviceType.equals("") || deviceType.equals("热泵")) {
+ //设置热泵实体对象
+ PumpSetEntity pumpData = new PumpSetEntity();
+ pumpData.setBuildingId(deviceInstallEntity.getBuildingId());
+ pumpData.setPumpId(deviceAddr);
+ if (param == null || param.equals("") || param.equals("温度设定")) {
+ //发送指令
+ if (brand.equals("美的")) {
+ deviceCodeParam.setRegisterAddr("0642"); //寄存器地址
+ deviceCodeParam.setFunCode("10"); //功能码写数据
+ } else {
+ deviceCodeParam.setRegisterAddr("0003"); //寄存器地址
+ deviceCodeParam.setFunCode("06"); //功能码写数据
+ }
+ //保存数据
+ pumpData.setTempSet(serialPortModel.getDataValue());
+ pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
+
+ nowDataService.upTempSet2(buildingId, serialPortModel.getDataValue(), deviceAddr);//更新实时状态表
+ log.info("楼栋编号:" + buildingId + ",设定温度:" + serialPortModel.getDataValue() + ",热泵编号:" + deviceAddr);
+ } else if (param.equals("时段1")) {
+ if (brand.equals("美的")) {
//发送指令
- if (brand.equals("美的")){
- deviceCodeParam.setRegisterAddr("0642"); //寄存器地址
- deviceCodeParam.setFunCode("10"); //功能码写数据
- }else{
- deviceCodeParam.setRegisterAddr("0003"); //寄存器地址
- deviceCodeParam.setFunCode("06"); //功能码写数据
- }
+ deviceCodeParam.setRegisterAddr("0656"); //寄存器地址
+ deviceCodeParam.setFunCode("10"); //功能码写数据
//保存数据
- pumpData.setTempSet(serialPortModel.getDataValue());
- pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
-
- nowDataService.upTempSet2(buildingId,serialPortModel.getDataValue(),deviceAddr);//更新实时状态表
- log.info("楼栋编号:"+buildingId+",设定温度:"+serialPortModel.getDataValue()+",热泵编号:"+deviceAddr);
- }else if(param.equals("时段1")){
- if (brand.equals("美的")) {
- //发送指令
- deviceCodeParam.setRegisterAddr("0656"); //寄存器地址
- deviceCodeParam.setFunCode("10"); //功能码写数据
- //保存数据
- String time=serialPortModel.getDataValue();
- if (time.length()==8){
- String statTime=time.substring(0,2)+":"+time.substring(2,4);
- String closeTime=time.substring(4,6)+":"+time.substring(6,8);
- pumpData.setStartTime1(statTime);
- pumpData.setCloseTime1(closeTime);
- }
- pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
- }
- }else if(param.equals("时段2")){
- if (brand.equals("美的")) {
- //发送指令
- deviceCodeParam.setRegisterAddr("065A"); //寄存器地址
- deviceCodeParam.setFunCode("10"); //功能码写数据
- //保存数据
- String time=serialPortModel.getDataValue();
- if (time.length()==8){
- String statTime=time.substring(0,2)+":"+time.substring(2,4);
- String closeTime=time.substring(4,6)+":"+time.substring(6,8);
- pumpData.setStartTime2(statTime);
- pumpData.setCloseTime2(closeTime);
- }
- pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
+ String time = serialPortModel.getDataValue();
+ if (time.length() == 8) {
+ String statTime = time.substring(0, 2) + ":" + time.substring(2, 4);
+ String closeTime = time.substring(4, 6) + ":" + time.substring(6, 8);
+ pumpData.setStartTime1(statTime);
+ pumpData.setCloseTime1(closeTime);
}
+ pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
}
- }else if (deviceType.equals("时控")){
- deviceCodeParam.setFunCode("10"); //功能码写数据
- String time=serialPortModel.getDataValue();
- if (time.length()==16){
- //时段1 HHmmHHmm
- String statTime1=time.substring(0,2)+":"+time.substring(2,4); //HH:mm
- String closeTime1=time.substring(4,6)+":"+time.substring(6,8); //HH:mm
- //时段2
- String statTime2=time.substring(8,10)+":"+time.substring(10,12);
- String closeTime2=time.substring(12,14)+":"+time.substring(14,16);
- if(param.equals("L1")){
- deviceCodeParam.setRegisterAddr("0009"); //寄存器地址,L3路,L1(0009),L2(000D)
- controlData.setUseStartTime1(statTime1);
- controlData.setUseCloseTime1(closeTime1);
- controlData.setUseStartTime2(statTime2);
- controlData.setUseCloseTime2(closeTime2);
- }else if(param.equals("L2")){
- deviceCodeParam.setRegisterAddr("000D");
- controlData.setUseStartTime3(statTime1);
- controlData.setUseCloseTime3(closeTime1);
- controlData.setUseStartTime4(statTime2);
- controlData.setUseCloseTime4(closeTime2);
- }else{
- deviceCodeParam.setRegisterAddr("0011");
- controlData.setUseStartTime5(statTime1);
- controlData.setUseCloseTime5(closeTime1);
- controlData.setUseStartTime6(statTime2);
- controlData.setUseCloseTime6(closeTime2);
+ } else if (param.equals("时段2")) {
+ if (brand.equals("美的")) {
+ //发送指令
+ deviceCodeParam.setRegisterAddr("065A"); //寄存器地址
+ deviceCodeParam.setFunCode("10"); //功能码写数据
+ //保存数据
+ String time = serialPortModel.getDataValue();
+ if (time.length() == 8) {
+ String statTime = time.substring(0, 2) + ":" + time.substring(2, 4);
+ String closeTime = time.substring(4, 6) + ":" + time.substring(6, 8);
+ pumpData.setStartTime2(statTime);
+ pumpData.setCloseTime2(closeTime);
}
+ pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
}
- controlSetService.saveControlSet(controlData); //保存设置内容
- }else if (deviceType.equals("水位开关")){
- if (brand==null || brand.equals("") || brand.equals("中凯")){//品牌
- deviceCodeParam.setFunCode("12"); //功能码写数据
- if (!serialPortModel.getDataValue().equals("100%")){
- deviceCodeParam.setDataValue("100%");
- serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- Thread.sleep(1500);
- }
- }else if(brand.equals("远向")){
- deviceCodeParam.setFunCode("06"); //功能码写数据
- if (!serialPortModel.getDataValue().equals("100%")){
- deviceCodeParam.setDataValue("100%");
- serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- Thread.sleep(1500);
- }
- }else if(brand.equals("顶威")){
- deviceCodeParam.setFunCode("0407"); //功能码写数据
+ }
+ } else if (deviceType.equals("时控")) {
+ deviceCodeParam.setFunCode("10"); //功能码写数据
+ String time = serialPortModel.getDataValue();
+ if (time.length() == 16) {
+ //时段1 HHmmHHmm
+ String statTime1 = time.substring(0, 2) + ":" + time.substring(2, 4); //HH:mm
+ String closeTime1 = time.substring(4, 6) + ":" + time.substring(6, 8); //HH:mm
+ //时段2
+ String statTime2 = time.substring(8, 10) + ":" + time.substring(10, 12);
+ String closeTime2 = time.substring(12, 14) + ":" + time.substring(14, 16);
+ if (param.equals("L1")) {
+ deviceCodeParam.setRegisterAddr("0009"); //寄存器地址,L3路,L1(0009),L2(000D)
+ controlData.setUseStartTime1(statTime1);
+ controlData.setUseCloseTime1(closeTime1);
+ controlData.setUseStartTime2(statTime2);
+ controlData.setUseCloseTime2(closeTime2);
+ } else if (param.equals("L2")) {
+ deviceCodeParam.setRegisterAddr("000D");
+ controlData.setUseStartTime3(statTime1);
+ controlData.setUseCloseTime3(closeTime1);
+ controlData.setUseStartTime4(statTime2);
+ controlData.setUseCloseTime4(closeTime2);
+ } else {
+ deviceCodeParam.setRegisterAddr("0011");
+ controlData.setUseStartTime5(statTime1);
+ controlData.setUseCloseTime5(closeTime1);
+ controlData.setUseStartTime6(statTime2);
+ controlData.setUseCloseTime6(closeTime2);
}
- deviceCodeParam.setDataValue(serialPortModel.getDataValue());
- //controlData.setLevelSet(serialPortModel.getDataValue());
- //controlSetService.saveControlSet(controlData);
- nowDataService.upLevelSet(buildingId,serialPortModel.getDataValue());//更新实时状态表
}
- serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- }else{
- return HttpResult.error("通讯ID为空!");
+ controlSetService.saveControlSet(controlData); //保存设置内容
+ } else if (deviceType.equals("水位开关")) {
+ if (brand == null || brand.equals("") || brand.equals("中凯")) {//品牌
+ deviceCodeParam.setFunCode("12"); //功能码写数据
+ if (!serialPortModel.getDataValue().equals("100%")) {
+ deviceCodeParam.setDataValue("100%");
+ serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ Thread.sleep(1500);
+ }
+ } else if (brand.equals("远向")) {
+ deviceCodeParam.setFunCode("06"); //功能码写数据
+ if (!serialPortModel.getDataValue().equals("100%")) {
+ deviceCodeParam.setDataValue("100%");
+ serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ Thread.sleep(1500);
+ }
+ } else if (brand.equals("顶威")) {
+ deviceCodeParam.setFunCode("0407"); //功能码写数据
+ }
+ deviceCodeParam.setDataValue(serialPortModel.getDataValue());
+ //controlData.setLevelSet(serialPortModel.getDataValue());
+ //controlSetService.saveControlSet(controlData);
+ nowDataService.upLevelSet(buildingId, serialPortModel.getDataValue());//更新实时状态表
}
+ serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
}
- Constant.WEB_FLAG=false; //单抄,恢复采集
+ Constant.WEB_FLAG = false; //单抄,恢复采集
return HttpResult.ok();
- }catch(Exception e){
+ } catch (Exception e) {
// e.printStackTrace();
- Constant.WEB_FLAG=false; //单抄,恢复采集
- return HttpResult.error(500,"fail");
+ Constant.WEB_FLAG = false; //单抄,恢复采集
+ return HttpResult.error(500, "fail");
}
}
//读数据
- @SysLogger(title="控制管理",optDesc = "读设备数据")
- @PostMapping(value="/read")
- public HttpResult readData(@RequestBody List params){
- try{
+ @SysLogger(title = "控制管理", optDesc = "读设备数据")
+ @PostMapping(value = "/read")
+ public HttpResult readData(@RequestBody List params) {
+ try {
SerialPortSingle serialPortSingle = new SerialPortSingle();
- DeviceCodeParamEntity deviceCodeParam=new DeviceCodeParamEntity();
- String rtData=""; //返回值
- Constant.WEB_FLAG=true; //单抄,暂时停止采集
+ DeviceCodeParamEntity deviceCodeParam = new DeviceCodeParamEntity();
+ String rtData = ""; //返回值
+ Constant.WEB_FLAG = true; //单抄,暂时停止采集
for (SerialPortModel serialPortModel :
params) {
- String deviceAddr=serialPortModel.getDeviceAddr();//设备通讯地址
- String deviceType=serialPortModel.getDeviceType();//设备类型
- String buildingId=serialPortModel.getBuildingId();//楼栋
- String param=serialPortModel.getParam();//操作参数
- if (deviceAddr==null || deviceAddr=="" ){
- List list=deviceInstallService.selectDevices(buildingId,deviceType);
- deviceAddr=list.get(0).getDeviceAddr();
+ String deviceAddr = serialPortModel.getDeviceAddr();//设备通讯地址
+ String deviceType = serialPortModel.getDeviceType();//设备类型
+ String buildingId = serialPortModel.getBuildingId();//楼栋
+ String param = serialPortModel.getParam();//操作参数
+ if (deviceAddr == null || deviceAddr == "") {
+ List list = deviceInstallService.selectDevices(buildingId, deviceType);
+ deviceAddr = list.get(0).getDeviceAddr();
}
- if(deviceAddr!=null && deviceAddr.length()>0){
- DeviceInstallEntity deviceInstallEntity=deviceInstallService.selectDevice(deviceAddr,deviceType,buildingId);
+ if (deviceAddr != null && deviceAddr.length() > 0) {
+ DeviceInstallEntity deviceInstallEntity = deviceInstallService.selectDevice(deviceAddr, deviceType, buildingId);
//发送指令实体类
deviceCodeParam.setDeviceAddr(deviceAddr);
deviceCodeParam.setDeviceType(deviceType);
@@ -225,114 +225,114 @@ public class SerialPortController {
deviceCodeParam.setParity(deviceInstallEntity.getParity());
deviceCodeParam.setDataValue(serialPortModel.getDataValue());//传入相关参数值
deviceCodeParam.setBuildingId(buildingId);
- String brand=deviceInstallEntity.getBrand();//品牌
+ String brand = deviceInstallEntity.getBrand();//品牌
deviceCodeParam.setBrand(brand);
//设置设备实体对象
- ControlSetEntity controlData=new ControlSetEntity();
+ ControlSetEntity controlData = new ControlSetEntity();
controlData.setBuildingId(deviceInstallEntity.getBuildingId());
- if (deviceType==null || deviceType.equals("") || deviceType.equals("热泵")){
+ if (deviceType == null || deviceType.equals("") || deviceType.equals("热泵")) {
//设置热泵实体对象
- PumpSetEntity pumpData=new PumpSetEntity();
+ PumpSetEntity pumpData = new PumpSetEntity();
pumpData.setBuildingId(deviceInstallEntity.getBuildingId());
pumpData.setPumpId(deviceAddr);
- if (param==null || param.equals("") || param.equals("读温度设定")){
+ if (param == null || param.equals("") || param.equals("读温度设定")) {
deviceCodeParam.setFunCode("03"); //功能码读数据
- if (brand.equals("美的")){
+ if (brand.equals("美的")) {
deviceCodeParam.setRegisterAddr("0642"); //寄存器地址
- }else{
+ } else {
deviceCodeParam.setRegisterAddr("0003"); //寄存器地址
}
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- if (!rtData.equals("")){
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ if (!rtData.equals("")) {
pumpData.setTempSet(rtData);
pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
}
- } else if (param.equals("实际温度")){
+ } else if (param.equals("实际温度")) {
deviceCodeParam.setFunCode("03"); //功能码读数据
- if (brand.equals("美的")){
+ if (brand.equals("美的")) {
deviceCodeParam.setRegisterAddr("0007"); //寄存器地址
- }else{
+ } else {
deviceCodeParam.setRegisterAddr("0064"); //寄存器地址
}
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- if (!rtData.equals("")){
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ if (!rtData.equals("")) {
pumpData.setWaterTemp(rtData);
pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
}
- } else if (param.equals("运行状态")){
+ } else if (param.equals("运行状态")) {
deviceCodeParam.setFunCode("03"); //功能码读数据
- if (brand.equals("美的")){
+ if (brand.equals("美的")) {
deviceCodeParam.setRegisterAddr("0641"); //寄存器地址
- }else{
+ } else {
deviceCodeParam.setRegisterAddr("0BBD"); //寄存器地址
}
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
//pumpData(rtData);
//pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
- } else if(param.equals("时段1")){
+ } else if (param.equals("时段1")) {
if (brand.equals("美的")) {
//发送指令
deviceCodeParam.setRegisterAddr("0656"); //寄存器地址
deviceCodeParam.setFunCode("03"); //功能码读数据
//保存数据
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- String time=rtData;
- if (time.length()==8){
- String statTime=time.substring(0,2)+":"+time.substring(2,4);
- String closeTime=time.substring(4,6)+":"+time.substring(6,8);
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ String time = rtData;
+ if (time.length() == 8) {
+ String statTime = time.substring(0, 2) + ":" + time.substring(2, 4);
+ String closeTime = time.substring(4, 6) + ":" + time.substring(6, 8);
pumpData.setStartTime1(statTime);
pumpData.setCloseTime1(closeTime);
}
pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
}
- }else if(param.equals("时段2")){
+ } else if (param.equals("时段2")) {
if (brand.equals("美的")) {
//发送指令
deviceCodeParam.setRegisterAddr("065A"); //寄存器地址
deviceCodeParam.setFunCode("03"); //功能码读数据
//保存数据
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- String time=rtData;
- if (time.length()==8){
- String statTime=time.substring(0,2)+":"+time.substring(2,4);
- String closeTime=time.substring(4,6)+":"+time.substring(6,8);
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ String time = rtData;
+ if (time.length() == 8) {
+ String statTime = time.substring(0, 2) + ":" + time.substring(2, 4);
+ String closeTime = time.substring(4, 6) + ":" + time.substring(6, 8);
pumpData.setStartTime2(statTime);
pumpData.setCloseTime2(closeTime);
}
pumpSetService.savePumpSet(pumpData);//热泵信息保存数据库
}
}
- }else if (deviceType.equals("时控")){
- if(param.equals("L1")){
+ } else if (deviceType.equals("时控")) {
+ if (param.equals("L1")) {
deviceCodeParam.setRegisterAddr("0009"); //寄存器地址,L3路,L1(0009),L2(000D)
- }else if(param.equals("L2")){
+ } else if (param.equals("L2")) {
deviceCodeParam.setRegisterAddr("000D");
- }else{
+ } else {
deviceCodeParam.setRegisterAddr("0011");
}
deviceCodeParam.setFunCode("03"); //功能码读数据
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- String time=rtData;
- if (time.length()==16){
+ String time = rtData;
+ if (time.length() == 16) {
//时段1
- String statTime1=time.substring(0,2)+":"+time.substring(2,4);
- String closeTime1=time.substring(4,6)+":"+time.substring(6,8);
+ String statTime1 = time.substring(0, 2) + ":" + time.substring(2, 4);
+ String closeTime1 = time.substring(4, 6) + ":" + time.substring(6, 8);
//时段2
- String statTime2=time.substring(8,10)+":"+time.substring(10,12);
- String closeTime2=time.substring(12,14)+":"+time.substring(14,16);
+ String statTime2 = time.substring(8, 10) + ":" + time.substring(10, 12);
+ String closeTime2 = time.substring(12, 14) + ":" + time.substring(14, 16);
- if(param.equals("L1")){
+ if (param.equals("L1")) {
controlData.setUseStartTime1(statTime1);
controlData.setUseCloseTime1(closeTime1);
controlData.setUseStartTime2(statTime2);
controlData.setUseCloseTime2(closeTime2);
- }else if(param.equals("L2")){
+ } else if (param.equals("L2")) {
controlData.setUseStartTime3(statTime1);
controlData.setUseCloseTime3(closeTime1);
controlData.setUseStartTime4(statTime2);
controlData.setUseCloseTime4(closeTime2);
- }else{
+ } else {
controlData.setUseStartTime5(statTime1);
controlData.setUseCloseTime5(closeTime1);
controlData.setUseStartTime6(statTime2);
@@ -340,83 +340,83 @@ public class SerialPortController {
}
}
controlSetService.saveControlSet(controlData); //保存设置内容
- }else if (deviceType.equals("水位开关") && !param.equals("状态")){
- if (brand==null || brand.equals("") || brand.equals("中凯")){//品牌
+ } else if (deviceType.equals("水位开关") && !param.equals("状态")) {
+ if (brand == null || brand.equals("") || brand.equals("中凯")) {//品牌
deviceCodeParam.setFunCode("17"); //功能码读
deviceCodeParam.setRegisterAddr("0017");
- }else if(brand.equals("远向")){
+ } else if (brand.equals("远向")) {
deviceCodeParam.setFunCode("03"); //功能码读
deviceCodeParam.setRegisterAddr("0018");
- }else if(brand.equals("顶威")){
+ } else if (brand.equals("顶威")) {
deviceCodeParam.setFunCode("0102"); //功能码读
deviceCodeParam.setRegisterAddr("0102");
}
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
deviceCodeParam.setDataValue(rtData);
//controlData.setLevelSet(serialPortModel.getDataValue());
//controlSetService.saveControlSet(controlData);
- log.info("--------------读取返回数据:"+rtData+"------------------");
- }else if (deviceType.equals("水位开关") && param.equals("状态")){
- if(brand.equals("远向")){
+ log.info("--------------读取返回数据:" + rtData + "------------------");
+ } else if (deviceType.equals("水位开关") && param.equals("状态")) {
+ if (brand.equals("远向")) {
deviceCodeParam.setFunCode("03"); //功能码读
deviceCodeParam.setRegisterAddr("0010");
}
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- }else if (deviceType.equals("温度变送器")){
+ } else if (deviceType.equals("温度变送器")) {
deviceCodeParam.setFunCode("03"); //功能码读
deviceCodeParam.setRegisterAddr("0028");
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- }else if (deviceType.equals("压变")){
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ } else if (deviceType.equals("压变")) {
deviceCodeParam.setFunCode("03"); //功能码读
deviceCodeParam.setRegisterAddr("0004");
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
- }else if (deviceType.equals("水表")){
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);
- }else if (deviceType.equals("电表")){
- rtData=serialPortSingle.serialPortSend(deviceCodeParam);
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
+ } else if (deviceType.equals("水表")) {
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);
+ } else if (deviceType.equals("电表")) {
+ rtData = serialPortSingle.serialPortSend(deviceCodeParam);
}
- }else{
- return HttpResult.error(500,"fail");
+ } else {
+ return HttpResult.error(500, "fail");
}
}
- Constant.WEB_FLAG=false; //单抄,恢复采集
- if(ExchangeStringUtil.getJSONType(rtData)){
- Map map = JSONObject.parseObject(rtData);
- return HttpResult.ok("success",map);
- }else{
- if(rtData.equals("fail")){
- return HttpResult.error(500,"fail");
- }else{
- return HttpResult.ok(rtData,rtData);
+ Constant.WEB_FLAG = false; //单抄,恢复采集
+ if (ExchangeStringUtil.getJSONType(rtData)) {
+ Map map = JSONObject.parseObject(rtData);
+ return HttpResult.ok("success", map);
+ } else {
+ if (rtData.equals("fail")) {
+ return HttpResult.error(500, "fail");
+ } else {
+ return HttpResult.ok(rtData, rtData);
}
}
- }catch (Exception e){
- Constant.WEB_FLAG=false; //单抄,恢复采集
- return HttpResult.error(500,"fail");
+ } catch (Exception e) {
+ Constant.WEB_FLAG = false; //单抄,恢复采集
+ return HttpResult.error(500, "fail");
}
}
- @PostMapping(value="/pump")
- public HttpResult queryPumpSet(@RequestParam(value = "pumpId",defaultValue = "2") String pumpId,
- @RequestParam(value = "buildingId") String buildingId){
- try{
- PumpSetEntity list=pumpSetService.queryPumpSet(pumpId,buildingId);
+ @PostMapping(value = "/pump")
+ public HttpResult queryPumpSet(@RequestParam(value = "pumpId", defaultValue = "2") String pumpId,
+ @RequestParam(value = "buildingId") String buildingId) {
+ try {
+ PumpSetEntity list = pumpSetService.queryPumpSet(pumpId, buildingId);
return HttpResult.ok(list);
- }catch (Exception e){
+ } catch (Exception e) {
//e.printStackTrace();
return HttpResult.error();
}
}
- @PostMapping(value="/control")
- public HttpResult queryControlSet(@RequestParam(value = "buildingId") String buildingId){
- try{
- ControlSetEntity list=controlSetService.queryControlSet(buildingId);
+ @PostMapping(value = "/control")
+ public HttpResult queryControlSet(@RequestParam(value = "buildingId") String buildingId) {
+ try {
+ ControlSetEntity list = controlSetService.queryControlSet(buildingId);
return HttpResult.ok(list);
- }catch (Exception e){
- // e.printStackTrace();
+ } catch (Exception e) {
+ // e.printStackTrace();
return HttpResult.error();
}
}
diff --git a/user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java b/user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java
index 3437208..7b8b716 100644
--- a/user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java
+++ b/user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java
@@ -60,8 +60,8 @@ public class CollectionLoopRunner implements ApplicationRunner {
if (r2==0){
getReadOrder485.createOrderParam3(); //生成采集参数
}
- // 生成指令缓存
- //CacheUtil instance = CacheUtil.getInstance();
+ // 分组参数缓存
+ CacheUtil instance = CacheUtil.getInstance();
}
public void test() throws Exception {
diff --git a/user-service/src/main/java/com/mh/user/job/DealDataJob.java b/user-service/src/main/java/com/mh/user/job/DealDataJob.java
index 331543e..f575d19 100644
--- a/user-service/src/main/java/com/mh/user/job/DealDataJob.java
+++ b/user-service/src/main/java/com/mh/user/job/DealDataJob.java
@@ -12,8 +12,10 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
+
import java.text.SimpleDateFormat;
import java.util.Date;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
/**
@@ -30,12 +32,11 @@ public class DealDataJob {
private final DealDataService dealDataService;
@Autowired
- private DeviceCodeParamService deviceCodeParamService;
+ private DeviceCodeParamService deviceCodeParamService;
private static int taskTimes = 1;
- public DealDataJob(DealDataService dealDataService)
- {
+ public DealDataJob(DealDataService dealDataService) {
this.dealDataService = dealDataService;
}
@@ -47,13 +48,13 @@ public class DealDataJob {
@Scheduled(cron = "0 0/15 * * * ?")
public void ProEnergy() {
try {
- SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:00:00");
- Date date=new Date();
- String curDate=sdf1.format(date);
- String name=dealDataService.customName();
- if (name!=null && name.length()>0 && name.contains("华夏学院")){
+ SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
+ Date date = new Date();
+ String curDate = sdf1.format(date);
+ String name = dealDataService.customName();
+ if (name != null && name.length() > 0 && name.contains("华夏学院")) {
dealDataService.proEnergy2(curDate);
- }else{
+ } else {
dealDataService.proEnergy(curDate); //yyyy-MM-dd HH:00:00
}
dealDataService.proGatewayState(); //判断网关在线状态:在线或离线
@@ -64,6 +65,7 @@ public class DealDataJob {
//Constant.WEB_FLAG=false;
}
}
+
/**
* 采集
*/
@@ -72,49 +74,54 @@ public class DealDataJob {
// @Scheduled(cron = "0 0/5 * * * ?") //5分钟
public void collect() {
try {
- log.info("------定时采集开始>>>>Constant.FLAG=="+Constant.FLAG+"------");
- if(!Constant.FLAG){
- if(!Constant.WEB_FLAG){
- Constant.FLAG=true;
- log.info("------Constant.WEB_FLAG=="+ false +"------");
+ log.info("------定时采集开始>>>>Constant.FLAG==" + Constant.FLAG + "------");
+ if (!Constant.FLAG) {
+ if (!Constant.WEB_FLAG) {
+ Constant.FLAG = true;
+ log.info("------Constant.WEB_FLAG==" + false + "------");
for (int i = 1; i <= 4; i++) {
String threadName;
if (i == 1 || i == 3) {
threadName = "1";
- log.info("------采集水位、水温!"+i+"------");
+ log.info("------采集水位、水温!" + i + "------");
} else if (i == 2) {
threadName = "2";
- log.info("------采集水、电、运行状态!"+i+"------");
+ log.info("------采集水、电、运行状态!" + i + "------");
} else {
threadName = "3";
- log.info("------采集设定温度、设定水位、故障状态!"+i+"------");
+ log.info("------采集设定温度、设定水位、故障状态!" + i + "------");
}
- for(int j=1;j<11;j++){
+ CountDownLatch countDownLatch = new CountDownLatch(10);
+ for (int j = 1; j < 11; j++) {
SerialPortThread myThread = new SerialPortThread();
+ myThread.setName(threadName, String.valueOf(j), countDownLatch);
Thread thread = new Thread(myThread);
- myThread.setName(threadName, String.valueOf(j));
comThreadPool.execute(thread);
}
+ countDownLatch.await();
}
}
}
} catch (Exception e) {
- e.printStackTrace();
+ log.error("定时采集异常==>", e);
+ } finally {
+ Constant.FLAG = false;
}
}
+
/**
* 定时处理数据:每十五分钟处理一次
*/
@Scheduled(cron = "0 0/15 * * * ?")
public void dealData() {
try {
- SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
- Date date=new Date();
- String curDate=sdf1.format(date);
- String name=dealDataService.customName();
- if (name!=null && name.length()>0 && name.contains("华夏学院")){
+ SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
+ Date date = new Date();
+ String curDate = sdf1.format(date);
+ String name = dealDataService.customName();
+ if (name != null && name.length() > 0 && name.contains("华夏学院")) {
dealDataService.proEnergySum2(curDate);
- }else{
+ } else {
dealDataService.proEnergySum(curDate);
}
dealDataService.proMaintainSum(curDate); //汇总维修数
diff --git a/user-service/src/main/java/com/mh/user/job/JobCloud.java b/user-service/src/main/java/com/mh/user/job/JobCloud.java
index d627f86..0ef5c67 100644
--- a/user-service/src/main/java/com/mh/user/job/JobCloud.java
+++ b/user-service/src/main/java/com/mh/user/job/JobCloud.java
@@ -1,41 +1,41 @@
-package com.mh.user.job;
-
-import com.mh.user.netty.NettyClient;
-import com.mh.user.constants.SocketMessage;
-import lombok.SneakyThrows;
-import lombok.extern.slf4j.Slf4j;
-import org.quartz.DisallowConcurrentExecution;
-import org.quartz.Job;
-import org.quartz.JobExecutionContext;
-import org.quartz.JobExecutionException;
-import org.springframework.beans.factory.annotation.Autowired;
-
-/**
- * @author ljf
- * @title :
- * @description : 定时采集冷量计任务
- * @updateTime 2020-05-18
- * @throws :
- */
-/**
- * :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
- * :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
- * :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
- * 否则会在3秒时再启用新的线程执行
- */
-@DisallowConcurrentExecution
-@Slf4j
-public class JobCloud implements Job {
-
- @Autowired
- private SocketMessage socketMessage;
-
- @SneakyThrows
- @Override
- public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
- // 定时采集冷量计
- log.info("定时采集冷量计");
- NettyClient nettyClient = new NettyClient();
- nettyClient.connect(socketMessage.getPort(),socketMessage.getIP());
- }
-}
+//package com.mh.user.job;
+//
+//import com.mh.user.netty.NettyClient;
+//import com.mh.user.constants.SocketMessage;
+//import lombok.SneakyThrows;
+//import lombok.extern.slf4j.Slf4j;
+//import org.quartz.DisallowConcurrentExecution;
+//import org.quartz.Job;
+//import org.quartz.JobExecutionContext;
+//import org.quartz.JobExecutionException;
+//import org.springframework.beans.factory.annotation.Autowired;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description : 定时采集冷量计任务
+// * @updateTime 2020-05-18
+// * @throws :
+// */
+///**
+// * :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
+// * :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
+// * :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
+// * 否则会在3秒时再启用新的线程执行
+// */
+//@DisallowConcurrentExecution
+//@Slf4j
+//public class JobCloud implements Job {
+//
+// @Autowired
+// private SocketMessage socketMessage;
+//
+// @SneakyThrows
+// @Override
+// public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
+// // 定时采集冷量计
+// log.info("定时采集冷量计");
+// NettyClient nettyClient = new NettyClient();
+// nettyClient.connect(socketMessage.getPort(),socketMessage.getIP());
+// }
+//}
diff --git a/user-service/src/main/java/com/mh/user/job/JobMeter.java b/user-service/src/main/java/com/mh/user/job/JobMeter.java
index b9e6cd8..9af6912 100644
--- a/user-service/src/main/java/com/mh/user/job/JobMeter.java
+++ b/user-service/src/main/java/com/mh/user/job/JobMeter.java
@@ -1,39 +1,39 @@
-package com.mh.user.job;
-
-import com.mh.user.netty.NettyMeterClient;
-import com.mh.user.constants.SocketMessage;
-import lombok.SneakyThrows;
-import lombok.extern.slf4j.Slf4j;
-import org.quartz.DisallowConcurrentExecution;
-import org.quartz.Job;
-import org.quartz.JobExecutionContext;
-import org.springframework.beans.factory.annotation.Autowired;
-
-/**
- * @author ljf
- * @title :
- * @description : 定时采集电表数据任务
- * @updateTime 2020-05-18
- * @throws :
- */
-/**
- * :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
- * :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
- * :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
- * 否则会在3秒时再启用新的线程执行
- */
-@DisallowConcurrentExecution
-@Slf4j
-public class JobMeter implements Job {
-
- @Autowired
- private SocketMessage socketMessage;
-
- @SneakyThrows
- @Override
- public void execute(JobExecutionContext jobExecutionContext) {
- log.info("定时采集电表数据任务开始");
- NettyMeterClient nettyMeterClient = new NettyMeterClient();
- nettyMeterClient.connect(socketMessage.getPort(), socketMessage.getIP());
- }
-}
+//package com.mh.user.job;
+//
+//import com.mh.user.netty.NettyMeterClient;
+//import com.mh.user.constants.SocketMessage;
+//import lombok.SneakyThrows;
+//import lombok.extern.slf4j.Slf4j;
+//import org.quartz.DisallowConcurrentExecution;
+//import org.quartz.Job;
+//import org.quartz.JobExecutionContext;
+//import org.springframework.beans.factory.annotation.Autowired;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description : 定时采集电表数据任务
+// * @updateTime 2020-05-18
+// * @throws :
+// */
+///**
+// * :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
+// * :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
+// * :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
+// * 否则会在3秒时再启用新的线程执行
+// */
+//@DisallowConcurrentExecution
+//@Slf4j
+//public class JobMeter implements Job {
+//
+// @Autowired
+// private SocketMessage socketMessage;
+//
+// @SneakyThrows
+// @Override
+// public void execute(JobExecutionContext jobExecutionContext) {
+// log.info("定时采集电表数据任务开始");
+// NettyMeterClient nettyMeterClient = new NettyMeterClient();
+// nettyMeterClient.connect(socketMessage.getPort(), socketMessage.getIP());
+// }
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyChillerControlClient.java b/user-service/src/main/java/com/mh/user/netty/NettyChillerControlClient.java
index e266f9f..27cf23e 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyChillerControlClient.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyChillerControlClient.java
@@ -1,98 +1,98 @@
-package com.mh.user.netty;
-
-import com.mh.user.entity.OrderMessageEntity;
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.timeout.IdleStateHandler;
-import io.netty.handler.timeout.ReadTimeoutHandler;
-import lombok.Getter;
-import lombok.Setter;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author ljf
- * @title :
- * @description : 控制冷水机组和其他设备
- * @updateTime 2020-05-28
- * @throws :
- */
-@Setter
-@Getter
-@Slf4j
-public class NettyChillerControlClient {
-
-// private int port;
-// private String host;
-// private List orderMessageEntityList;
-
- // 构造函数传递值 继承Thread时需要
-// public NettyChillerControlClient(int port, String host) {
-// this.port = port;
-// this.host = host;
-// }
-
- public void connect(int port, String host, List orderMessageEntityList) throws InterruptedException {
- // 配置客户端NIO线程组
- EventLoopGroup group = new NioEventLoopGroup(1);
- try {
- Bootstrap bootstrap = new Bootstrap();
- bootstrap.group(group).channel(NioSocketChannel.class)
- .option(ChannelOption.TCP_NODELAY, true)
- .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
- .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
- .handler(new ChannelInitializer() {
- @Override
- protected void initChannel(SocketChannel socketChannel) {
- // 基于换行符号
-// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
-// // 解码转String,注意调整自己的编码格式GBK、UTF-8
-// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
-// // 解码转String,注意调整自己的编码格式GBK、UTF-8
-// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
-// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
- // 超过10秒钟没有数据读取自动断开连接
-// socketChannel.pipeline().addLast(new ReadTimeoutHandler(30));
- // 超过10秒没有返回触发心跳机制 update by ljf on 2021-01-30
- socketChannel.pipeline().addLast(new IdleStateHandler(10,10,6, TimeUnit.SECONDS));
- // 在管道中添加我们自己的接收数据实现方法
- socketChannel.pipeline().addLast(new NettyChillerControlHandler(orderMessageEntityList));
-// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
- }
- });
- // 发起异步连接操作
- ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
- if (channelFuture.isSuccess()) {
- log.info("connect server 成功---------");
- } else {
- log.info("连接失败!");
- log.info("准备重连!");
-// connect(port, host);
- }
-
- // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
- channelFuture.channel().closeFuture().sync();
- } catch (Exception e) {
- log.error(e.getMessage());
- } finally {
- group.shutdownGracefully();
-// try {
-// TimeUnit.SECONDS.sleep(5);
-// connect(port, host); // 断线重连
-// } catch (InterruptedException e) {
-// e.printStackTrace();
+//package com.mh.user.netty;
+//
+//import com.mh.user.entity.OrderMessageEntity;
+//import io.netty.bootstrap.Bootstrap;
+//import io.netty.channel.*;
+//import io.netty.channel.nio.NioEventLoopGroup;
+//import io.netty.channel.socket.SocketChannel;
+//import io.netty.channel.socket.nio.NioSocketChannel;
+//import io.netty.handler.timeout.IdleStateHandler;
+//import io.netty.handler.timeout.ReadTimeoutHandler;
+//import lombok.Getter;
+//import lombok.Setter;
+//import lombok.extern.slf4j.Slf4j;
+//
+//import java.util.List;
+//import java.util.concurrent.TimeUnit;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description : 控制冷水机组和其他设备
+// * @updateTime 2020-05-28
+// * @throws :
+// */
+//@Setter
+//@Getter
+//@Slf4j
+//public class NettyChillerControlClient {
+//
+//// private int port;
+//// private String host;
+//// private List orderMessageEntityList;
+//
+// // 构造函数传递值 继承Thread时需要
+//// public NettyChillerControlClient(int port, String host) {
+//// this.port = port;
+//// this.host = host;
+//// }
+//
+// public void connect(int port, String host, List orderMessageEntityList) throws InterruptedException {
+// // 配置客户端NIO线程组
+// EventLoopGroup group = new NioEventLoopGroup(1);
+// try {
+// Bootstrap bootstrap = new Bootstrap();
+// bootstrap.group(group).channel(NioSocketChannel.class)
+// .option(ChannelOption.TCP_NODELAY, true)
+// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
+// .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
+// .handler(new ChannelInitializer() {
+// @Override
+// protected void initChannel(SocketChannel socketChannel) {
+// // 基于换行符号
+//// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
+//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
+//// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
+//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
+//// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
+//// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
+// // 超过10秒钟没有数据读取自动断开连接
+//// socketChannel.pipeline().addLast(new ReadTimeoutHandler(30));
+// // 超过10秒没有返回触发心跳机制 update by ljf on 2021-01-30
+// socketChannel.pipeline().addLast(new IdleStateHandler(10,10,6, TimeUnit.SECONDS));
+// // 在管道中添加我们自己的接收数据实现方法
+// socketChannel.pipeline().addLast(new NettyChillerControlHandler(orderMessageEntityList));
+//// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
+// }
+// });
+// // 发起异步连接操作
+// ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
+// if (channelFuture.isSuccess()) {
+// log.info("connect server 成功---------");
+// } else {
+// log.info("连接失败!");
+// log.info("准备重连!");
+//// connect(port, host);
// }
- }
- }
-
-// @SneakyThrows
-// @Override
-// public void run() {
-// connect(port, host);
+//
+// // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
+// channelFuture.channel().closeFuture().sync();
+// } catch (Exception e) {
+// log.error(e.getMessage());
+// } finally {
+// group.shutdownGracefully();
+//// try {
+//// TimeUnit.SECONDS.sleep(5);
+//// connect(port, host); // 断线重连
+//// } catch (InterruptedException e) {
+//// e.printStackTrace();
+//// }
+// }
// }
-}
+//
+//// @SneakyThrows
+//// @Override
+//// public void run() {
+//// connect(port, host);
+//// }
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyChillerControlHandler.java b/user-service/src/main/java/com/mh/user/netty/NettyChillerControlHandler.java
index f7fdbd3..dc67920 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyChillerControlHandler.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyChillerControlHandler.java
@@ -1,311 +1,311 @@
-package com.mh.user.netty;
-
-import com.mh.user.entity.OrderMessageEntity;
-import com.mh.user.service.impl.DeviceDisplayServiceImpl;
-import com.mh.user.constants.Constant;
-import com.mh.user.utils.ExchangeStringUtil;
-import com.mh.user.utils.SpringBeanUtil;
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerAdapter;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.timeout.IdleState;
-import io.netty.handler.timeout.IdleStateEvent;
-import io.netty.util.ReferenceCountUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.context.ApplicationContext;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-
-/**
- * @author ljf
- * @title :
- * @description :客户端异步消息处理机制
- * @updateTime 2020-05-13
- * @throws :
- */
-@Slf4j
-public class NettyChillerControlHandler extends ChannelHandlerAdapter {
-
- private int num = 0;
- private int size = 0;
- private String receiveStr = "";
- private int sendNum = 0;
- private int idle_count = 1;
-
- List orderMessageEntityList;
-
- // 调用service
- ApplicationContext context = SpringBeanUtil.getApplicationContext();
- DeviceDisplayServiceImpl.GatewayManageService gatewayManageService = context.getBean(DeviceDisplayServiceImpl.GatewayManageService.class);
- //OrderMessageService orderMessageService = context.getBean(OrderMessageService.class);
-
- public NettyChillerControlHandler(List orderMessageEntityList) {
- this.orderMessageEntityList = orderMessageEntityList;
- }
-
- @Override
- public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
- log.info("当前channel从EventLoop取消注册");
-// Constant.SEND_STATUS = false;
-// super.channelUnregistered(ctx);
- ctx.close();
- }
-
- /**
- * 超时处理
- * 如果120秒没有接受客户端的心跳,就触发;
- * 如果超过3次,则直接关闭;
- */
- @Override
- public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
- if (obj instanceof IdleStateEvent) {
- IdleStateEvent event = (IdleStateEvent) obj;
- if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
- System.out.println("第" + idle_count + "已经10秒没有接收到服务器的信息了,发送第" + num + "条数据");
- if (num > size - 1) {
- num = 0;
- // 关闭连接
- receiveStr = null;
- Constant.SEND_STATUS = true;
- System.out.println("关闭这个不活跃的channel");
- ctx.close();
- } else if (idle_count > 3) {
- System.out.println("关闭这个不活跃的channel");
- num = 0;
- // 关闭连接
- receiveStr = null;
- Constant.SEND_STATUS = false;
- ctx.close();
- } else {
- // 发送采集DDC指令
- // 判断空值
- if (orderMessageEntityList.get(num).getRegisterAddr() == null ||
- orderMessageEntityList.get(num).getRegisterAddr().equalsIgnoreCase("")) {
- num = 0;
- // 关闭连接
- receiveStr = null;
- Constant.SEND_STATUS = true;
- ctx.close();
- } else {
- String sendStr = orderMessageEntityList.get(num).getOrderStr();
-// // 获取采集参数个数
-// size = orderMessageEntityList.size();
- // 2.发送数据
- ByteBuf buffer = getByteBuf(ctx, sendStr);
- ctx.channel().writeAndFlush(buffer);
- idle_count++;
- }
- }
- }
- } else {
- super.userEventTriggered(ctx, obj);
- }
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-// super.exceptionCaught(ctx, cause);
- log.info("通信异常!!");
- cause.printStackTrace();
-// receiveStr = null;
-// Channel incoming = ctx.channel();
-// if (incoming.isActive()) {
-// // 重新发送
-// if (sendNum > 2) {
-// // 通信异常,发送失败
-// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
-// cause.printStackTrace();
-// Constant.SEND_STATUS = false;
-// ctx.close();
-// } else {
-// // 发送采集DDC指令
-// String sendStr = orderMessageEntityList.get(num).getOrderStr();
-// // 获取采集参数个数
-// size = orderMessageEntityList.size();
-// // 2.发送数据
-// ByteBuf buffer = getByteBuf(ctx,sendStr);
-// ctx.channel().writeAndFlush(buffer);
-// sendNum += 1;
+//package com.mh.user.netty;
+//
+//import com.mh.user.entity.OrderMessageEntity;
+//import com.mh.user.service.impl.DeviceDisplayServiceImpl;
+//import com.mh.user.constants.Constant;
+//import com.mh.user.utils.ExchangeStringUtil;
+//import com.mh.user.utils.SpringBeanUtil;
+//import io.netty.buffer.ByteBuf;
+//import io.netty.channel.ChannelHandlerAdapter;
+//import io.netty.channel.ChannelHandlerContext;
+//import io.netty.handler.timeout.IdleState;
+//import io.netty.handler.timeout.IdleStateEvent;
+//import io.netty.util.ReferenceCountUtil;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.context.ApplicationContext;
+//
+//import java.text.SimpleDateFormat;
+//import java.util.Date;
+//import java.util.List;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description :客户端异步消息处理机制
+// * @updateTime 2020-05-13
+// * @throws :
+// */
+//@Slf4j
+//public class NettyChillerControlHandler extends ChannelHandlerAdapter {
+//
+// private int num = 0;
+// private int size = 0;
+// private String receiveStr = "";
+// private int sendNum = 0;
+// private int idle_count = 1;
+//
+// List orderMessageEntityList;
+//
+// // 调用service
+// ApplicationContext context = SpringBeanUtil.getApplicationContext();
+// DeviceDisplayServiceImpl.GatewayManageService gatewayManageService = context.getBean(DeviceDisplayServiceImpl.GatewayManageService.class);
+// //OrderMessageService orderMessageService = context.getBean(OrderMessageService.class);
+//
+// public NettyChillerControlHandler(List orderMessageEntityList) {
+// this.orderMessageEntityList = orderMessageEntityList;
+// }
+//
+// @Override
+// public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
+// log.info("当前channel从EventLoop取消注册");
+//// Constant.SEND_STATUS = false;
+//// super.channelUnregistered(ctx);
+// ctx.close();
+// }
+//
+// /**
+// * 超时处理
+// * 如果120秒没有接受客户端的心跳,就触发;
+// * 如果超过3次,则直接关闭;
+// */
+// @Override
+// public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
+// if (obj instanceof IdleStateEvent) {
+// IdleStateEvent event = (IdleStateEvent) obj;
+// if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
+// System.out.println("第" + idle_count + "已经10秒没有接收到服务器的信息了,发送第" + num + "条数据");
+// if (num > size - 1) {
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// Constant.SEND_STATUS = true;
+// System.out.println("关闭这个不活跃的channel");
+// ctx.close();
+// } else if (idle_count > 3) {
+// System.out.println("关闭这个不活跃的channel");
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// Constant.SEND_STATUS = false;
+// ctx.close();
+// } else {
+// // 发送采集DDC指令
+// // 判断空值
+// if (orderMessageEntityList.get(num).getRegisterAddr() == null ||
+// orderMessageEntityList.get(num).getRegisterAddr().equalsIgnoreCase("")) {
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// Constant.SEND_STATUS = true;
+// ctx.close();
+// } else {
+// String sendStr = orderMessageEntityList.get(num).getOrderStr();
+//// // 获取采集参数个数
+//// size = orderMessageEntityList.size();
+// // 2.发送数据
+// ByteBuf buffer = getByteBuf(ctx, sendStr);
+// ctx.channel().writeAndFlush(buffer);
+// idle_count++;
+// }
+// }
// }
+// } else {
+// super.userEventTriggered(ctx, obj);
// }
-// // 判断发送的下标,如果不等于指令数组大小
-// num = num + 1;
-// if (num > size-1) {
-// num = 0;
-// // 关闭连接
-// receiveStr = null;
-// Constant.SEND_STATUS = true;
-// ctx.close();
+// }
+//
+// @Override
+// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+//// super.exceptionCaught(ctx, cause);
+// log.info("通信异常!!");
+// cause.printStackTrace();
+//// receiveStr = null;
+//// Channel incoming = ctx.channel();
+//// if (incoming.isActive()) {
+//// // 重新发送
+//// if (sendNum > 2) {
+//// // 通信异常,发送失败
+//// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
+//// cause.printStackTrace();
+//// Constant.SEND_STATUS = false;
+//// ctx.close();
+//// } else {
+//// // 发送采集DDC指令
+//// String sendStr = orderMessageEntityList.get(num).getOrderStr();
+//// // 获取采集参数个数
+//// size = orderMessageEntityList.size();
+//// // 2.发送数据
+//// ByteBuf buffer = getByteBuf(ctx,sendStr);
+//// ctx.channel().writeAndFlush(buffer);
+//// sendNum += 1;
+//// }
+//// }
+//// // 判断发送的下标,如果不等于指令数组大小
+//// num = num + 1;
+//// if (num > size-1) {
+//// num = 0;
+//// // 关闭连接
+//// receiveStr = null;
+//// Constant.SEND_STATUS = true;
+//// ctx.close();
+//// }
+// }
+//
+//
+// @Override
+// public void channelActive(ChannelHandlerContext ctx) throws Exception {
+// super.channelActive(ctx);
+// SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
+// Date date=new Date();
+// log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
+// // 截取IP地址
+// String IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress()+"","/", ":");
+// // 截取端口号
+// String port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress()+"",":", "");
+// log.info("IP: " + IP + ",端口号: " + port);
+// // 更新对应的网关在线情况
+// gatewayManageService.updateGatewayManage(IP, port);
+//
+// // 发送控制DDC指令
+// String sendStr = orderMessageEntityList.get(num).getOrderStr();
+// // 获取采集参数个数
+// size = orderMessageEntityList.size();
+//
+// // 2.发送数据
+// ByteBuf buffer = getByteBuf(ctx,sendStr);
+// ctx.channel().writeAndFlush(buffer);
+// }
+//
+// private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
+// // 申请一个数据结构存储信息
+// ByteBuf buffer = ctx.alloc().buffer();
+// // 将信息放入数据结构中
+// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
+// return buffer;
+// }
+//
+// @Override
+// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+//// Thread.sleep(100);
+// ctx.close();
+// log.info(ctx.channel().localAddress() + "退出链接!!");
+// }
+//
+// @Override
+// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+//// super.channelRead(ctx, msg);
+// // ByteBuf buf = (ByteBuf)msg;
+//// byte[] req = new byte[buf.readableBytes()];
+//// buf.readBytes(req);
+//// String body = new String(req, "UTF-8");
+// try {
+// ByteBuf buf = (ByteBuf)msg;
+// byte [] bytes = new byte[buf.readableBytes()];
+// buf.readBytes(bytes);//复制内容到字节数组bytes
+// buf.clear();
+// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
+//// if (bytes.length <= 24) {
+// if (bytes.length != 0) {
+//// receiveStr = receiveStr.replace("null", "");
+//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+//// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+// receiveStr = receiveStr.replace("null", "");
+// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+// }
+// } catch (Exception e) {
+// e.printStackTrace();
+// } finally {
+// ReferenceCountUtil.release(msg);
// }
- }
-
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- super.channelActive(ctx);
- SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
- Date date=new Date();
- log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
- // 截取IP地址
- String IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress()+"","/", ":");
- // 截取端口号
- String port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress()+"",":", "");
- log.info("IP: " + IP + ",端口号: " + port);
- // 更新对应的网关在线情况
- gatewayManageService.updateGatewayManage(IP, port);
-
- // 发送控制DDC指令
- String sendStr = orderMessageEntityList.get(num).getOrderStr();
- // 获取采集参数个数
- size = orderMessageEntityList.size();
-
- // 2.发送数据
- ByteBuf buffer = getByteBuf(ctx,sendStr);
- ctx.channel().writeAndFlush(buffer);
- }
-
- private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
- // 申请一个数据结构存储信息
- ByteBuf buffer = ctx.alloc().buffer();
- // 将信息放入数据结构中
- buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
- return buffer;
- }
-
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-// Thread.sleep(100);
- ctx.close();
- log.info(ctx.channel().localAddress() + "退出链接!!");
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
-// super.channelRead(ctx, msg);
- // ByteBuf buf = (ByteBuf)msg;
-// byte[] req = new byte[buf.readableBytes()];
-// buf.readBytes(req);
-// String body = new String(req, "UTF-8");
- try {
- ByteBuf buf = (ByteBuf)msg;
- byte [] bytes = new byte[buf.readableBytes()];
- buf.readBytes(bytes);//复制内容到字节数组bytes
- buf.clear();
- log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
-// if (bytes.length <= 24) {
- if (bytes.length != 0) {
-// receiveStr = receiveStr.replace("null", "");
-// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
-// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
- receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
- receiveStr = receiveStr.replace("null", "");
- log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- ReferenceCountUtil.release(msg);
- }
- }
-
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- log.info("数据读取接收完成: " + receiveStr);
- if (receiveStr.length() == 24) {
- if (receiveStr.equalsIgnoreCase(orderMessageEntityList.get(num).getOrderStr())) {
- // 解析采集回来的数据
- log.info("采集完整的报文: " + receiveStr + ",指令下标: " + size);
- // 解析采集的报文
- // 更新发送后的指令
- OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
- orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
- orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
- orderMessageEntity.setGrade(1);
- orderMessageEntity.setSendNum(1);
- orderMessageEntity.setStatus(1);
- orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
- //orderMessageService.updateOrderMessage(orderMessageEntity);
-
+// }
+//
+// @Override
+// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+// log.info("数据读取接收完成: " + receiveStr);
+// if (receiveStr.length() == 24) {
+// if (receiveStr.equalsIgnoreCase(orderMessageEntityList.get(num).getOrderStr())) {
+// // 解析采集回来的数据
+// log.info("采集完整的报文: " + receiveStr + ",指令下标: " + size);
+// // 解析采集的报文
+// // 更新发送后的指令
+// OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
+// orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
+// orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
+// orderMessageEntity.setGrade(1);
+// orderMessageEntity.setSendNum(1);
+// orderMessageEntity.setStatus(1);
+// orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
+// //orderMessageService.updateOrderMessage(orderMessageEntity);
+//
+//// // 关闭连接
+//// receiveStr = null;
+//// Constant.SEND_STATUS = true;
+//// ctx.close();
+//
+// // 清空receiveStr
+// receiveStr = "";
+// // 判断发送的下标,如果不等于指令数组大小
+// num = num + 1;
+// if (num > size - 1) {
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// Constant.SEND_STATUS = true;
+// ctx.close();
+// } else {
+// Thread.sleep(4000);
+// // 继续发送下一个采集DDC设备指令
+// String sendStr = orderMessageEntityList.get(num).getOrderStr();
+// ByteBuf buffer = getByteBuf(ctx, sendStr);
+// // 2.发送数据
+// ctx.channel().writeAndFlush(buffer);
+// log.info("客户端再次往服务端发送数据" + num + ",报文: " + sendStr);
+// }
+// }
+// } else if ((receiveStr.length() > 24) && (num == 0)) {
+// // 发送采集DDC指令
+// String sendStr = orderMessageEntityList.get(num).getOrderStr();
+// // 获取采集参数个数
+// size = orderMessageEntityList.size();
+// // 2.发送数据
+// ByteBuf buffer = getByteBuf(ctx,sendStr);
+// ctx.channel().writeAndFlush(buffer);
+// // 清空receiveStr
+// receiveStr = "";
+// sendNum += 1;
+// } else if (sendNum > 2){
+// // 更新发送后的指令
+// OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
+// orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
+// orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
+// orderMessageEntity.setGrade(1);
+// orderMessageEntity.setSendNum(sendNum);
+// orderMessageEntity.setStatus(0);
+// orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
+// //orderMessageService.updateOrderMessage(orderMessageEntity);
+// Constant.SEND_STATUS = false;
+// ctx.close();
+// } else if ((receiveStr.length() > 24)) {
+// // 接收采集DDC的数据
+// // 解析采集的报文
+//// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
+//// analysisReceiveOrder485.analysisChillersDDC(receiveStr);
+//
+// // 清空receiveStr
+// receiveStr = "";
+// // 更新发送后的指令
+// OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
+// orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
+// orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
+// orderMessageEntity.setGrade(1);
+// orderMessageEntity.setSendNum(1);
+// orderMessageEntity.setStatus(1);
+// orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
+// //orderMessageService.updateOrderMessage(orderMessageEntity);
+//
+// // 判断发送的下标,如果不等于指令数组大小
+// num = num + 1;
+//// Thread.sleep(500);
+// if (num > size-1) {
+// num = 0;
// // 关闭连接
// receiveStr = null;
// Constant.SEND_STATUS = true;
// ctx.close();
-
- // 清空receiveStr
- receiveStr = "";
- // 判断发送的下标,如果不等于指令数组大小
- num = num + 1;
- if (num > size - 1) {
- num = 0;
- // 关闭连接
- receiveStr = null;
- Constant.SEND_STATUS = true;
- ctx.close();
- } else {
- Thread.sleep(4000);
- // 继续发送下一个采集DDC设备指令
- String sendStr = orderMessageEntityList.get(num).getOrderStr();
- ByteBuf buffer = getByteBuf(ctx, sendStr);
- // 2.发送数据
- ctx.channel().writeAndFlush(buffer);
- log.info("客户端再次往服务端发送数据" + num + ",报文: " + sendStr);
- }
- }
- } else if ((receiveStr.length() > 24) && (num == 0)) {
- // 发送采集DDC指令
- String sendStr = orderMessageEntityList.get(num).getOrderStr();
- // 获取采集参数个数
- size = orderMessageEntityList.size();
- // 2.发送数据
- ByteBuf buffer = getByteBuf(ctx,sendStr);
- ctx.channel().writeAndFlush(buffer);
- // 清空receiveStr
- receiveStr = "";
- sendNum += 1;
- } else if (sendNum > 2){
- // 更新发送后的指令
- OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
- orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
- orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
- orderMessageEntity.setGrade(1);
- orderMessageEntity.setSendNum(sendNum);
- orderMessageEntity.setStatus(0);
- orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
- //orderMessageService.updateOrderMessage(orderMessageEntity);
- Constant.SEND_STATUS = false;
- ctx.close();
- } else if ((receiveStr.length() > 24)) {
- // 接收采集DDC的数据
- // 解析采集的报文
-// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
-// analysisReceiveOrder485.analysisChillersDDC(receiveStr);
-
- // 清空receiveStr
- receiveStr = "";
- // 更新发送后的指令
- OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
- orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
- orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
- orderMessageEntity.setGrade(1);
- orderMessageEntity.setSendNum(1);
- orderMessageEntity.setStatus(1);
- orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
- //orderMessageService.updateOrderMessage(orderMessageEntity);
-
- // 判断发送的下标,如果不等于指令数组大小
- num = num + 1;
-// Thread.sleep(500);
- if (num > size-1) {
- num = 0;
- // 关闭连接
- receiveStr = null;
- Constant.SEND_STATUS = true;
- ctx.close();
- }
- }
- ctx.flush();
- }
-
-}
+// }
+// }
+// ctx.flush();
+// }
+//
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyClient.java b/user-service/src/main/java/com/mh/user/netty/NettyClient.java
index 828c646..5c1a261 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyClient.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyClient.java
@@ -1,90 +1,90 @@
-package com.mh.user.netty;
-
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.timeout.ReadTimeoutHandler;
-import lombok.Getter;
-import lombok.Setter;
-import lombok.extern.slf4j.Slf4j;
-
-/**
- * @author ljf
- * @title :
- * @description :Netty客户端,采集冷量计
- * @updateTime 2020-05-13
- * @throws :
- */
-@Slf4j
-@Setter
-@Getter
-public class NettyClient {
-
- private int port;
- private String host;
-
- // 构造函数传递值 继承Thread时需要
-// public NettyClient(int port, String host) {
-// this.port = port;
-// this.host = host;
-// }
-
- public void connect(int port, String host) throws InterruptedException {
- // 配置客户端NIO线程组
- EventLoopGroup group = new NioEventLoopGroup(1);
- try {
- Bootstrap bootstrap = new Bootstrap();
- bootstrap.group(group).channel(NioSocketChannel.class)
- .option(ChannelOption.TCP_NODELAY, true)
- .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
- .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
- .handler(new ChannelInitializer() {
- @Override
- protected void initChannel(SocketChannel socketChannel) {
- // 基于换行符号
-// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
-// // 解码转String,注意调整自己的编码格式GBK、UTF-8
-// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
-// // 解码转String,注意调整自己的编码格式GBK、UTF-8
-// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
-// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
- // 超过10秒钟没有数据读取自动断开连接
- socketChannel.pipeline().addLast(new ReadTimeoutHandler(10));
- // 在管道中添加我们自己的接收数据实现方法
- socketChannel.pipeline().addLast(new NettyClientHandler());
-// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
- }
- });
- // 发起异步连接操作
- ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
- if (channelFuture.isSuccess()) {
- log.info("connect server 成功---------");
- } else {
- log.info("连接失败!");
- log.info("准备重连!");
-// connect(port, host);
- }
-
- // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
- channelFuture.channel().closeFuture().sync();
- } catch (Exception e) {
- log.error(e.getMessage());
- } finally {
- group.shutdownGracefully();
-// try {
-// TimeUnit.SECONDS.sleep(5);
-// connect(port, host); // 断线重连
-// } catch (InterruptedException e) {
-// e.printStackTrace();
+//package com.mh.user.netty;
+//
+//import io.netty.bootstrap.Bootstrap;
+//import io.netty.channel.*;
+//import io.netty.channel.nio.NioEventLoopGroup;
+//import io.netty.channel.socket.SocketChannel;
+//import io.netty.channel.socket.nio.NioSocketChannel;
+//import io.netty.handler.timeout.ReadTimeoutHandler;
+//import lombok.Getter;
+//import lombok.Setter;
+//import lombok.extern.slf4j.Slf4j;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description :Netty客户端,采集冷量计
+// * @updateTime 2020-05-13
+// * @throws :
+// */
+//@Slf4j
+//@Setter
+//@Getter
+//public class NettyClient {
+//
+// private int port;
+// private String host;
+//
+// // 构造函数传递值 继承Thread时需要
+//// public NettyClient(int port, String host) {
+//// this.port = port;
+//// this.host = host;
+//// }
+//
+// public void connect(int port, String host) throws InterruptedException {
+// // 配置客户端NIO线程组
+// EventLoopGroup group = new NioEventLoopGroup(1);
+// try {
+// Bootstrap bootstrap = new Bootstrap();
+// bootstrap.group(group).channel(NioSocketChannel.class)
+// .option(ChannelOption.TCP_NODELAY, true)
+// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
+// .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
+// .handler(new ChannelInitializer() {
+// @Override
+// protected void initChannel(SocketChannel socketChannel) {
+// // 基于换行符号
+//// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
+//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
+//// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
+//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
+//// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
+//// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
+// // 超过10秒钟没有数据读取自动断开连接
+// socketChannel.pipeline().addLast(new ReadTimeoutHandler(10));
+// // 在管道中添加我们自己的接收数据实现方法
+// socketChannel.pipeline().addLast(new NettyClientHandler());
+//// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
+// }
+// });
+// // 发起异步连接操作
+// ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
+// if (channelFuture.isSuccess()) {
+// log.info("connect server 成功---------");
+// } else {
+// log.info("连接失败!");
+// log.info("准备重连!");
+//// connect(port, host);
// }
- }
- }
-
-// @SneakyThrows
-// @Override
-// public void run() {
-// connect(port, host);
+//
+// // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
+// channelFuture.channel().closeFuture().sync();
+// } catch (Exception e) {
+// log.error(e.getMessage());
+// } finally {
+// group.shutdownGracefully();
+//// try {
+//// TimeUnit.SECONDS.sleep(5);
+//// connect(port, host); // 断线重连
+//// } catch (InterruptedException e) {
+//// e.printStackTrace();
+//// }
+// }
// }
-}
+//
+//// @SneakyThrows
+//// @Override
+//// public void run() {
+//// connect(port, host);
+//// }
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyClientHandler.java b/user-service/src/main/java/com/mh/user/netty/NettyClientHandler.java
index 8862451..3b5cf9b 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyClientHandler.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyClientHandler.java
@@ -1,295 +1,295 @@
-package com.mh.user.netty;
-
-import com.mh.user.constants.Constant;
-import com.mh.user.entity.DeviceManageEntity;
-import com.mh.user.service.DeviceManageService;
-import com.mh.user.utils.*;
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandlerAdapter;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.util.ReferenceCountUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.context.ApplicationContext;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-
-/**
- * @author ljf
- * @title :
- * @description :客户端异步消息处理机制
- * @updateTime 2020-05-13
- * @throws :
- */
-@Slf4j
-public class NettyClientHandler extends ChannelHandlerAdapter {
-
- private int num = 0;
- private int size = 0;
- private String receiveStr = null;
- private String IP = null;
- private String port = null;
- List deviceManageEntityList;
-
- // 调用service
- ApplicationContext context = SpringBeanUtil.getApplicationContext();
- DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
-
-
- @Override
- public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
- log.info("当前channel从EventLoop取消注册");
- super.channelUnregistered(ctx);
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-// super.exceptionCaught(ctx, cause);
- log.info("通信异常!!");
- receiveStr = null;
- Channel incoming = ctx.channel();
- if (incoming.isActive()){
- log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
- cause.printStackTrace();
- ctx.close();
-// receiveStr = null;
-// try {
-// TimeUnit.SECONDS.sleep(5);
-// SocketAddress remoteAddress = ctx.channel().remoteAddress();
-// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
-// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
-// NettyClient nettyClient = new NettyClient();
-// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
-// } catch (InterruptedException e) {
-// e.printStackTrace();
-// }
- }
- }
-
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) {
- // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
- if (Constant.WEB_FLAG) {
- num = 0;
- // 关闭连接
- receiveStr = null;
- ctx.close();
- } else {
- ctx.channel().read();
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
- Date date = new Date();
- log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
- // 截取IP地址
- IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
- // 截取端口号
- port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
- log.info("IP: " + IP + ",端口号: " + port);
- // 生成对应采集冷量计的命令
- // 生成对应的采集指令
- deviceManageEntityList = deviceManageService.queryDevicesByType("3");
- size = deviceManageEntityList.size();
-
- // 封装工具类进行采集,update by ljf on 2021-01-26
- SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(0),0,IP,port,ctx);
-// // 1.创建将要写出的数据
-// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
-// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
-// deviceManageEntityList.get(0).getDataCom(),
-// collectionNum, "34");
-//// String sendStr = "5803004900021914";
-// ByteBuf buffer = getByteBuf(ctx, sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
- }
-
-// String sendStr = "5803004900021914"; // 冷量计
+//package com.mh.user.netty;
+//
+//import com.mh.user.constants.Constant;
+//import com.mh.user.entity.DeviceManageEntity;
+//import com.mh.user.service.DeviceManageService;
+//import com.mh.user.utils.*;
+//import io.netty.buffer.ByteBuf;
+//import io.netty.channel.Channel;
+//import io.netty.channel.ChannelHandlerAdapter;
+//import io.netty.channel.ChannelHandlerContext;
+//import io.netty.util.ReferenceCountUtil;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.context.ApplicationContext;
+//
+//import java.text.SimpleDateFormat;
+//import java.util.Date;
+//import java.util.List;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description :客户端异步消息处理机制
+// * @updateTime 2020-05-13
+// * @throws :
+// */
+//@Slf4j
+//public class NettyClientHandler extends ChannelHandlerAdapter {
+//
+// private int num = 0;
+// private int size = 0;
+// private String receiveStr = null;
+// private String IP = null;
+// private String port = null;
+// List deviceManageEntityList;
+//
+// // 调用service
+// ApplicationContext context = SpringBeanUtil.getApplicationContext();
+// DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
+//
+//
+// @Override
+// public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
+// log.info("当前channel从EventLoop取消注册");
+// super.channelUnregistered(ctx);
+// }
+//
+// @Override
+// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+//// super.exceptionCaught(ctx, cause);
+// log.info("通信异常!!");
+// receiveStr = null;
+// Channel incoming = ctx.channel();
+// if (incoming.isActive()){
+// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
+// cause.printStackTrace();
+// ctx.close();
+//// receiveStr = null;
+//// try {
+//// TimeUnit.SECONDS.sleep(5);
+//// SocketAddress remoteAddress = ctx.channel().remoteAddress();
+//// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
+//// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
+//// NettyClient nettyClient = new NettyClient();
+//// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
+//// } catch (InterruptedException e) {
+//// e.printStackTrace();
+//// }
+// }
+// }
+//
+//
+// @Override
+// public void channelActive(ChannelHandlerContext ctx) {
+// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
+// if (Constant.WEB_FLAG) {
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// ctx.close();
+// } else {
+// ctx.channel().read();
+// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
+// Date date = new Date();
+// log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
+// // 截取IP地址
+// IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
+// // 截取端口号
+// port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
+// log.info("IP: " + IP + ",端口号: " + port);
+// // 生成对应采集冷量计的命令
+// // 生成对应的采集指令
+// deviceManageEntityList = deviceManageService.queryDevicesByType("3");
+// size = deviceManageEntityList.size();
+//
+// // 封装工具类进行采集,update by ljf on 2021-01-26
+// SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(0),0,IP,port,ctx);
+//// // 1.创建将要写出的数据
+//// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
+//// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
+//// deviceManageEntityList.get(0).getDataCom(),
+//// collectionNum, "34");
+////// String sendStr = "5803004900021914";
+//// ByteBuf buffer = getByteBuf(ctx, sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+// }
+//
+//// String sendStr = "5803004900021914"; // 冷量计
+//// // 申请一个数据结构存储信息
+//// ByteBuf buffer = ctx.alloc().buffer();
+//// // 将信息放入数据结构中
+//// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
+//// ctx.writeAndFlush(buffer, ctx.newProgressivePromise());
+// }
+//
+// private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
+// // byte类型的数据
+//// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
+//// String sendStr = "5803004900021914"; // 冷量计
// // 申请一个数据结构存储信息
// ByteBuf buffer = ctx.alloc().buffer();
// // 将信息放入数据结构中
// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
-// ctx.writeAndFlush(buffer, ctx.newProgressivePromise());
- }
-
- private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
- // byte类型的数据
-// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
-// String sendStr = "5803004900021914"; // 冷量计
- // 申请一个数据结构存储信息
- ByteBuf buffer = ctx.alloc().buffer();
- // 将信息放入数据结构中
- buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
- return buffer;
- }
-
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- Thread.sleep(100);
- ctx.close();
- log.info(ctx.channel().localAddress() + "退出链接!!");
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- try {
- ByteBuf buf = (ByteBuf)msg;
- byte [] bytes = new byte[buf.readableBytes()];
- buf.readBytes(bytes);//复制内容到字节数组bytes
- buf.clear();
- log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
- if (bytes.length <= 36) {
-// receiveStr = receiveStr.replace("null", "");
-// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
-// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
- receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
- receiveStr = receiveStr.replace("null", "");
- log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- ReferenceCountUtil.release(msg);
- }
- }
-
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- log.info("采集冷量计-数据读取接收完成: " + receiveStr);
-// A9 FE C2 C7 1F 90 01 58 03 04 4A 30 00 53 65 1C C4 06
- if (receiveStr.length() == 36) {
- // 接收到的报文
- log.info("接收完整报文: " + receiveStr);
- // 解析报文
-// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
-// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
- receiveStr = "";
- // 1.创建将要写出的数据
-// String sendStr = "5803004900021914";
- num = num + 1;
- Thread.sleep(500);
- if (num > size-1) {
- num = 0;
- // 关闭连接
- receiveStr = null;
- ctx.close();
-// 保持长连接
-// // 封装工具类进行采集,update by ljf on 2021-01-26
-// SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
- } else {
- // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
- if (Constant.WEB_FLAG) {
- log.info("有指令下发退出定时采集DDC参数");
- num = 0;
- // 关闭连接
- receiveStr = null;
- ctx.close();
- } else {
- // 封装工具类进行采集,update by ljf on 2021-01-26
- SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
-// // 1.创建将要写出的数据
-// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
-// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
-// deviceManageEntityList.get(num).getDataCom(),
-// collectionNum, "34");
-//// String sendStr = "5803004900021914";
-// ByteBuf buffer = getByteBuf(ctx, sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
-// log.info("客户端再次往服务端发送数据" + sendStr);
- }
- }
-
- } else {
- log.info(receiveStr);
- receiveStr = null;
- ctx.flush();
- ctx.close();
- }
-
-// if (receiveStr.contains("c0a801fc")) { // 冷量计
+// return buffer;
+// }
//
-// // 生成对应的采集指令
-// deviceManageEntityList = deviceManageService.queryDevicesByType("3");
-// size = deviceManageEntityList.size();
+// @Override
+// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+// Thread.sleep(100);
+// ctx.close();
+// log.info(ctx.channel().localAddress() + "退出链接!!");
+// }
//
-// log.info("初始连接报文: " + receiveStr);
-// IP = receiveStr;
-// receiveStr = "";
-// // 1.创建将要写出的数据
-// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
-// String sendStr = GetReadOrder485.createCloudOrder(collectionNum,"34");
-//// String sendStr = "5803004900021914";
-// ByteBuf buffer = getByteBuf(ctx,sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
-// } else if (receiveStr.contains("c0a801f0")) { // 电表
-//
-// // 生成对应的采集指令
-// deviceManageEntityList = deviceManageService.queryDevicesByType("1");
-// size = deviceManageEntityList.size();
+// @Override
+// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+// try {
+// ByteBuf buf = (ByteBuf)msg;
+// byte [] bytes = new byte[buf.readableBytes()];
+// buf.readBytes(bytes);//复制内容到字节数组bytes
+// buf.clear();
+// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
+// if (bytes.length <= 36) {
+//// receiveStr = receiveStr.replace("null", "");
+//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+//// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+// receiveStr = receiveStr.replace("null", "");
+// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+// }
+// } catch (Exception e) {
+// e.printStackTrace();
+// } finally {
+// ReferenceCountUtil.release(msg);
+// }
+// }
//
-// log.info("初始连接报文: " + receiveStr);
-// IP = receiveStr;
-// receiveStr = "";
-// // 1.创建将要写出的数据
-//// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表
-//// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表
-// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
-// String sendStr = GetReadOrder485.createMeterOrder(collectionNum,"1");
-// ByteBuf buffer = getByteBuf(ctx,sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
-// } else if ((receiveStr.length() == 18) && (IP.contains("c0a801fc"))) {
-// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
+// @Override
+// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+// log.info("采集冷量计-数据读取接收完成: " + receiveStr);
+//// A9 FE C2 C7 1F 90 01 58 03 04 4A 30 00 53 65 1C C4 06
+// if (receiveStr.length() == 36) {
+// // 接收到的报文
+// log.info("接收完整报文: " + receiveStr);
+// // 解析报文
+//// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
+//// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
// receiveStr = "";
// // 1.创建将要写出的数据
//// String sendStr = "5803004900021914";
// num = num + 1;
-// Thread.sleep(1000);
-// if (num >= size-1) {
+// Thread.sleep(500);
+// if (num > size-1) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
+//// 保持长连接
+//// // 封装工具类进行采集,update by ljf on 2021-01-26
+//// SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
// } else {
-// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
-// String sendStr = GetReadOrder485.createCloudOrder(collectionNum, "34");
-// ByteBuf buffer = getByteBuf(ctx, sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
-// log.info("客户端再次往服务端发送数据" + num);
-// }
-//
-// } else if ((receiveStr.length() == 44) && (IP.contains("c0a801f0"))) {
-// analysisReceiveOrder485.analysisMeterOrder485(receiveStr); // 解析电表
-// receiveStr = "";
-// num = num + 1;
-// Thread.sleep(1000);
-// if (num >= size-1) {
+// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
+// if (Constant.WEB_FLAG) {
+// log.info("有指令下发退出定时采集DDC参数");
// num = 0;
-// receiveStr = null;
// // 关闭连接
+// receiveStr = null;
// ctx.close();
-// } else {
-// // 1.创建将要写出的数据
-// // fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
-//// String sendStr = "FEFEFE6880025007000068010243C3B216";
-// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
-// String sendStr = GetReadOrder485.createMeterOrder(collectionNum, "1");
-// ByteBuf buffer = getByteBuf(ctx, sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
-// log.info("客户端再次往服务端发送数据" + num);
+// } else {
+// // 封装工具类进行采集,update by ljf on 2021-01-26
+// SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
+//// // 1.创建将要写出的数据
+//// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
+//// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
+//// deviceManageEntityList.get(num).getDataCom(),
+//// collectionNum, "34");
+////// String sendStr = "5803004900021914";
+//// ByteBuf buffer = getByteBuf(ctx, sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+//// log.info("客户端再次往服务端发送数据" + sendStr);
+// }
// }
-// } else if ((receiveStr.length() > 44)) {
+//
+// } else {
// log.info(receiveStr);
// receiveStr = null;
// ctx.flush();
// ctx.close();
// }
- ctx.flush();
- }
-
-}
+//
+//// if (receiveStr.contains("c0a801fc")) { // 冷量计
+////
+//// // 生成对应的采集指令
+//// deviceManageEntityList = deviceManageService.queryDevicesByType("3");
+//// size = deviceManageEntityList.size();
+////
+//// log.info("初始连接报文: " + receiveStr);
+//// IP = receiveStr;
+//// receiveStr = "";
+//// // 1.创建将要写出的数据
+//// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
+//// String sendStr = GetReadOrder485.createCloudOrder(collectionNum,"34");
+////// String sendStr = "5803004900021914";
+//// ByteBuf buffer = getByteBuf(ctx,sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+//// } else if (receiveStr.contains("c0a801f0")) { // 电表
+////
+//// // 生成对应的采集指令
+//// deviceManageEntityList = deviceManageService.queryDevicesByType("1");
+//// size = deviceManageEntityList.size();
+////
+//// log.info("初始连接报文: " + receiveStr);
+//// IP = receiveStr;
+//// receiveStr = "";
+//// // 1.创建将要写出的数据
+////// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表
+////// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表
+//// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
+//// String sendStr = GetReadOrder485.createMeterOrder(collectionNum,"1");
+//// ByteBuf buffer = getByteBuf(ctx,sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+//// } else if ((receiveStr.length() == 18) && (IP.contains("c0a801fc"))) {
+//// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
+//// receiveStr = "";
+//// // 1.创建将要写出的数据
+////// String sendStr = "5803004900021914";
+//// num = num + 1;
+//// Thread.sleep(1000);
+//// if (num >= size-1) {
+//// num = 0;
+//// // 关闭连接
+//// receiveStr = null;
+//// ctx.close();
+//// } else {
+//// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
+//// String sendStr = GetReadOrder485.createCloudOrder(collectionNum, "34");
+//// ByteBuf buffer = getByteBuf(ctx, sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+//// log.info("客户端再次往服务端发送数据" + num);
+//// }
+////
+//// } else if ((receiveStr.length() == 44) && (IP.contains("c0a801f0"))) {
+//// analysisReceiveOrder485.analysisMeterOrder485(receiveStr); // 解析电表
+//// receiveStr = "";
+//// num = num + 1;
+//// Thread.sleep(1000);
+//// if (num >= size-1) {
+//// num = 0;
+//// receiveStr = null;
+//// // 关闭连接
+//// ctx.close();
+//// } else {
+//// // 1.创建将要写出的数据
+//// // fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
+////// String sendStr = "FEFEFE6880025007000068010243C3B216";
+//// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
+//// String sendStr = GetReadOrder485.createMeterOrder(collectionNum, "1");
+//// ByteBuf buffer = getByteBuf(ctx, sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+//// log.info("客户端再次往服务端发送数据" + num);
+//// }
+//// } else if ((receiveStr.length() > 44)) {
+//// log.info(receiveStr);
+//// receiveStr = null;
+//// ctx.flush();
+//// ctx.close();
+//// }
+// ctx.flush();
+// }
+//
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyEchoServer.java b/user-service/src/main/java/com/mh/user/netty/NettyEchoServer.java
index d0d1c75..a85a2d4 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyEchoServer.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyEchoServer.java
@@ -1,179 +1,179 @@
-package com.mh.user.netty;
-
-import com.mh.user.utils.ExchangeStringUtil;
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioServerSocketChannel;
-import io.netty.handler.logging.LogLevel;
-import io.netty.handler.logging.LoggingHandler;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.util.StringUtils;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-
-
-/**
- * @author ljf
- * @title :Netty
- * @description :netty 使用
- * @updateTime 2020-04-21
- * @throws :
- */
-@Slf4j
-public class NettyEchoServer {
-
- public void bind(int port) throws Exception {
- // accept线程组,用来接收连接
- EventLoopGroup bossGroup = new NioEventLoopGroup(1);
- // IO 线程组,用来处理业务逻辑
- EventLoopGroup workerGroup = new NioEventLoopGroup(1);
-
- try {
- // 服务端启动引导
- ServerBootstrap serverBootstrap = new ServerBootstrap();
- serverBootstrap.group(bossGroup,workerGroup) // 绑定两个线程
- .channel(NioServerSocketChannel.class) // 指定通道类型
- .option(ChannelOption.SO_BACKLOG, 1024) // 设置TCP连接的缓冲区
- .handler(new LoggingHandler(LogLevel.INFO)) // 设置日志级别
- .childHandler(new ChannelInitializer() {
- @Override
- protected void initChannel(SocketChannel socketChannel) throws Exception {
- ChannelPipeline pipeline = socketChannel.pipeline(); // 获取处理器链
- pipeline.addLast(new EchoServerHandler()); // 添加新的事件处理器
- }
- });
- // 通过bind启动服务
- ChannelFuture f = serverBootstrap.bind(port).sync();
- // 阻塞主线程,知道网络服务被关闭
- f.channel().closeFuture().sync();
- } catch (Exception e){
- e.printStackTrace();
- } finally {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- }
-
- static class EchoServerHandler extends ChannelHandlerAdapter {
-
- // 每当从客户端收到新的数据时,这个方法会在收到消息时被调用
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- try {
- ByteBuf buf = (ByteBuf)msg;
- byte [] bytes = new byte[buf.readableBytes()];
- buf.readBytes(bytes);//复制内容到字节数组bytes
- String receiveStr = ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
- log.info("接收到的数据: "+ receiveStr);
- //返回16进制到客户端
- writeToClient(receiveStr,ctx,"测试");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-// ctx.write(Unpooled.wrappedBuffer("Server message".getBytes()));
-// ctx.fireChannelRead(msg);
- }
-
- // 数据读取完后被调用
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- ctx.flush();
- }
-
- // 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- cause.printStackTrace();
- ctx.close();
- }
-
- /**
- * 客户端与服务端第一次建立连接时 执行
- *
- * @param ctx
- * @throws Exception
- */
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException
- {
- super.channelActive(ctx);
- ctx.channel().read();
- InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
- String clientIp = ifsock.getAddress().getHostAddress();
- //此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
- log.info("channelActive: "+clientIp + ctx.name());
- }
-
- /**
- * 客户端与服务端 断连时 执行
- *
- * @param ctx
- * @throws Exception
- */
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException
- {
- super.channelInactive(ctx);
- InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
- String clientIp = ifsock.getAddress().getHostAddress();
- ctx.close(); //断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
- System.out.println("channelInactive:"+clientIp);
- }
-
- /**
- * 服务端当read超时, 会调用这个方法
- *
- * @param ctx
- * @param evt
- * @throws Exception
- */
- @Override
- public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException
- {
- super.userEventTriggered(ctx, evt);
- InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
- String clientIp = ifsock.getAddress().getHostAddress();
- ctx.close();//超时时断开连接
- System.out.println("userEventTriggered:"+clientIp);
- }
-
-
- /**
- * 公用回写数据到客户端的方法
- * @param channel
- * @param mark 用于打印/log的输出
- *
//channel.writeAndFlush(msg);//不行
- *
//channel.writeAndFlush(receiveStr.getBytes());//不行
- *
在netty里,进出的都是ByteBuf,楼主应确定服务端是否有对应的编码器,将字符串转化为ByteBuf
- */
- private void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark) {
- try {
- ByteBuf buff = Unpooled.buffer();//netty需要用ByteBuf传输
- buff.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(receiveStr));//对接需要16进制
- channel.writeAndFlush(buff).addListener((ChannelFutureListener) future -> {
- StringBuilder sb = new StringBuilder("");
- if(!StringUtils.isEmpty(mark)){
- sb.append("【").append(mark).append("】");
- }
- if (future.isSuccess()) {
- System.out.println(sb.toString()+"回写成功"+receiveStr);
- log.info(sb.toString()+"回写成功"+receiveStr);
- } else {
- System.out.println(sb.toString()+"回写失败"+receiveStr);
- log.error(sb.toString()+"回写失败"+receiveStr);
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("调用通用writeToClient()异常"+e.getMessage());
- log.error("调用通用writeToClient()异常:",e);
- }
- }
- }
-}
+//package com.mh.user.netty;
+//
+//import com.mh.user.utils.ExchangeStringUtil;
+//import io.netty.bootstrap.ServerBootstrap;
+//import io.netty.buffer.ByteBuf;
+//import io.netty.buffer.Unpooled;
+//import io.netty.channel.*;
+//import io.netty.channel.nio.NioEventLoopGroup;
+//import io.netty.channel.socket.SocketChannel;
+//import io.netty.channel.socket.nio.NioServerSocketChannel;
+//import io.netty.handler.logging.LogLevel;
+//import io.netty.handler.logging.LoggingHandler;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.util.StringUtils;
+//
+//import java.io.IOException;
+//import java.net.InetSocketAddress;
+//
+//
+///**
+// * @author ljf
+// * @title :Netty
+// * @description :netty 使用
+// * @updateTime 2020-04-21
+// * @throws :
+// */
+//@Slf4j
+//public class NettyEchoServer {
+//
+// public void bind(int port) throws Exception {
+// // accept线程组,用来接收连接
+// EventLoopGroup bossGroup = new NioEventLoopGroup(1);
+// // IO 线程组,用来处理业务逻辑
+// EventLoopGroup workerGroup = new NioEventLoopGroup(1);
+//
+// try {
+// // 服务端启动引导
+// ServerBootstrap serverBootstrap = new ServerBootstrap();
+// serverBootstrap.group(bossGroup,workerGroup) // 绑定两个线程
+// .channel(NioServerSocketChannel.class) // 指定通道类型
+// .option(ChannelOption.SO_BACKLOG, 1024) // 设置TCP连接的缓冲区
+// .handler(new LoggingHandler(LogLevel.INFO)) // 设置日志级别
+// .childHandler(new ChannelInitializer() {
+// @Override
+// protected void initChannel(SocketChannel socketChannel) throws Exception {
+// ChannelPipeline pipeline = socketChannel.pipeline(); // 获取处理器链
+// pipeline.addLast(new EchoServerHandler()); // 添加新的事件处理器
+// }
+// });
+// // 通过bind启动服务
+// ChannelFuture f = serverBootstrap.bind(port).sync();
+// // 阻塞主线程,知道网络服务被关闭
+// f.channel().closeFuture().sync();
+// } catch (Exception e){
+// e.printStackTrace();
+// } finally {
+// workerGroup.shutdownGracefully();
+// bossGroup.shutdownGracefully();
+// }
+// }
+//
+// static class EchoServerHandler extends ChannelHandlerAdapter {
+//
+// // 每当从客户端收到新的数据时,这个方法会在收到消息时被调用
+// @Override
+// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+// try {
+// ByteBuf buf = (ByteBuf)msg;
+// byte [] bytes = new byte[buf.readableBytes()];
+// buf.readBytes(bytes);//复制内容到字节数组bytes
+// String receiveStr = ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+// log.info("接收到的数据: "+ receiveStr);
+// //返回16进制到客户端
+// writeToClient(receiveStr,ctx,"测试");
+// } catch (Exception e) {
+// // TODO Auto-generated catch block
+// e.printStackTrace();
+// }
+//// ctx.write(Unpooled.wrappedBuffer("Server message".getBytes()));
+//// ctx.fireChannelRead(msg);
+// }
+//
+// // 数据读取完后被调用
+// @Override
+// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+// ctx.flush();
+// }
+//
+// // 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用
+// @Override
+// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+// cause.printStackTrace();
+// ctx.close();
+// }
+//
+// /**
+// * 客户端与服务端第一次建立连接时 执行
+// *
+// * @param ctx
+// * @throws Exception
+// */
+// @Override
+// public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException
+// {
+// super.channelActive(ctx);
+// ctx.channel().read();
+// InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
+// String clientIp = ifsock.getAddress().getHostAddress();
+// //此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
+// log.info("channelActive: "+clientIp + ctx.name());
+// }
+//
+// /**
+// * 客户端与服务端 断连时 执行
+// *
+// * @param ctx
+// * @throws Exception
+// */
+// @Override
+// public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException
+// {
+// super.channelInactive(ctx);
+// InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
+// String clientIp = ifsock.getAddress().getHostAddress();
+// ctx.close(); //断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
+// System.out.println("channelInactive:"+clientIp);
+// }
+//
+// /**
+// * 服务端当read超时, 会调用这个方法
+// *
+// * @param ctx
+// * @param evt
+// * @throws Exception
+// */
+// @Override
+// public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException
+// {
+// super.userEventTriggered(ctx, evt);
+// InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
+// String clientIp = ifsock.getAddress().getHostAddress();
+// ctx.close();//超时时断开连接
+// System.out.println("userEventTriggered:"+clientIp);
+// }
+//
+//
+// /**
+// * 公用回写数据到客户端的方法
+// * @param channel
+// * @param mark 用于打印/log的输出
+// *
//channel.writeAndFlush(msg);//不行
+// *
//channel.writeAndFlush(receiveStr.getBytes());//不行
+// *
在netty里,进出的都是ByteBuf,楼主应确定服务端是否有对应的编码器,将字符串转化为ByteBuf
+// */
+// private void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark) {
+// try {
+// ByteBuf buff = Unpooled.buffer();//netty需要用ByteBuf传输
+// buff.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(receiveStr));//对接需要16进制
+// channel.writeAndFlush(buff).addListener((ChannelFutureListener) future -> {
+// StringBuilder sb = new StringBuilder("");
+// if(!StringUtils.isEmpty(mark)){
+// sb.append("【").append(mark).append("】");
+// }
+// if (future.isSuccess()) {
+// System.out.println(sb.toString()+"回写成功"+receiveStr);
+// log.info(sb.toString()+"回写成功"+receiveStr);
+// } else {
+// System.out.println(sb.toString()+"回写失败"+receiveStr);
+// log.error(sb.toString()+"回写失败"+receiveStr);
+// }
+// });
+// } catch (Exception e) {
+// e.printStackTrace();
+// System.out.println("调用通用writeToClient()异常"+e.getMessage());
+// log.error("调用通用writeToClient()异常:",e);
+// }
+// }
+// }
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClient.java b/user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClient.java
index b95a213..a5ff438 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClient.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClient.java
@@ -1,97 +1,97 @@
-package com.mh.user.netty;
-
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.timeout.IdleStateHandler;
-import io.netty.handler.timeout.ReadTimeoutHandler;
-import lombok.Getter;
-import lombok.Setter;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author ljf
- * @title :
- * @description :Netty客户端,采集电表
- * @updateTime 2020-05-13
- * @throws :
- */
-@Slf4j
-@Setter
-@Getter
-public class NettyMeterAndCloudClient {
-// implements Runnable {
-
- private int port;
- private String host;
-
- // 构造函数传递值 继承Thread时需要
- public NettyMeterAndCloudClient(int port, String host) {
- this.port = port;
- this.host = host;
- }
-
- public NettyMeterAndCloudClient() {
- super();
- }
-
- public void connect(int port, String host) throws InterruptedException {
- // 配置客户端NIO线程组
- EventLoopGroup group = new NioEventLoopGroup(1);
- try {
- Bootstrap bootstrap = new Bootstrap();
- bootstrap.group(group).channel(NioSocketChannel.class)
- .option(ChannelOption.TCP_NODELAY, true)
- .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
- .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
- .handler(new ChannelInitializer() {
- @Override
- protected void initChannel(SocketChannel socketChannel) {
- // 基于换行符号
-// socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
-// // 解码转String,注意调整自己的编码格式GBK、UTF-8
-// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
-// // 解码转String,注意调整自己的编码格式GBK、UTF-8
-// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
- // 超过10秒钟没有数据读取自动断开连接
- socketChannel.pipeline().addLast(new IdleStateHandler(10,10,10, TimeUnit.SECONDS));
- // 在管道中添加我们自己的接收数据实现方法
-// socketChannel.pipeline().addLast(new NettyClientHandler());
- socketChannel.pipeline().addLast(new NettyMeterAndCloudClientHandler());
- }
- });
- // 发起异步连接操作
- ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
- if (channelFuture.isSuccess()) {
- log.info("connect server 成功---------");
- } else {
- log.info("连接失败!");
- log.info("准备重连!");
-// connect(port, host);
- }
-
- // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
- channelFuture.channel().closeFuture().sync();
- } catch (Exception e) {
- log.error(e.getMessage());
- } finally {
- group.shutdownGracefully();
-// try {
-// TimeUnit.SECONDS.sleep(5);
-// connect(port, host); // 断线重连
-// } catch (InterruptedException e) {
-// e.printStackTrace();
+//package com.mh.user.netty;
+//
+//import io.netty.bootstrap.Bootstrap;
+//import io.netty.channel.*;
+//import io.netty.channel.nio.NioEventLoopGroup;
+//import io.netty.channel.socket.SocketChannel;
+//import io.netty.channel.socket.nio.NioSocketChannel;
+//import io.netty.handler.timeout.IdleStateHandler;
+//import io.netty.handler.timeout.ReadTimeoutHandler;
+//import lombok.Getter;
+//import lombok.Setter;
+//import lombok.extern.slf4j.Slf4j;
+//
+//import java.util.concurrent.TimeUnit;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description :Netty客户端,采集电表
+// * @updateTime 2020-05-13
+// * @throws :
+// */
+//@Slf4j
+//@Setter
+//@Getter
+//public class NettyMeterAndCloudClient {
+//// implements Runnable {
+//
+// private int port;
+// private String host;
+//
+// // 构造函数传递值 继承Thread时需要
+// public NettyMeterAndCloudClient(int port, String host) {
+// this.port = port;
+// this.host = host;
+// }
+//
+// public NettyMeterAndCloudClient() {
+// super();
+// }
+//
+// public void connect(int port, String host) throws InterruptedException {
+// // 配置客户端NIO线程组
+// EventLoopGroup group = new NioEventLoopGroup(1);
+// try {
+// Bootstrap bootstrap = new Bootstrap();
+// bootstrap.group(group).channel(NioSocketChannel.class)
+// .option(ChannelOption.TCP_NODELAY, true)
+// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
+// .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
+// .handler(new ChannelInitializer() {
+// @Override
+// protected void initChannel(SocketChannel socketChannel) {
+// // 基于换行符号
+//// socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
+//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
+//// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
+//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
+//// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
+// // 超过10秒钟没有数据读取自动断开连接
+// socketChannel.pipeline().addLast(new IdleStateHandler(10,10,10, TimeUnit.SECONDS));
+// // 在管道中添加我们自己的接收数据实现方法
+//// socketChannel.pipeline().addLast(new NettyClientHandler());
+// socketChannel.pipeline().addLast(new NettyMeterAndCloudClientHandler());
+// }
+// });
+// // 发起异步连接操作
+// ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
+// if (channelFuture.isSuccess()) {
+// log.info("connect server 成功---------");
+// } else {
+// log.info("连接失败!");
+// log.info("准备重连!");
+//// connect(port, host);
// }
- }
- }
//
-// @SneakyThrows
-// @Override
-// public void run() {
-// connect(port, host);
+// // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
+// channelFuture.channel().closeFuture().sync();
+// } catch (Exception e) {
+// log.error(e.getMessage());
+// } finally {
+// group.shutdownGracefully();
+//// try {
+//// TimeUnit.SECONDS.sleep(5);
+//// connect(port, host); // 断线重连
+//// } catch (InterruptedException e) {
+//// e.printStackTrace();
+//// }
+// }
// }
-}
+////
+//// @SneakyThrows
+//// @Override
+//// public void run() {
+//// connect(port, host);
+//// }
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClientHandler.java b/user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClientHandler.java
index f8d876a..897f0bb 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClientHandler.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClientHandler.java
@@ -1,193 +1,193 @@
-package com.mh.user.netty;
-
-import com.mh.user.constants.Constant;
-import com.mh.user.entity.DeviceManageEntity;
-import com.mh.user.service.DeviceManageService;
-import com.mh.user.utils.*;
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandlerAdapter;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.timeout.IdleState;
-import io.netty.handler.timeout.IdleStateEvent;
-import io.netty.util.ReferenceCountUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.context.ApplicationContext;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-
-/**
- * @author ljf
- * @title :
- * @description :客户端异步消息处理机制
- * @updateTime 2020-05-13
- * @throws :
- */
-@Slf4j
-public class NettyMeterAndCloudClientHandler extends ChannelHandlerAdapter {
-
-
- private int num = 0;
- private int size = 0;
- private String receiveStr = null;
- private int idle_count = 0;
- private String IP = "";
- private String port = "";
-
- List deviceManageEntityList;
-
- // 调用service
- ApplicationContext context = SpringBeanUtil.getApplicationContext();
- DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
-
- AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
-
- @Override
- public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
- log.info("当前channel从EventLoop取消注册");
- super.channelUnregistered(ctx);
- }
-
- /**
- * 超时处理
- * 如果120秒没有接受客户端的心跳,就触发;
- * 如果超过3次,则直接关闭;
- */
- @Override
- public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
- if (obj instanceof IdleStateEvent) {
- IdleStateEvent event = (IdleStateEvent) obj;
- if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
- System.out.println("第" + idle_count + "已经20秒没有接收到服务器的信息了,发送的第" + num + "条数据");
- if (deviceManageEntityList.get(num) == null) {
- ctx.channel().close();
- } else {
- if (idle_count > 3 || num > size - 1) {
- System.out.println("关闭这个不活跃的channel");
- ctx.channel().close();
- }
-
- SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(num), num, IP, port, ctx);
- idle_count++;
- }
- }
- } else {
- super.userEventTriggered(ctx, obj);
- }
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- log.info("通信异常!!");
- Channel incoming = ctx.channel();
- if (incoming.isActive()) {
- log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
- receiveStr = null;
- cause.printStackTrace();
- ctx.close();
- }
- }
-
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
-// super.channelActive(ctx);
- // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
- if (Constant.WEB_FLAG) {
- num = 0;
- // 关闭连接
- receiveStr = null;
- ctx.close();
- } else {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
- Date date = new Date();
- log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
-
- // 截取IP地址
- IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
- // 截取端口号
- port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
- log.info("IP: " + IP + ",端口号: " + port);
-
- // 生成对应的采集指令
- deviceManageEntityList = deviceManageService.queryDevicesByType(null);
- size = deviceManageEntityList.size();
-
- log.info("初始连接报文: " + receiveStr);
- receiveStr = "";
- // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
- SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(0), 0, IP, port, ctx);
- }
- }
-
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- Thread.sleep(500);
- receiveStr = null;
- ctx.close();
- log.info(ctx.channel().localAddress() + "退出链接!!");
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- try {
- ByteBuf buf = (ByteBuf) msg;
- byte[] bytes = new byte[buf.readableBytes()];
- buf.readBytes(bytes);//复制内容到字节数组bytes
- buf.clear();
- log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
- if (bytes.length <= 62) {
-// if (bytes.length <= 142) {
-// receiveStr = receiveStr.replace("null", "");
-// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
-// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
- receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
- receiveStr = receiveStr.replace("null", "");
- log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- ReferenceCountUtil.release(msg);
- }
- }
-
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- log.info("采集电表或者冷量计-数据读取接收完成: " + receiveStr);
- if ((receiveStr.length() == 36) && (deviceManageEntityList.get(num).getParamId() == 3)) {
-// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
- } else if ((receiveStr.length() == 62) && (deviceManageEntityList.get(num).getParamId() == 1)) {
-// 把receiveStr的"null"值去掉
-// a9fec2c71f9002fefefefe6839025007000068810643c3bb446c338d16c2b8
-// A9 FE C2 C7 1F 90 02 FE FE FE FE 68 39 02 50 07 00 00 68 81 06 43 C3 5B 38 6C 33 21 16 F8 12
- analysisReceiveOrder485.analysisMeterOrder485(receiveStr,"","",""); // 解析电表
- }
- receiveStr = "";
- num = num + 1;
- Thread.sleep(600);
- if (num > size - 1) {
- num = 0;
- receiveStr = null;
- // 关闭连接
- ctx.close();
-// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
-// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
- } else {
- // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
- if (Constant.WEB_FLAG) {
- log.info("有指令下发退出定时采集DDC参数");
- num = 0;
- // 关闭连接
- receiveStr = null;
- ctx.close();
- } else {
- // 封装发送电表工具方法 update by ljf on 2021-01-26
- SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(num), num, IP, port, ctx);
- }
- }
- ctx.flush();
- }
-}
+//package com.mh.user.netty;
+//
+//import com.mh.user.constants.Constant;
+//import com.mh.user.entity.DeviceManageEntity;
+//import com.mh.user.service.DeviceManageService;
+//import com.mh.user.utils.*;
+//import io.netty.buffer.ByteBuf;
+//import io.netty.channel.Channel;
+//import io.netty.channel.ChannelHandlerAdapter;
+//import io.netty.channel.ChannelHandlerContext;
+//import io.netty.handler.timeout.IdleState;
+//import io.netty.handler.timeout.IdleStateEvent;
+//import io.netty.util.ReferenceCountUtil;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.context.ApplicationContext;
+//
+//import java.text.SimpleDateFormat;
+//import java.util.Date;
+//import java.util.List;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description :客户端异步消息处理机制
+// * @updateTime 2020-05-13
+// * @throws :
+// */
+//@Slf4j
+//public class NettyMeterAndCloudClientHandler extends ChannelHandlerAdapter {
+//
+//
+// private int num = 0;
+// private int size = 0;
+// private String receiveStr = null;
+// private int idle_count = 0;
+// private String IP = "";
+// private String port = "";
+//
+// List deviceManageEntityList;
+//
+// // 调用service
+// ApplicationContext context = SpringBeanUtil.getApplicationContext();
+// DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
+//
+// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
+//
+// @Override
+// public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
+// log.info("当前channel从EventLoop取消注册");
+// super.channelUnregistered(ctx);
+// }
+//
+// /**
+// * 超时处理
+// * 如果120秒没有接受客户端的心跳,就触发;
+// * 如果超过3次,则直接关闭;
+// */
+// @Override
+// public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
+// if (obj instanceof IdleStateEvent) {
+// IdleStateEvent event = (IdleStateEvent) obj;
+// if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
+// System.out.println("第" + idle_count + "已经20秒没有接收到服务器的信息了,发送的第" + num + "条数据");
+// if (deviceManageEntityList.get(num) == null) {
+// ctx.channel().close();
+// } else {
+// if (idle_count > 3 || num > size - 1) {
+// System.out.println("关闭这个不活跃的channel");
+// ctx.channel().close();
+// }
+//
+// SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(num), num, IP, port, ctx);
+// idle_count++;
+// }
+// }
+// } else {
+// super.userEventTriggered(ctx, obj);
+// }
+// }
+//
+// @Override
+// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+// log.info("通信异常!!");
+// Channel incoming = ctx.channel();
+// if (incoming.isActive()) {
+// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
+// receiveStr = null;
+// cause.printStackTrace();
+// ctx.close();
+// }
+// }
+//
+//
+// @Override
+// public void channelActive(ChannelHandlerContext ctx) throws Exception {
+//// super.channelActive(ctx);
+// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
+// if (Constant.WEB_FLAG) {
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// ctx.close();
+// } else {
+// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
+// Date date = new Date();
+// log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
+//
+// // 截取IP地址
+// IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
+// // 截取端口号
+// port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
+// log.info("IP: " + IP + ",端口号: " + port);
+//
+// // 生成对应的采集指令
+// deviceManageEntityList = deviceManageService.queryDevicesByType(null);
+// size = deviceManageEntityList.size();
+//
+// log.info("初始连接报文: " + receiveStr);
+// receiveStr = "";
+// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
+// SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(0), 0, IP, port, ctx);
+// }
+// }
+//
+// @Override
+// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+// Thread.sleep(500);
+// receiveStr = null;
+// ctx.close();
+// log.info(ctx.channel().localAddress() + "退出链接!!");
+// }
+//
+// @Override
+// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+// try {
+// ByteBuf buf = (ByteBuf) msg;
+// byte[] bytes = new byte[buf.readableBytes()];
+// buf.readBytes(bytes);//复制内容到字节数组bytes
+// buf.clear();
+// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
+// if (bytes.length <= 62) {
+//// if (bytes.length <= 142) {
+//// receiveStr = receiveStr.replace("null", "");
+//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+//// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+// receiveStr = receiveStr.replace("null", "");
+// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+// }
+// } catch (Exception e) {
+// e.printStackTrace();
+// } finally {
+// ReferenceCountUtil.release(msg);
+// }
+// }
+//
+// @Override
+// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+// log.info("采集电表或者冷量计-数据读取接收完成: " + receiveStr);
+// if ((receiveStr.length() == 36) && (deviceManageEntityList.get(num).getParamId() == 3)) {
+//// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
+// } else if ((receiveStr.length() == 62) && (deviceManageEntityList.get(num).getParamId() == 1)) {
+//// 把receiveStr的"null"值去掉
+//// a9fec2c71f9002fefefefe6839025007000068810643c3bb446c338d16c2b8
+//// A9 FE C2 C7 1F 90 02 FE FE FE FE 68 39 02 50 07 00 00 68 81 06 43 C3 5B 38 6C 33 21 16 F8 12
+// analysisReceiveOrder485.analysisMeterOrder485(receiveStr,"","","", null); // 解析电表
+// }
+// receiveStr = "";
+// num = num + 1;
+// Thread.sleep(600);
+// if (num > size - 1) {
+// num = 0;
+// receiveStr = null;
+// // 关闭连接
+// ctx.close();
+//// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
+//// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
+// } else {
+// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
+// if (Constant.WEB_FLAG) {
+// log.info("有指令下发退出定时采集DDC参数");
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// ctx.close();
+// } else {
+// // 封装发送电表工具方法 update by ljf on 2021-01-26
+// SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(num), num, IP, port, ctx);
+// }
+// }
+// ctx.flush();
+// }
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyMeterClient.java b/user-service/src/main/java/com/mh/user/netty/NettyMeterClient.java
index 77f00df..59b2f23 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyMeterClient.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyMeterClient.java
@@ -1,96 +1,96 @@
-package com.mh.user.netty;
-
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.timeout.ReadTimeoutHandler;
-import lombok.Getter;
-import lombok.Setter;
-import lombok.SneakyThrows;
-import lombok.extern.slf4j.Slf4j;
-
-/**
- * @author ljf
- * @title :
- * @description :Netty客户端,采集电表
- * @updateTime 2020-05-13
- * @throws :
- */
-@Slf4j
-@Setter
-@Getter
-public class NettyMeterClient {
-// implements Runnable {
-
- private int port;
- private String host;
-
- // 构造函数传递值 继承Thread时需要
- public NettyMeterClient(int port, String host) {
- this.port = port;
- this.host = host;
- }
-
- public NettyMeterClient() {
- super();
- }
-
- public void connect(int port, String host) throws InterruptedException {
- // 配置客户端NIO线程组
- // 配置客户端NIO线程组
- EventLoopGroup group = new NioEventLoopGroup(1);
- try {
- Bootstrap bootstrap = new Bootstrap();
- bootstrap.group(group).channel(NioSocketChannel.class)
- .option(ChannelOption.TCP_NODELAY, true)
- .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
- .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
- .handler(new ChannelInitializer() {
- @Override
- protected void initChannel(SocketChannel socketChannel) {
- // 基于换行符号
-// socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
-// // 解码转String,注意调整自己的编码格式GBK、UTF-8
-// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
-// // 解码转String,注意调整自己的编码格式GBK、UTF-8
-// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
- // 超过10秒钟没有数据读取自动断开连接
- socketChannel.pipeline().addLast(new ReadTimeoutHandler(20));
- // 在管道中添加我们自己的接收数据实现方法
-// socketChannel.pipeline().addLast(new NettyClientHandler());
- socketChannel.pipeline().addLast(new NettyMeterClientHandler1());
- }
- });
- // 发起异步连接操作
- ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
- if (channelFuture.isSuccess()) {
- log.info("connect server 成功---------");
- } else {
- log.info("连接失败!");
- log.info("准备重连!");
-// connect(port, host);
- }
-
- // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
- channelFuture.channel().closeFuture().sync();
- } catch (Exception e) {
- log.error(e.getMessage());
- } finally {
- group.shutdownGracefully();
-// try {
-// TimeUnit.SECONDS.sleep(5);
-// connect(port, host); // 断线重连
-// } catch (InterruptedException e) {
-// e.printStackTrace();
+//package com.mh.user.netty;
+//
+//import io.netty.bootstrap.Bootstrap;
+//import io.netty.channel.*;
+//import io.netty.channel.nio.NioEventLoopGroup;
+//import io.netty.channel.socket.SocketChannel;
+//import io.netty.channel.socket.nio.NioSocketChannel;
+//import io.netty.handler.timeout.ReadTimeoutHandler;
+//import lombok.Getter;
+//import lombok.Setter;
+//import lombok.SneakyThrows;
+//import lombok.extern.slf4j.Slf4j;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description :Netty客户端,采集电表
+// * @updateTime 2020-05-13
+// * @throws :
+// */
+//@Slf4j
+//@Setter
+//@Getter
+//public class NettyMeterClient {
+//// implements Runnable {
+//
+// private int port;
+// private String host;
+//
+// // 构造函数传递值 继承Thread时需要
+// public NettyMeterClient(int port, String host) {
+// this.port = port;
+// this.host = host;
+// }
+//
+// public NettyMeterClient() {
+// super();
+// }
+//
+// public void connect(int port, String host) throws InterruptedException {
+// // 配置客户端NIO线程组
+// // 配置客户端NIO线程组
+// EventLoopGroup group = new NioEventLoopGroup(1);
+// try {
+// Bootstrap bootstrap = new Bootstrap();
+// bootstrap.group(group).channel(NioSocketChannel.class)
+// .option(ChannelOption.TCP_NODELAY, true)
+// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
+// .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
+// .handler(new ChannelInitializer() {
+// @Override
+// protected void initChannel(SocketChannel socketChannel) {
+// // 基于换行符号
+//// socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
+//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
+//// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
+//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
+//// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
+// // 超过10秒钟没有数据读取自动断开连接
+// socketChannel.pipeline().addLast(new ReadTimeoutHandler(20));
+// // 在管道中添加我们自己的接收数据实现方法
+//// socketChannel.pipeline().addLast(new NettyClientHandler());
+// socketChannel.pipeline().addLast(new NettyMeterClientHandler1());
+// }
+// });
+// // 发起异步连接操作
+// ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
+// if (channelFuture.isSuccess()) {
+// log.info("connect server 成功---------");
+// } else {
+// log.info("连接失败!");
+// log.info("准备重连!");
+//// connect(port, host);
// }
- }
- }
//
-// @SneakyThrows
-// @Override
-// public void run() {
-// connect(port, host);
+// // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
+// channelFuture.channel().closeFuture().sync();
+// } catch (Exception e) {
+// log.error(e.getMessage());
+// } finally {
+// group.shutdownGracefully();
+//// try {
+//// TimeUnit.SECONDS.sleep(5);
+//// connect(port, host); // 断线重连
+//// } catch (InterruptedException e) {
+//// e.printStackTrace();
+//// }
+// }
// }
-}
+////
+//// @SneakyThrows
+//// @Override
+//// public void run() {
+//// connect(port, host);
+//// }
+//}
diff --git a/user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler1.java b/user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler1.java
index d2f2c65..c7085da 100644
--- a/user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler1.java
+++ b/user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler1.java
@@ -1,259 +1,259 @@
-package com.mh.user.netty;
-
-import com.mh.user.constants.Constant;
-import com.mh.user.entity.DeviceManageEntity;
-import com.mh.user.service.DeviceManageService;
-import com.mh.user.utils.*;
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandlerAdapter;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.util.ReferenceCountUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.context.ApplicationContext;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-
-/**
- * @author ljf
- * @title :
- * @description :客户端异步消息处理机制
- * @updateTime 2020-05-13
- * @throws :
- */
-@Slf4j
-public class NettyMeterClientHandler1 extends ChannelHandlerAdapter {
-
-
- private int num = 0;
- private int size = 0;
- private String receiveStr = null;
- private String IP = "";
- private String port = "";
- List deviceManageEntityList;
-
- // 调用service
- ApplicationContext context = SpringBeanUtil.getApplicationContext();
- DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
-
- AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
-
- @Override
- public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
- log.info("当前channel从EventLoop取消注册");
- super.channelUnregistered(ctx);
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-// super.exceptionCaught(ctx, cause);
- log.info("通信异常!!");
-// receiveStr = null;
- Channel incoming = ctx.channel();
- if (incoming.isActive()) {
- log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
- receiveStr = null;
- cause.printStackTrace();
- ctx.close();
-// receiveStr = null;
-// try {
-// TimeUnit.SECONDS.sleep(5);
-// SocketAddress remoteAddress = ctx.channel().remoteAddress();
-// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
-// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
-// NettyClient nettyClient = new NettyClient();
-// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
-// } catch (InterruptedException e) {
-// e.printStackTrace();
-// }
- }
- }
-
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
-// super.channelActive(ctx);
- // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
- if (Constant.WEB_FLAG) {
- num = 0;
- // 关闭连接
- receiveStr = null;
- ctx.close();
- } else {
- ctx.channel().read();
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
- Date date = new Date();
- log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
-
- // 截取IP地址
- IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
- // 截取端口号
- port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
- log.info("IP: " + IP + ",端口号: " + port);
-
- // 生成对应的采集指令
- // 修改生成指令(冷量计和电量一起采集) update by ljf on 2021-01-27
- deviceManageEntityList = deviceManageService.queryDevicesByType(null);
- size = deviceManageEntityList.size();
-
- log.info("初始连接报文: " + receiveStr);
- receiveStr = "";
- // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
- SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(0), 0, IP, port, ctx);
- // 1.创建将要写出的数据
-// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表
-// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表
-// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
-// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
-// deviceManageEntityList.get(0).getDataCom(), collectionNum, "1");
-//// FileUtils.createFileAndWrite(sendStr, 0);
-// ByteBuf buffer = getByteBuf(ctx, sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
- }
-
- }
-
- private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
- // byte类型的数据
-// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
-// String sendStr = "5803004900021914"; // 冷量计
- // 申请一个数据结构存储信息
- ByteBuf buffer = ctx.alloc().buffer();
- // 将信息放入数据结构中
- buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
- return buffer;
- }
-
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- Thread.sleep(500);
- receiveStr = null;
- ctx.close();
- log.info(ctx.channel().localAddress() + "退出链接!!");
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- try {
- ByteBuf buf = (ByteBuf) msg;
- byte[] bytes = new byte[buf.readableBytes()];
- buf.readBytes(bytes);//复制内容到字节数组bytes
- buf.clear();
- log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
- if (bytes.length <= 62) {
-// if (bytes.length <= 142) {
-// receiveStr = receiveStr.replace("null", "");
-// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
-// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
- receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
- receiveStr = receiveStr.replace("null", "");
- log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- ReferenceCountUtil.release(msg);
- }
-// super.channelRead(ctx, msg);
- // ByteBuf buf = (ByteBuf)msg;
-// byte[] req = new byte[buf.readableBytes()];
-// buf.readBytes(req);
-// String body = new String(req, "UTF-8");
-// ByteBuf buf = (ByteBuf)msg;
-// byte [] bytes = new byte[buf.readableBytes()];
-// buf.readBytes(bytes);//复制内容到字节数组bytes
-// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
-// if (bytes.length != 0) {
+//package com.mh.user.netty;
+//
+//import com.mh.user.constants.Constant;
+//import com.mh.user.entity.DeviceManageEntity;
+//import com.mh.user.service.DeviceManageService;
+//import com.mh.user.utils.*;
+//import io.netty.buffer.ByteBuf;
+//import io.netty.channel.Channel;
+//import io.netty.channel.ChannelHandlerAdapter;
+//import io.netty.channel.ChannelHandlerContext;
+//import io.netty.util.ReferenceCountUtil;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.context.ApplicationContext;
+//
+//import java.text.SimpleDateFormat;
+//import java.util.Date;
+//import java.util.List;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description :客户端异步消息处理机制
+// * @updateTime 2020-05-13
+// * @throws :
+// */
+//@Slf4j
+//public class NettyMeterClientHandler1 extends ChannelHandlerAdapter {
+//
+//
+// private int num = 0;
+// private int size = 0;
+// private String receiveStr = null;
+// private String IP = "";
+// private String port = "";
+// List deviceManageEntityList;
+//
+// // 调用service
+// ApplicationContext context = SpringBeanUtil.getApplicationContext();
+// DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
+//
+// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
+//
+// @Override
+// public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
+// log.info("当前channel从EventLoop取消注册");
+// super.channelUnregistered(ctx);
+// }
+//
+// @Override
+// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+//// super.exceptionCaught(ctx, cause);
+// log.info("通信异常!!");
+//// receiveStr = null;
+// Channel incoming = ctx.channel();
+// if (incoming.isActive()) {
+// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
+// receiveStr = null;
+// cause.printStackTrace();
+// ctx.close();
+//// receiveStr = null;
+//// try {
+//// TimeUnit.SECONDS.sleep(5);
+//// SocketAddress remoteAddress = ctx.channel().remoteAddress();
+//// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
+//// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
+//// NettyClient nettyClient = new NettyClient();
+//// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
+//// } catch (InterruptedException e) {
+//// e.printStackTrace();
+//// }
+// }
+// }
+//
+//
+// @Override
+// public void channelActive(ChannelHandlerContext ctx) throws Exception {
+//// super.channelActive(ctx);
+// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
+// if (Constant.WEB_FLAG) {
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// ctx.close();
+// } else {
+// ctx.channel().read();
+// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
+// Date date = new Date();
+// log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
+//
+// // 截取IP地址
+// IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
+// // 截取端口号
+// port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
+// log.info("IP: " + IP + ",端口号: " + port);
+//
+// // 生成对应的采集指令
+// // 修改生成指令(冷量计和电量一起采集) update by ljf on 2021-01-27
+// deviceManageEntityList = deviceManageService.queryDevicesByType(null);
+// size = deviceManageEntityList.size();
+//
+// log.info("初始连接报文: " + receiveStr);
+// receiveStr = "";
+// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
+// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(0), 0, IP, port, ctx);
+// // 1.创建将要写出的数据
+//// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表
+//// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表
+//// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
+//// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
+//// deviceManageEntityList.get(0).getDataCom(), collectionNum, "1");
+////// FileUtils.createFileAndWrite(sendStr, 0);
+//// ByteBuf buffer = getByteBuf(ctx, sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+// }
+//
+// }
+//
+// private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
+// // byte类型的数据
+//// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
+//// String sendStr = "5803004900021914"; // 冷量计
+// // 申请一个数据结构存储信息
+// ByteBuf buffer = ctx.alloc().buffer();
+// // 将信息放入数据结构中
+// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
+// return buffer;
+// }
+//
+// @Override
+// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+// Thread.sleep(500);
+// receiveStr = null;
+// ctx.close();
+// log.info(ctx.channel().localAddress() + "退出链接!!");
+// }
+//
+// @Override
+// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+// try {
+// ByteBuf buf = (ByteBuf) msg;
+// byte[] bytes = new byte[buf.readableBytes()];
+// buf.readBytes(bytes);//复制内容到字节数组bytes
+// buf.clear();
+// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
+// if (bytes.length <= 62) {
+//// if (bytes.length <= 142) {
//// receiveStr = receiveStr.replace("null", "");
//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
//// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
-// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
-// receiveStr = receiveStr.replace("null", "");
-// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+// receiveStr = receiveStr.replace("null", "");
+// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+// }
+// } catch (Exception e) {
+// e.printStackTrace();
+// } finally {
+// ReferenceCountUtil.release(msg);
+// }
+//// super.channelRead(ctx, msg);
+// // ByteBuf buf = (ByteBuf)msg;
+//// byte[] req = new byte[buf.readableBytes()];
+//// buf.readBytes(req);
+//// String body = new String(req, "UTF-8");
+//// ByteBuf buf = (ByteBuf)msg;
+//// byte [] bytes = new byte[buf.readableBytes()];
+//// buf.readBytes(bytes);//复制内容到字节数组bytes
+//// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
+//// if (bytes.length != 0) {
+////// receiveStr = receiveStr.replace("null", "");
+////// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+////// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+//// receiveStr = receiveStr.replace("null", "");
+//// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
+//// }
+// }
+//
+// @Override
+// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+// log.info("采集电表-数据读取接收完成: " + receiveStr);
+//// 把receiveStr的"null"值去掉
+//// a9fec2c71f9002fefefefe6839025007000068810643c3bb446c338d16c2b8
+//// A9 FE C2 C7 1F 90 02 FE FE FE FE 68 39 02 50 07 00 00 68 81 06 43 C3 5B 38 6C 33 21 16 F8 12
+// if ((receiveStr.length() == 62)) {
+//// log.info(receiveStr);
+// analysisReceiveOrder485.analysisMeterOrder485(receiveStr,"","","", null); // 解析电表
+// receiveStr = "";
+// num = num + 1;
+// Thread.sleep(600);
+// if (num > size - 1) {
+// num = 0;
+// receiveStr = null;
+// // 关闭连接
+// ctx.close();
+//// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
+//// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
+// } else {
+// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
+// if (Constant.WEB_FLAG) {
+// log.info("有指令下发退出定时采集DDC参数");
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// ctx.close();
+// } else {
+// // 封装发送电表工具方法 update by ljf on 2021-01-26
+// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num), num, IP, port, ctx);
+// // 1.创建将要写出的数据
+// // fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
+//// String sendStr = "FEFEFE6880025007000068010243C3B216";
+//// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
+//// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
+//// deviceManageEntityList.get(num).getDataCom(), collectionNum, "1");
+//// ByteBuf buffer = getByteBuf(ctx, sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+//// log.info("客户端再次往服务端发送数据" + num);
+// }
+// }
+// } else if ((receiveStr.length() > 62)) {
+// receiveStr = null;
+// num = num + 1;
+// Thread.sleep(500);
+// if (num > size - 1) {
+// num = 0;
+// receiveStr = null;
+// // 关闭连接
+// ctx.close();
+//// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
+//// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
+// } else {
+// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
+// if (Constant.WEB_FLAG) {
+// log.info("有指令下发退出定时采集DDC参数");
+// num = 0;
+// // 关闭连接
+// receiveStr = null;
+// ctx.close();
+// } else {
+// // 封装发送电表工具方法 update by ljf on 2021-01-26
+// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num), num, IP, port, ctx);
+// // 1.创建将要写出的数据
+// // fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
+//// String sendStr = "FEFEFE6880025007000068010243C3B216";
+//// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
+//// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
+//// deviceManageEntityList.get(num).getDataCom(), collectionNum, "1");
+//// ByteBuf buffer = getByteBuf(ctx, sendStr);
+//// // 2.发送数据
+//// ctx.channel().writeAndFlush(buffer);
+//// log.info("客户端再次往服务端发送数据" + num);
// }
- }
-
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- log.info("采集电表-数据读取接收完成: " + receiveStr);
-// 把receiveStr的"null"值去掉
-// a9fec2c71f9002fefefefe6839025007000068810643c3bb446c338d16c2b8
-// A9 FE C2 C7 1F 90 02 FE FE FE FE 68 39 02 50 07 00 00 68 81 06 43 C3 5B 38 6C 33 21 16 F8 12
- if ((receiveStr.length() == 62)) {
-// log.info(receiveStr);
- analysisReceiveOrder485.analysisMeterOrder485(receiveStr,"","",""); // 解析电表
- receiveStr = "";
- num = num + 1;
- Thread.sleep(600);
- if (num > size - 1) {
- num = 0;
- receiveStr = null;
- // 关闭连接
- ctx.close();
-// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
-// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
- } else {
- // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
- if (Constant.WEB_FLAG) {
- log.info("有指令下发退出定时采集DDC参数");
- num = 0;
- // 关闭连接
- receiveStr = null;
- ctx.close();
- } else {
- // 封装发送电表工具方法 update by ljf on 2021-01-26
- SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num), num, IP, port, ctx);
- // 1.创建将要写出的数据
- // fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
-// String sendStr = "FEFEFE6880025007000068010243C3B216";
-// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
-// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
-// deviceManageEntityList.get(num).getDataCom(), collectionNum, "1");
-// ByteBuf buffer = getByteBuf(ctx, sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
-// log.info("客户端再次往服务端发送数据" + num);
- }
- }
- } else if ((receiveStr.length() > 62)) {
- receiveStr = null;
- num = num + 1;
- Thread.sleep(500);
- if (num > size - 1) {
- num = 0;
- receiveStr = null;
- // 关闭连接
- ctx.close();
-// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
-// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
- } else {
- // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
- if (Constant.WEB_FLAG) {
- log.info("有指令下发退出定时采集DDC参数");
- num = 0;
- // 关闭连接
- receiveStr = null;
- ctx.close();
- } else {
- // 封装发送电表工具方法 update by ljf on 2021-01-26
- SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num), num, IP, port, ctx);
- // 1.创建将要写出的数据
- // fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
-// String sendStr = "FEFEFE6880025007000068010243C3B216";
-// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
-// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
-// deviceManageEntityList.get(num).getDataCom(), collectionNum, "1");
-// ByteBuf buffer = getByteBuf(ctx, sendStr);
-// // 2.发送数据
-// ctx.channel().writeAndFlush(buffer);
-// log.info("客户端再次往服务端发送数据" + num);
- }
- }
- }
- ctx.flush();
- }
-
-}
+// }
+// }
+// ctx.flush();
+// }
+//
+//}
diff --git a/user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive.java b/user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive.java
index 6472c5c..b5641ac 100644
--- a/user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive.java
+++ b/user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive.java
@@ -137,7 +137,7 @@ public class SerialPortSendReceive {
if (d==1){
deviceInstallService.updateNotOnline(deviceAddr,deviceType,buildingId,"离线"); //所有设备离线
if (deviceType.equals("热泵")){
- nowDataService.updateRunState(buildingId,deviceAddr,"离线"); //监控界面状态表热泵在线状态
+ nowDataService.updateRunState(buildingId,deviceAddr,"离线", buildingName); //监控界面状态表热泵在线状态
}
}
continue;
@@ -174,11 +174,11 @@ public class SerialPortSendReceive {
if (deviceType.equals("热泵")){
String strState=nowDataService.selectState(buildingId,deviceAddr);
if (strState!=null && strState.equals("离线")){ //采集到数据
- nowDataService.updateRunState(buildingId,deviceAddr,"不运行"); //监控界面状态表热泵在线状态
+ nowDataService.updateRunState(buildingId,deviceAddr,"不运行", buildingName); //监控界面状态表热泵在线状态
}
}
try{
- SerialPortSendReceive2.analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, dataStr, analysisReceiveOrder485, nowDataService);
+ SerialPortSendReceive2.analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, dataStr, analysisReceiveOrder485, nowDataService, buildingName);
}catch (Exception e){
// e.printStackTrace();
Constant.WEB_FLAG=false;//可以采集的状态
diff --git a/user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive2.java b/user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive2.java
index 704a09b..ffe0815 100644
--- a/user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive2.java
+++ b/user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive2.java
@@ -45,9 +45,6 @@ public class SerialPortSendReceive2 {
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
public void serialPortSend(String sort, String thread) {
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = df.format(date);
SerialPort serialPort = null;
CacheUtil cacheUtil = CacheUtil.getInstance();
// if (port.contains(comName)){
@@ -70,8 +67,8 @@ public class SerialPortSendReceive2 {
.filter(value -> value.getThread().equals(thread))
.sorted(Comparator.comparing(DeviceCodeParamEntity::getDataCom))
.collect(Collectors.toList());
- size = deviceManageEntityList.size();
- for (int i = 0; i < size; i++) {
+// size = deviceManageEntityList.size();
+ for (int i = 0; i < deviceManageEntityList.size(); i++) {
//判断网页端是否有操作设备的
if (Constant.WEB_FLAG) {
Constant.FLAG = false;
@@ -125,38 +122,35 @@ public class SerialPortSendReceive2 {
byte[] bytes = SerialTool.readFromPort(serialPort);
if (bytes == null) {
SerialTool.closePort(serialPort);
- Thread.sleep(2000);
+ Thread.sleep(1000);
log.info("串口" + serialPort + "没有数据返回!" + i);
log.info("----------------" + deviceType + "离线,设备号:" + deviceAddr + ",所属楼栋:" + buildingName + "----------------");
Constant.WEB_FLAG = false;//可以采集的状态
- if (i == size - 1) {
- Constant.FLAG = false;
- }
String time1 = deviceInstallService.selectLastDate(deviceType, deviceAddr, buildingId);
Date date1 = new Date();
- String time2 = df.format(date1);
+ String time2 = DateUtil.dateToString(date1, "yyyy-MM-dd HH:mm:ss");;
if (time1 == null) {
- time1 = df.format(date1);
+ time1 = DateUtil.dateToString(date1, "yyyy-MM-dd HH:mm:ss");;
}
int d = ExchangeStringUtil.compareCopyTime(time1, time2);
if (d == 1) {
deviceInstallService.updateNotOnline(deviceAddr, deviceType, buildingId, "离线"); //所有设备离线
if (deviceType.equals("热泵")) {
- nowDataService.updateRunState(buildingId, deviceAddr, "离线"); //监控界面状态表热泵在线状态
+ nowDataService.updateRunState(buildingId, deviceAddr, "离线", buildingName); //监控界面状态表热泵在线状态
}
}
continue;
}
+ String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
// 处理返回来的数据报文
dealReceiveData(dateStr, serialPort, i, deviceAddr, deviceType, registerAddr, brand, buildingId, buildingName, bytes);
}
Constant.FLAG = false;
log.info("-------------一轮采集完,采集标志Constant.Flag=false-------------");
} catch (Exception e) {
- e.printStackTrace();
Constant.WEB_FLAG = false;//可以采集的状态
Constant.FLAG = false;
- log.error("-------------串口采集异常!-------------");
+ log.error("-------------串口采集异常!----------->>", e);
}
}
@@ -184,7 +178,7 @@ public class SerialPortSendReceive2 {
String buildingId,
String buildingName, byte[] bytes) throws InterruptedException {
receiveStr = "";
- receiveStr = printHexString(bytes);
+ receiveStr = ExchangeStringUtil.parseByte2HexStr(bytes);
//去掉空格和null
receiveStr = receiveStr.replace("null", "");
receiveStr = receiveStr.replace(" ", "");
@@ -194,9 +188,6 @@ public class SerialPortSendReceive2 {
log.info("关闭" + serialPort);
} catch (Exception e) {
Constant.WEB_FLAG = false;//可以采集的状态
- if (i == size - 1) {
- Constant.FLAG = false;
- }
log.error("关闭" + serialPort + "失败!", e);
}
//返回值全部变成大写
@@ -215,12 +206,12 @@ public class SerialPortSendReceive2 {
if (deviceType.equals("热泵")) {
String strState = nowDataService.selectState(buildingId, deviceAddr);
if (strState != null && strState.equals("离线")) { //采集到数据
- nowDataService.updateRunState(buildingId, deviceAddr, "不运行"); //监控界面状态表热泵在线状态
+ nowDataService.updateRunState(buildingId, deviceAddr, "不运行", buildingName); //监控界面状态表热泵在线状态
}
}
try {
// 解析返回来的数据
- analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, dataStr, analysisReceiveOrder485, nowDataService);
+ analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, dataStr, analysisReceiveOrder485, nowDataService, buildingName);
} catch (Exception e) {
Constant.WEB_FLAG = false;//可以采集的状态
log.error(deviceManageEntityList.get(i).getDeviceType() + "保存数据库失败!" + i,e);
@@ -228,51 +219,41 @@ public class SerialPortSendReceive2 {
Thread.sleep(1000);
}
- static void analysisReceiveData(String dateStr, String deviceType, String registerAddr, String brand, String buildingId, String dataStr, AnalysisReceiveOrder485 analysisReceiveOrder485, NowDataService nowDataService) {
+ static void analysisReceiveData(String dateStr,
+ String deviceType,
+ String registerAddr,
+ String brand,
+ String buildingId,
+ String dataStr,
+ AnalysisReceiveOrder485 analysisReceiveOrder485,
+ NowDataService nowDataService,
+ String buildingName) {
if ((dataStr.length() == 36 || dataStr.length() == 44 || dataStr.length() == 40 || dataStr.length() == 50) && deviceType.equals("电表")) {
- analysisReceiveOrder485.analysisMeterOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisMeterOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
nowDataService.proWaterLevel(dateStr, buildingId); //保存时间点楼栋水位
} else if ((dataStr.length() == 18 || dataStr.length() == 70 || dataStr.length() == 44) && deviceType.equals("水表")) {
- analysisReceiveOrder485.analysisWtMeterOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisWtMeterOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("压变")) {
- analysisReceiveOrder485.analysisPressureOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisPressureOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("热泵")) {
- analysisReceiveOrder485.analysisPumpOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisPumpOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("温控")) {
- analysisReceiveOrder485.analysisTempOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisTempOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("时控")) {
- analysisReceiveOrder485.analysisTimeSetOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisTimeSetOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) {
- analysisReceiveOrder485.analysisRelayOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisRelayOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (dataStr.length() == 30 && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统
- analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && registerAddr.equals("0010")) {
- analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId); //创新,热泵状态与水位共用一个8路设备
+ analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId, buildingName); //创新,热泵状态与水位共用一个8路设备
// analysisReceiveOrder485.analysisRelayOrder485(dataStr,registerAddr,brand,buildingId); //华厦
nowDataService.proWaterLevel(dateStr, buildingId); //保存时间点楼栋水位
} else if (deviceType.equals("温度变送器")) {
- analysisReceiveOrder485.analysisMulTempOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisMulTempOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("热泵状态")) {
- analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId);
- }
- }
-
- /**
- * 字节数组转16进制字符串
- *
- * @param b 字节数组
- * @return 16进制字符串
- */
- public static String printHexString(byte[] b) {
- StringBuilder sbf = new StringBuilder();
- for (byte value : b) {
- String hex = Integer.toHexString(value & 0xFF);
- if (hex.length() == 1) {
- hex = '0' + hex;
- }
- sbf.append(hex.toUpperCase()).append(" ");
+ analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId, buildingName);
}
- return sbf.toString().trim();
}
/**
diff --git a/user-service/src/main/java/com/mh/user/serialport/SerialPortSingle.java b/user-service/src/main/java/com/mh/user/serialport/SerialPortSingle.java
index 3b34d9c..6122742 100644
--- a/user-service/src/main/java/com/mh/user/serialport/SerialPortSingle.java
+++ b/user-service/src/main/java/com/mh/user/serialport/SerialPortSingle.java
@@ -103,7 +103,7 @@ public class SerialPortSingle {
if (deviceType.equals("热泵")) {
String strState = nowDataService.selectState(buildingId, deviceAddr);
if (strState != null && strState.equals("离线")) { //采集到数据
- nowDataService.updateRunState(buildingId, deviceAddr, "不运行"); //监控界面状态表热泵在线状态
+ nowDataService.updateRunState(buildingId, deviceAddr, "不运行", buildingName); //监控界面状态表热泵在线状态
}
}
try {
@@ -114,7 +114,7 @@ public class SerialPortSingle {
} else if (deviceType.equals("压变")) {
rtData = analysisReceiveOrder485.analysisPressureOrder4852(dataStr, registerAddr, brand, buildingId);
} else if ((dataStr.length() == 30) && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统
- analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId);
+ analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) {
rtData = analysisReceiveOrder485.analysisRelayOrder4852(dataStr, registerAddr, brand, buildingId);
} else if (deviceType.equals("热泵")) {
diff --git a/user-service/src/main/java/com/mh/user/serialport/SerialPortSingle2.java b/user-service/src/main/java/com/mh/user/serialport/SerialPortSingle2.java
index f529a58..811295b 100644
--- a/user-service/src/main/java/com/mh/user/serialport/SerialPortSingle2.java
+++ b/user-service/src/main/java/com/mh/user/serialport/SerialPortSingle2.java
@@ -87,7 +87,7 @@ public class SerialPortSingle2 {
if (deviceType.equals("热泵")){
String strState=nowDataService.selectState(buildingId,deviceAddr);
if (strState!=null && strState.equals("离线")){ //采集到数据
- nowDataService.updateRunState(buildingId,deviceAddr,"不运行"); //监控界面状态表热泵在线状态
+ nowDataService.updateRunState(buildingId,deviceAddr,"不运行", buildingName); //监控界面状态表热泵在线状态
}
}
try{
@@ -98,7 +98,7 @@ public class SerialPortSingle2 {
} else if (deviceType.equals("压变")) {
rtData=analysisReceiveOrder485.analysisPressureOrder4852(dataStr,registerAddr,brand,buildingId);
} else if ((dataStr.length() == 30) && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统
- analysisReceiveOrder485.analysisStateOrder485(dataStr,registerAddr,brand,buildingId);
+ analysisReceiveOrder485.analysisStateOrder485(dataStr,registerAddr,brand,buildingId, buildingName);
} else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) {
rtData=analysisReceiveOrder485.analysisRelayOrder4852(dataStr,registerAddr,brand,buildingId);
} else if (deviceType.equals("热泵")) {
diff --git a/user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java b/user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java
index 9d08947..f368d6c 100644
--- a/user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java
+++ b/user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java
@@ -3,6 +3,8 @@ package com.mh.user.serialport;
import gnu.io.SerialPort;
import lombok.extern.slf4j.Slf4j;
+import java.util.concurrent.CountDownLatch;
+
/**
* @author nxr
* @title :
@@ -19,14 +21,24 @@ public class SerialPortThread implements Runnable{
// 调用service
//ApplicationContext context = SpringBeanUtil.getApplicationContext();
+ private CountDownLatch countDownLatch;
+
public void setName(String name,String thread){
this.name = name;
this.thread=thread;
}
+
+ public void setName(String name,String thread, CountDownLatch countDownLatch){
+ this.name = name;
+ this.thread=thread;
+ this.countDownLatch = countDownLatch;
+ }
+
public void run(){
+ log.info("创建发送接收数据线程>>>>>>>>>>>>>>"+thread);
SerialPortSendReceive2 serial=new SerialPortSendReceive2();
serial.serialPortSend(name,thread);
- log.info("创建发送接收数据线程>>>>>>>>>>>>>>"+thread);
+ this.countDownLatch.countDown();
}
}
diff --git a/user-service/src/main/java/com/mh/user/serialport/SerialTool.java b/user-service/src/main/java/com/mh/user/serialport/SerialTool.java
index b081a25..5cf9bc8 100644
--- a/user-service/src/main/java/com/mh/user/serialport/SerialTool.java
+++ b/user-service/src/main/java/com/mh/user/serialport/SerialTool.java
@@ -172,9 +172,6 @@ public class SerialTool {
out.close();
out = null;
}
-// if (serialPort != null) {
-// serialPort.close();
-// }
} catch (IOException e) {
log.error("关闭串口对象的输出流出错");
throw e;
diff --git a/user-service/src/main/java/com/mh/user/service/NowDataService.java b/user-service/src/main/java/com/mh/user/service/NowDataService.java
index b79904d..d3f8a9d 100644
--- a/user-service/src/main/java/com/mh/user/service/NowDataService.java
+++ b/user-service/src/main/java/com/mh/user/service/NowDataService.java
@@ -103,7 +103,7 @@ public interface NowDataService {
void proWaterLevel(String curDate,String buildingID);
//在没有接收到返回值前设置监控界面热泵是否离线
- void updateRunState(String buildingId,String pumpId,String strState);
+ void updateRunState(String buildingId,String pumpId,String strState, String buildingName);
//计算热泵运行时间,按分钟
void proPumpMinutes(String buildingId,String pumpId,String runState);
diff --git a/user-service/src/main/java/com/mh/user/service/impl/NowDataServiceImpl.java b/user-service/src/main/java/com/mh/user/service/impl/NowDataServiceImpl.java
index eb99c16..3cb7b49 100644
--- a/user-service/src/main/java/com/mh/user/service/impl/NowDataServiceImpl.java
+++ b/user-service/src/main/java/com/mh/user/service/impl/NowDataServiceImpl.java
@@ -447,9 +447,9 @@ public class NowDataServiceImpl implements NowDataService {
}
@Override
- public void updateRunState(String buildingId, String pumpId,String strState) {
+ public void updateRunState(String buildingId, String pumpId,String strState, String buildingName) {
DeviceInstallEntity deviceInstallEntity=deviceInstallMapper.selectDevice(pumpId,"热泵",buildingId);
- String buildingName=buildingService.queryBuildingName(buildingId);
+// String buildingName=buildingService.queryBuildingName(buildingId);
NowDataEntity data=new NowDataEntity();
int r1 = nowDataMapper.selectNowDataCount(buildingId,pumpId);//判断now_data表是否存在记录
if(r1==0){
diff --git a/user-service/src/main/java/com/mh/user/utils/AnalysisReceiveOrder485.java b/user-service/src/main/java/com/mh/user/utils/AnalysisReceiveOrder485.java
index 1c6746f..1b224e7 100644
--- a/user-service/src/main/java/com/mh/user/utils/AnalysisReceiveOrder485.java
+++ b/user-service/src/main/java/com/mh/user/utils/AnalysisReceiveOrder485.java
@@ -34,11 +34,8 @@ public class AnalysisReceiveOrder485 {
* 解析电表返回的数据
* @param dataStr
*/
- public void analysisMeterOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
+ public void analysisMeterOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId, String buildingName) {
+// threadPoolService.execute(() -> {
if (dataStr.length() == 36 || dataStr.length() == 40 || dataStr.length() == 44 || dataStr.length() == 50) {
String checkStr = dataStr.substring(0, dataStr.length() - 4); //减去校验码
String checkNum = ExchangeStringUtil.makeChecksum(checkStr); //生成校验码
@@ -67,25 +64,25 @@ public class AnalysisReceiveOrder485 {
data = String.format("%08d", Long.parseLong(data));
data = data.substring(0, 6) + "." + data.substring(6, 8);
log.info("电表表号:" + meterId+",电表读数:" + data);
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
+// String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
try {
DataResultEntity dataResultEntity = new DataResultEntity();
dataResultEntity.setDeviceAddr(meterId);//通讯编号
dataResultEntity.setDeviceType("电表");
dataResultEntity.setBuildingId(buildingId);
dataResultEntity.setCurValue(Double.parseDouble(data)); //当前读数
- dataResultEntity.setCurDate(sdf1.parse(dateStr)); //当前日期
+ Date date = new Date();
+ dataResultEntity.setCurDate(date); //当前日期
dataResultService.saveDataResult(dataResultEntity);
log.info("电表数据保存数据库成功! 楼栋名称:"+buildingName);
} catch (Exception e) {
- e.printStackTrace();
- log.error("电表数据保存数据库失败!楼栋名称:"+buildingName);
+ log.error("电表数据保存数据库失败!楼栋名称:"+buildingName, e);
}
}else {
log.info("电表报文检验失败: " + dataStr);
}
}
- });
+// });
}
public String analysisMeterOrder4852(final String dataStr,final String registerAddr,final String brand,String buildingId) {
@@ -146,11 +143,8 @@ public class AnalysisReceiveOrder485 {
}
// 水表
- public void analysisWtMeterOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
+ public void analysisWtMeterOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId, String buildingName) {
+// threadPoolService.execute(() -> {
String data = "";
String meterId="";
if (dataStr.length() == 44 || dataStr.length() == 70) {
@@ -189,14 +183,14 @@ public class AnalysisReceiveOrder485 {
log.info("水表报文检验失败: " + dataStr);
}
}
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
log.info("水表表号: " + meterId+",水表读数:" + data);
try {
DataResultEntity dataResultEntity = new DataResultEntity();
dataResultEntity.setDeviceAddr(meterId);//通讯编号
dataResultEntity.setDeviceType("水表");
dataResultEntity.setCurValue(Double.parseDouble(data)); //当前读数
- dataResultEntity.setCurDate(sdf1.parse(dateStr)); //当前日期
+ Date date = new Date();
+ dataResultEntity.setCurDate(date); //当前日期
dataResultEntity.setBuildingId(buildingId);
dataResultService.saveDataResult(dataResultEntity);
log.info("水表数据保存数据库成功!楼栋名称:"+buildingName);
@@ -204,7 +198,7 @@ public class AnalysisReceiveOrder485 {
e.printStackTrace();
log.error("水表数据保存数据库失败!楼栋名称:"+buildingName);
}
- });
+// });
}
// 水表
@@ -276,12 +270,12 @@ public class AnalysisReceiveOrder485 {
}
// 热泵
- public void analysisPumpOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) {
+ public void analysisPumpOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
// if (!Constant.CONTROL_WEB_FLAG) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
+// threadPoolService.execute(() -> {
+// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+// Date date = new Date();
+ String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
String checkStr = receiveData.substring(0, receiveData.length() - 4);//检验报文
String checkWord=ExchangeStringUtil.getStrCRC16(checkStr);//生成校验码
String sValue=null;
@@ -289,7 +283,7 @@ public class AnalysisReceiveOrder485 {
if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
String data = "";
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
+// String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (brand==null || brand.equals("") || brand.equals("美的")){
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {//读
if (registerAddr.equalsIgnoreCase("0641")) { //运行状态
@@ -359,10 +353,11 @@ public class AnalysisReceiveOrder485 {
}
nowDataService.saveNowHistoryData(addr,"热泵",sValue,dataType,buildingId);
log.info("热泵ID:" + addr + ",数据: " + sValue+",保存数据库成功!楼栋名称:"+buildingName);
- }else if (registerAddr.equalsIgnoreCase("0656") || registerAddr.equalsIgnoreCase("065A")
- || registerAddr.equalsIgnoreCase("065E")) { //定时设置值
- sValue = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
}
+// else if (registerAddr.equalsIgnoreCase("0656") || registerAddr.equalsIgnoreCase("065A")
+// || registerAddr.equalsIgnoreCase("065E")) { //定时设置值
+// sValue = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
+// }
} else if (checkStr.substring(2, 4).equalsIgnoreCase("10") ) {
log.info("时间: " + dateStr + ",热泵ID: " + addr + ",操作成功! " );
}
@@ -438,10 +433,11 @@ public class AnalysisReceiveOrder485 {
}
nowDataService.saveNowHistoryData(addr,"热泵",sValue,dataType,buildingId);
log.info("时间: " + dateStr + ",热泵ID: " + addr + ",数据: " + sValue+"保存数据库成功!楼栋名称:"+buildingName);
- }else if (registerAddr.equalsIgnoreCase("0656") || registerAddr.equalsIgnoreCase("065A")
- || registerAddr.equalsIgnoreCase("065E")) { //定时设置值
- sValue = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
}
+// else if (registerAddr.equalsIgnoreCase("0656") || registerAddr.equalsIgnoreCase("065A")
+// || registerAddr.equalsIgnoreCase("065E")) { //定时设置值
+// sValue = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
+// }
} else if (checkStr.substring(2, 4).equalsIgnoreCase("06") ) {
log.info("时间: " + dateStr + ",热泵ID: " + addr + ",操作成功! " );
}
@@ -451,7 +447,7 @@ public class AnalysisReceiveOrder485 {
}else{
log.info("热泵报文检验失败: " + receiveData);
}
- });
+// });
// }
}
@@ -621,66 +617,60 @@ public class AnalysisReceiveOrder485 {
}
// 温度变送器,长度42,读功能03
- public void analysisMulTempOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) {
-// if (!Constant.CONTROL_WEB_FLAG) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
- String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文
- byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
- int checkNum = CRC16.CRC16_MODBUS(strOrder);
- String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
- checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2);
- if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
- //log.info("温度变送器报文检验成功: " + receiveData);
- String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
- //log.info("温度变送器:" + addr);
- String data = "";
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
- if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
- Map map= new HashMap<>();
- String L1=checkStr.substring(6, 10); //1路
- map.put("1",String.valueOf(ExchangeStringUtil.parseHex4(L1)/10));
- String L2=checkStr.substring(10, 14); //2路
- map.put("2",String.valueOf(ExchangeStringUtil.parseHex4(L2)/10));
- String L3=checkStr.substring(14, 18); //3路
- map.put("3",String.valueOf(ExchangeStringUtil.parseHex4(L3)/10));
- String L4=checkStr.substring(18, 22); //4路
- map.put("4",String.valueOf(ExchangeStringUtil.parseHex4(L4)/10));
- String L5=checkStr.substring(22, 26); //5路
- map.put("5",String.valueOf(ExchangeStringUtil.parseHex4(L5)/10));
- String L6=checkStr.substring(26, 30); //6路
- map.put("6",String.valueOf(ExchangeStringUtil.parseHex4(L6)/10));
- String L7=checkStr.substring(30, 34); //7路
- map.put("7",String.valueOf(ExchangeStringUtil.parseHex4(L7)/10));
- String L8=checkStr.substring(34, 38); //8路
- map.put("8",String.valueOf(ExchangeStringUtil.parseHex4(L8)/10));
+ public void analysisMulTempOrder485(final String receiveData, final String registerAddr,final String brand,final String buildingId, final String buildingName) {
+// threadPoolService.execute(() -> {
+ String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文
+ byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
+ int checkNum = CRC16.CRC16_MODBUS(strOrder);
+ String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
+ checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2);
+ if (!checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
+ log.info("温度变送器报文检验失败: " + receiveData);
+ }
+ //log.info("温度变送器报文检验成功: " + receiveData);
+ String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
+ //log.info("温度变送器:" + addr);
+ String data = "";
+ if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
+ Map map= new HashMap<>();
+ String L1=checkStr.substring(6, 10); //1路
+ map.put("1",String.valueOf(ExchangeStringUtil.parseHex4(L1)/10));
+ String L2=checkStr.substring(10, 14); //2路
+ map.put("2",String.valueOf(ExchangeStringUtil.parseHex4(L2)/10));
+ String L3=checkStr.substring(14, 18); //3路
+ map.put("3",String.valueOf(ExchangeStringUtil.parseHex4(L3)/10));
+ String L4=checkStr.substring(18, 22); //4路
+ map.put("4",String.valueOf(ExchangeStringUtil.parseHex4(L4)/10));
+ String L5=checkStr.substring(22, 26); //5路
+ map.put("5",String.valueOf(ExchangeStringUtil.parseHex4(L5)/10));
+ String L6=checkStr.substring(26, 30); //6路
+ map.put("6",String.valueOf(ExchangeStringUtil.parseHex4(L6)/10));
+ String L7=checkStr.substring(30, 34); //7路
+ map.put("7",String.valueOf(ExchangeStringUtil.parseHex4(L7)/10));
+ String L8=checkStr.substring(34, 38); //8路
+ map.put("8",String.valueOf(ExchangeStringUtil.parseHex4(L8)/10));
- int count=buildingService.selectPumpCount(buildingId); //楼栋热泵数
- if (count>0){
- for (Map.Entry entry : map.entrySet()) {
- addr=entry.getKey();
- data=entry.getValue();
- if(addr!=null && Integer.valueOf(addr)<=count){
- nowDataService.saveNowHistoryData3(addr,"温度变送器",data,"waterTemp",buildingId);
- nowDataService.proWaterTemp(dateStr,buildingId,addr); //保存时间点温度
- }
- }
- log.info("温度变送器:" + addr+",保存数据库成功!楼栋名称:"+buildingName);
- String avgTemp=nowDataService.selectAve(buildingId);
- NowPublicDataEntity publicData=new NowPublicDataEntity();
- publicData.setBuildingId(buildingId);
- publicData.setUseWaterTemp(avgTemp);
- publicData.setBackWaterTemp(avgTemp);
- nowPublicDataService.saveNowHistoryPublicData(publicData);
+ int count=buildingService.selectPumpCount(buildingId); //楼栋热泵数
+ if (count>0){
+ String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
+ for (Map.Entry entry : map.entrySet()) {
+ addr=entry.getKey();
+ data=entry.getValue();
+ if(addr!=null && Integer.parseInt(addr)<=count){
+ nowDataService.saveNowHistoryData3(addr,"温度变送器",data,"waterTemp",buildingId);
+ nowDataService.proWaterTemp(dateStr,buildingId,addr); //保存时间点温度
}
}
- }else{
- log.info("温度变送器报文检验失败: " + receiveData);
+ log.info("温度变送器:" + addr+",保存数据库成功!楼栋名称:"+buildingName);
+ String avgTemp=nowDataService.selectAve(buildingId);
+ NowPublicDataEntity publicData=new NowPublicDataEntity();
+ publicData.setBuildingId(buildingId);
+ publicData.setUseWaterTemp(avgTemp);
+ publicData.setBackWaterTemp(avgTemp);
+ nowPublicDataService.saveNowHistoryPublicData(publicData);
}
- });
-// }
+ }
+// });
}
// 温度变送器,长度42,读功能03
@@ -745,53 +735,46 @@ public class AnalysisReceiveOrder485 {
}
// 温控,长度18,读功能03,用于检测水箱水温
- public void analysisTempOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) {
-// if (!Constant.CONTROL_WEB_FLAG) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
+ public void analysisTempOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
+// threadPoolService.execute(() -> {
// 检验报文
String checkStr = receiveData.substring(0, receiveData.length() - 4);
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
int checkNum = CRC16.CRC16_MODBUS(strOrder);
String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2);
- if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
- String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
- //log.info("温控号:" + addr);
- String data = "";
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
- if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
- data=ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
- Double fdata=Double.parseDouble(data)/10;
- if (fdata<=25){
- fdata=25.0;
- }else if (fdata>=65){
- fdata=65.0;
- }
- nowDataService.saveNowHistoryData2(addr,"温控",String.valueOf(fdata),"waterTemp",buildingId);
- nowDataService.proWaterTemp(dateStr,buildingId,"");//保存时间点温度
- String avgTemp=nowDataService.selectAve(buildingId);
- NowPublicDataEntity publicData=new NowPublicDataEntity();
- publicData.setBuildingId(buildingId);
- publicData.setUseWaterTemp(avgTemp);
- publicData.setBackWaterTemp(avgTemp);
- publicData.setSingleTemp(String.valueOf(fdata));//单箱温度
- nowPublicDataService.saveNowHistoryPublicData(publicData);
- log.info("温控号:" + addr+",温度值:"+fdata+",保存数据库成功!楼栋名称:"+buildingName);
- }
- }else{
+ if (!checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
log.info("温控报文检验失败: " + receiveData);
}
- });
-// }
+ String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
+ String data = "";
+ if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
+ data=ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
+ Double fdata=Double.parseDouble(data)/10;
+ if (fdata<=25){
+ fdata=25.0;
+ }else if (fdata>=65){
+ fdata=65.0;
+ }
+ nowDataService.saveNowHistoryData2(addr,"温控",String.valueOf(fdata),"waterTemp",buildingId);
+ String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
+ nowDataService.proWaterTemp(dateStr,buildingId,"");//保存时间点温度
+ String avgTemp=nowDataService.selectAve(buildingId);
+ NowPublicDataEntity publicData=new NowPublicDataEntity();
+ publicData.setBuildingId(buildingId);
+ publicData.setUseWaterTemp(avgTemp);
+ publicData.setBackWaterTemp(avgTemp);
+ publicData.setSingleTemp(String.valueOf(fdata));//单箱温度
+ nowPublicDataService.saveNowHistoryPublicData(publicData);
+ log.info("温控号:" + addr+",温度值:"+fdata+",保存数据库成功!楼栋名称:"+buildingName);
+ }
+// });
}
// 压变,长度14,18读功能03
- public void analysisPressureOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) {
+ public void analysisPressureOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
// if (!Constant.CONTROL_WEB_FLAG) {
- threadPoolService.execute(() -> {
+// threadPoolService.execute(() -> {
String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
int checkNum = CRC16.CRC16_MODBUS(strOrder);
@@ -804,7 +787,7 @@ public class AnalysisReceiveOrder485 {
String dateStr = sdf1.format(date);
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
String data = "";
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
+// String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
Double wtHeight=0.0;
if (brand==null || brand.equals("")){
@@ -835,7 +818,7 @@ public class AnalysisReceiveOrder485 {
}else{
log.info("压变报文检验失败: " + receiveData);
}
- });
+// });
// }
}
@@ -890,11 +873,9 @@ public class AnalysisReceiveOrder485 {
}
// 水位开关,长度42,128
- public void analysisRelayOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
+ public void analysisRelayOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
+// threadPoolService.execute(() -> {
+ String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
String l1="";
String l2="";
String l3="";
@@ -905,7 +886,6 @@ public class AnalysisReceiveOrder485 {
String l8="";
String waterLevelSet="";
String addr="";
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (brand==null || brand.equals("") || brand.equals("中凯")){
String checkStr = receiveData.substring(0, receiveData.length() - 4); //减去校验码
addr = ExchangeStringUtil.hexToDec(checkStr.substring(2, 4));
@@ -1039,7 +1019,7 @@ public class AnalysisReceiveOrder485 {
log.info("-----------------状态保存数据库成功!楼栋名称:"+buildingName+"-----------------");
}
}
- });
+// });
}
// 水位开关,长度42,128
@@ -1178,11 +1158,9 @@ public class AnalysisReceiveOrder485 {
}
// 热泵状态处理(水位开关),长度42,128
- public void analysisPumpStateOrder(final String receiveData, final String registerAddr,final String brand,String buildingId) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
+ public void analysisPumpStateOrder(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
+// threadPoolService.execute(() -> {
+ String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
String l1="";
String l2="";
String l3="";
@@ -1194,7 +1172,6 @@ public class AnalysisReceiveOrder485 {
String runState="";
String addr="";
Map map=new HashMap();
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (brand==null || brand.equals("") || brand.equals("顶威")){
String checkStr = receiveData.substring(0, receiveData.length() - 4); //检验报文减,去校验码
String checkNum = ExchangeStringUtil.makeChecksum(checkStr); //生成校验码
@@ -1354,7 +1331,7 @@ public class AnalysisReceiveOrder485 {
}
//}
//}
- });
+// });
}
// 热泵状态处理(水位开关),长度42,128
@@ -1538,12 +1515,8 @@ public class AnalysisReceiveOrder485 {
}
//状态检测
- public void analysisStateOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
- String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
+ public void analysisStateOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId, String buildingName) {
+// threadPoolService.execute(() -> {
if (dataStr.length() == 30) {
//检验报文
String checkStr = dataStr.substring(0, dataStr.length() - 4); //减去校验码
@@ -1601,56 +1574,51 @@ public class AnalysisReceiveOrder485 {
log.info("状态检测报文检验失败: " + dataStr);
}
}
- });
+// });
}
//时间控制器,长度26、22
- public void analysisTimeSetOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) {
-// if (!Constant.CONTROL_WEB_FLAG) {
- threadPoolService.execute(() -> {
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date = new Date();
- String dateStr = sdf1.format(date);
- // 去掉空格
-// String receiveData = receiveData1.replace(" ", "");
- // 检验报文
- String checkStr = receiveData.substring(0, receiveData.length() - 4);
- byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
- int checkNum = CRC16.CRC16_MODBUS(strOrder);
- String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
- checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2);
+ public void analysisTimeSetOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
+// threadPoolService.execute(() -> {
+ SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ Date date = new Date();
+ String dateStr = sdf1.format(date);
+ // 检验报文
+ String checkStr = receiveData.substring(0, receiveData.length() - 4);
+ byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
+ int checkNum = CRC16.CRC16_MODBUS(strOrder);
+ String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
+ checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2);
- String sValue=null;
- if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
- log.info("时控报文检验成功: " + receiveData);
-// System.out.println("时控报文检验成功: " + receiveData);
- //地址
- String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));
- log.info("时控号: " + addr);
+ String sValue=null;
+ if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
+ log.info("时控报文检验成功: " + receiveData);
+ //地址
+ String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));
+ log.info("时控号: " + addr);
// System.out.println("时控号: " + addr);
- String data = "";
- if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
- int rec=receiveData.length();
+ String data = "";
+ if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
+ int rec=receiveData.length();
- if (rec==26) { //读时间设置值
- data=checkStr.substring(6,rec-4);
- String curTimeBegin1=data.substring(0,2)+":"+data.substring(2,4);
- String curTimeEnd1=data.substring(4,6)+":"+data.substring(6,8);
- String curTimeBegin2=data.substring(8,10)+":"+data.substring(10,12);
- String curTimeEnd2=data.substring(12,14)+":"+data.substring(14,16);
+ if (rec==26) { //读时间设置值
+ data=checkStr.substring(6,rec-4);
+ String curTimeBegin1=data.substring(0,2)+":"+data.substring(2,4);
+ String curTimeEnd1=data.substring(4,6)+":"+data.substring(6,8);
+ String curTimeBegin2=data.substring(8,10)+":"+data.substring(10,12);
+ String curTimeEnd2=data.substring(12,14)+":"+data.substring(14,16);
- }else if (rec==22){ //读校对时间
- data=checkStr.substring(8,rec-4);
- String strDate="20"+data.substring(0,2)+"-"+data.substring(2,4)+"-"+data.substring(4,6); //拼接日期
- String strTime=data.substring(6,8)+":"+data.substring(8,10); //拼接时间
- }
- } else if (checkStr.substring(2, 4).equalsIgnoreCase("05") || checkStr.substring(2, 4).equalsIgnoreCase("10")) {
- log.info("时间: " + dateStr + ",时控ID: " + addr + ",操作成功! " );
-// System.out.println("时间: " + dateStr + ",时控ID: " + addr + ",操作成功! ");
+ }else if (rec==22){ //读校对时间
+ data=checkStr.substring(8,rec-4);
+ String strDate="20"+data.substring(0,2)+"-"+data.substring(2,4)+"-"+data.substring(4,6); //拼接日期
+ String strTime=data.substring(6,8)+":"+data.substring(8,10); //拼接时间
}
+ } else if (checkStr.substring(2, 4).equalsIgnoreCase("05") || checkStr.substring(2, 4).equalsIgnoreCase("10")) {
+ log.info("时间: " + dateStr + ",时控ID: " + addr + ",操作成功! " );
+// System.out.println("时间: " + dateStr + ",时控ID: " + addr + ",操作成功! ");
}
- });
-// }
+ }
+// });
}
//时间控制器,长度26、22
diff --git a/user-service/src/main/java/com/mh/user/utils/ComThreadPoolService.java b/user-service/src/main/java/com/mh/user/utils/ComThreadPoolService.java
index 9bc05ac..5c37ea4 100644
--- a/user-service/src/main/java/com/mh/user/utils/ComThreadPoolService.java
+++ b/user-service/src/main/java/com/mh/user/utils/ComThreadPoolService.java
@@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit;
public class ComThreadPoolService {
/** 线程池保持ALIVE状态线程数 */
- public static final int CORE_POOL_SIZE = 10;
+ public static final int CORE_POOL_SIZE = 11;
/** 线程池最大线程数 */
public static final int MAX_POOL_SIZE = 50;
@@ -23,7 +23,7 @@ public class ComThreadPoolService {
public static final int KEEP_ALIVE_TIME = 30000;
/** 线程池等待队列 */
- public static final int BLOCKING_QUEUE_SIZE = 1000;
+ public static final int BLOCKING_QUEUE_SIZE = 500;
// 私有化构造器
private ComThreadPoolService(){}
diff --git a/user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java b/user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java
index da5d999..447e86f 100644
--- a/user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java
+++ b/user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java
@@ -1,8 +1,8 @@
package com.mh.user.utils;
import com.mh.common.utils.StringUtils;
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
+//import io.netty.buffer.ByteBuf;
+//import io.netty.channel.ChannelHandlerContext;
import java.io.*;
import java.math.BigInteger;
import java.nio.ByteBuffer;
@@ -81,22 +81,22 @@ public class ExchangeStringUtil {
return c - '0';
}
- /**
- * 获取到对应的buffer
- * @param ctx
- * @param sendStr
- * @return
- */
- public static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
- // byte类型的数据
-// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
-// String sendStr = "5803004900021914"; // 冷量计
- // 申请一个数据结构存储信息
- ByteBuf buffer = ctx.alloc().buffer();
- // 将信息放入数据结构中
- buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
- return buffer;
- }
+// /**
+// * 获取到对应的buffer
+// * @param ctx
+// * @param sendStr
+// * @return
+// */
+// public static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
+// // byte类型的数据
+//// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
+//// String sendStr = "5803004900021914"; // 冷量计
+// // 申请一个数据结构存储信息
+// ByteBuf buffer = ctx.alloc().buffer();
+// // 将信息放入数据结构中
+// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
+// return buffer;
+// }
/**
* double转换为String :当为整数时,只显示整数,当小数时直接显示小数
@@ -992,16 +992,16 @@ public class ExchangeStringUtil {
}
//将二进字节数组制转换为十六进制
- public static String parseByte2HexStr(byte binary[]){
+ public static String parseByte2HexStr(byte[] binary){
StringBuffer sb = new StringBuffer();
- for(int i = 0; i < binary.length; i++){
- String hex = Integer.toHexString(binary[i] & 0xFF);
+ for (byte b : binary) {
+ String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
- return sb.toString();
+ return sb.toString().trim();
}
/**
* 十六进制字符串转IEEE754浮点型
diff --git a/user-service/src/main/java/com/mh/user/utils/GetReadOrder485.java b/user-service/src/main/java/com/mh/user/utils/GetReadOrder485.java
index cca0377..55d15b0 100644
--- a/user-service/src/main/java/com/mh/user/utils/GetReadOrder485.java
+++ b/user-service/src/main/java/com/mh/user/utils/GetReadOrder485.java
@@ -28,7 +28,7 @@ public class GetReadOrder485 {
// 电表
public static String createMeterOrder(DeviceCodeParamEntity orderParamModel){
- String str=null;
+ String str="";
String deviceAddr=orderParamModel.getDeviceAddr();
if (deviceAddr!=null && deviceAddr.length()>0){
try{
@@ -45,10 +45,9 @@ public class GetReadOrder485 {
String checkSum = ExchangeStringUtil.makeChecksum(str);
str = "FEFEFE" + str + checkSum + "16";
}catch (Exception e){
- e.printStackTrace();
+ log.error("生成采集电表指令错误==>",e);
}
}
-// log.info("发送电表采集数据>>>>" + str);
return str.toUpperCase();
}
@@ -56,7 +55,7 @@ public class GetReadOrder485 {
public static String createWtMeterOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr();
String brand=orderParamModel.getBrand();
- String str=null;
+ String str="";
if(deviceAddr!=null && deviceAddr.length()>0){
try{
if (brand==null || brand.equals("") || brand.equals("艾美柯")){
@@ -78,9 +77,9 @@ public class GetReadOrder485 {
}
}catch (Exception e){
e.printStackTrace();
+ log.error("生成水表采集指令异常>>>>", e);
}
}
-// log.info("生成水表采集指令>>>>" + str);
return str.toUpperCase();
}
@@ -91,7 +90,7 @@ public class GetReadOrder485 {
String funCode=orderParamModel.getFunCode();
String registerAddr=orderParamModel.getRegisterAddr();
String dataValue=orderParamModel.getDataValue();
- String str=null;
+ String str="";
String param="";
if(deviceAddr!=null && deviceAddr.length()>0) {
try{
@@ -164,7 +163,7 @@ public class GetReadOrder485 {
String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验
str = str + checkWord;
}catch (Exception e){
- e.printStackTrace();
+ log.info("热泵"+param+"指令>>>>异常" + str, e);
}
}
log.info("热泵"+param+"指令>>>>" + str);
@@ -178,7 +177,7 @@ public class GetReadOrder485 {
String funCode=orderParamModel.getFunCode();
String registerAddr=orderParamModel.getRegisterAddr();
String dataValue=orderParamModel.getDataValue();
- String str=null;
+ String str="";
if(deviceAddr!=null && deviceAddr.length()>0){
try{
if (brand==null || brand.equals("") || brand.equals("中凯"))
@@ -299,9 +298,9 @@ public class GetReadOrder485 {
}catch (Exception e){
// e.printStackTrace();
if(registerAddr.equals("0010")){
- log.info("生成热泵状态指令出错!" + str);
+ log.error("生成热泵状态指令出错!" + str);
}else{
- log.info("生成水位开关指令出错!" + str);
+ log.error("生成水位开关指令出错!" + str);
}
}
}
@@ -319,7 +318,7 @@ public class GetReadOrder485 {
String brand=orderParamModel.getBrand();
String funCode=orderParamModel.getFunCode();
String registerAddr=orderParamModel.getRegisterAddr();
- String str=null;
+ String str="";
if(deviceAddr!=null && deviceAddr.length()>0){
try{
if (brand==null || brand.equals("") || brand.equals("中凯"))
@@ -361,7 +360,7 @@ public class GetReadOrder485 {
}
}catch (Exception e){
// e.printStackTrace();
- log.info("生成热泵状态指令出错!" + str);
+ log.error("生成热泵状态指令出错!" + str, e);
}
}
log.info("生成热泵状态采集指令>>>>" + str);
@@ -372,7 +371,7 @@ public class GetReadOrder485 {
public static String createStateOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr();
String brand=orderParamModel.getBrand();
- String str=null;
+ String str="";
if(deviceAddr!=null && deviceAddr.length()>0){
try{
// 0代表前面补充0,12代表长度为12,d代表参数为正数型.12位通讯地址,以0补位
@@ -390,10 +389,9 @@ public class GetReadOrder485 {
}catch (Exception e){
// e.printStackTrace();
- log.info("生成状态检测指令出错!" + str);
+ log.error("生成状态检测指令出错!" + str,e);
}
}
-// log.info("生成状态检测采集指令>>>>" + str);
return str.toUpperCase();
}
@@ -401,7 +399,7 @@ public class GetReadOrder485 {
public static String createPressureOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr();
String brand=orderParamModel.getBrand();
- String str=null;
+ String str="";
if(deviceAddr!=null && deviceAddr.length()>0){
try{
str = ExchangeStringUtil.decToHex(deviceAddr); //十进制转为十六进制
@@ -416,11 +414,9 @@ public class GetReadOrder485 {
String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验
str = str + checkWord;
}catch (Exception e){
-// e.printStackTrace();
- log.info("生成压变指令出错!" + str);
+ log.info("生成压变指令出错!" + str, e);
}
}
-// log.info("生成压变采集指令>>>>" + str);
return str.toUpperCase();
}
@@ -428,7 +424,7 @@ public class GetReadOrder485 {
public static String createTempOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr();
String registerAddr=orderParamModel.getRegisterAddr();
- String str=null;
+ String str="";
if(deviceAddr!=null && deviceAddr.length()>0){
try{
str = ExchangeStringUtil.decToHex(deviceAddr);
@@ -443,11 +439,9 @@ public class GetReadOrder485 {
str = str + checkWord;
}catch (Exception e){
// e.printStackTrace();
- log.info("生成温控指令出错!" + str);
+ log.error("生成温控指令出错!" + str, e);
}
}
-// log.info("生成温控采集指令>>>>" + str);
-// System.out.println("生成温控采集指令>>>>" + str);
return str.toUpperCase();
}
@@ -455,7 +449,7 @@ public class GetReadOrder485 {
public static String createMulTempOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr();
String registerAddr=orderParamModel.getRegisterAddr();
- String str=null;
+ String str="";
if(deviceAddr!=null && deviceAddr.length()>0){
try{
str = ExchangeStringUtil.decToHex(deviceAddr);
@@ -464,11 +458,9 @@ public class GetReadOrder485 {
String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验
str = str + checkWord;
}catch (Exception e){
-// e.printStackTrace();
- log.info("生成多路温度变送器指令出错!" + str);
+ log.info("生成多路温度变送器指令出错!" + str, e);
}
}
-// log.info("生成多路温度变送器采集指令>>>>" + str);
return str.toUpperCase();
}
@@ -479,7 +471,7 @@ public class GetReadOrder485 {
String funCode=orderParamModel.getFunCode();
String registerAddr=orderParamModel.getRegisterAddr();
String dataValue=orderParamModel.getDataValue();
- String str=null;
+ String str="";
if(deviceAddr!=null && deviceAddr.length()>0){
str = ExchangeStringUtil.decToHex(deviceAddr);
str = ExchangeStringUtil.addZeroForNum(str, 2); //以0补位
@@ -501,11 +493,9 @@ public class GetReadOrder485 {
str = str + checkWord;
// }
}catch (Exception e){
-// e.printStackTrace();
- log.info("生成时控指令出错!" + str);
+ log.error("生成时控指令出错!" + str, e);
}
}
-// log.info("发送时控采集数据>>>>" + str);
return str.toUpperCase();
}
diff --git a/user-service/src/main/java/com/mh/user/utils/SendOrderUtils.java b/user-service/src/main/java/com/mh/user/utils/SendOrderUtils.java
index 1bead1f..6700cdb 100644
--- a/user-service/src/main/java/com/mh/user/utils/SendOrderUtils.java
+++ b/user-service/src/main/java/com/mh/user/utils/SendOrderUtils.java
@@ -1,16 +1,9 @@
package com.mh.user.utils;
-import com.mh.user.entity.ChillersEntity;
import com.mh.user.entity.DeviceCodeParamEntity;
-import com.mh.user.entity.DeviceManageEntity;
-import com.mh.user.model.OrderParamModel;
import com.mh.user.serialport.SerialPortListener;
import com.mh.user.serialport.SerialPortUtil;
-import com.mh.user.serialport.SerialTool;
-//import purejavacomm.SerialPort;
import gnu.io.SerialPort;
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
/**
@@ -23,80 +16,80 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SendOrderUtils {
- /**
- * 发送采集冷水机组
- * @param chillersEntity
- * @param ctx
- * @param num
- * @param size
- */
- public static void sendChillersOrder(ChillersEntity chillersEntity, ChannelHandlerContext ctx, int num, int size) {
- // 继续发送下一个采集冷水机设备指令
- GetReadOrder485 getReadOrder485 = new GetReadOrder485();
- String sendStr = getReadOrder485.createChillersOrder(chillersEntity);
- ByteBuf buffer = getByteBuf(ctx, sendStr);
- // 2.发送数据
- ctx.channel().writeAndFlush(buffer);
- log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
- }
-
- public static void sendMeterOrCloud(DeviceManageEntity deviceManageEntity,
- int num,
- String IP,
- String port,
- ChannelHandlerContext ctx) {
- if (deviceManageEntity.getParamId() == 1) {
- sendMeterOrder(deviceManageEntity, num, IP, port, ctx);
- } else if (deviceManageEntity.getParamId() == 3) {
- sendCloudOrder(deviceManageEntity, num, IP, port, ctx);
- }
- }
- /**
- * 发送采集电表
- * @param deviceManageEntity
- * @param num
- * @param IP
- * @param port
- * @param ctx
- */
- public static void sendMeterOrder(DeviceManageEntity deviceManageEntity,
- int num,
- String IP,
- String port,
- ChannelHandlerContext ctx) {
+// /**
+// * 发送采集冷水机组
+// * @param chillersEntity
+// * @param ctx
+// * @param num
+// * @param size
+// */
+// public static void sendChillersOrder(ChillersEntity chillersEntity, ChannelHandlerContext ctx, int num, int size) {
+// // 继续发送下一个采集冷水机设备指令
+// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
+// String sendStr = getReadOrder485.createChillersOrder(chillersEntity);
+// ByteBuf buffer = getByteBuf(ctx, sendStr);
+// // 2.发送数据
+// ctx.channel().writeAndFlush(buffer);
+// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
+// }
+//
+// public static void sendMeterOrCloud(DeviceManageEntity deviceManageEntity,
+// int num,
+// String IP,
+// String port,
+// ChannelHandlerContext ctx) {
+// if (deviceManageEntity.getParamId() == 1) {
+// sendMeterOrder(deviceManageEntity, num, IP, port, ctx);
+// } else if (deviceManageEntity.getParamId() == 3) {
+// sendCloudOrder(deviceManageEntity, num, IP, port, ctx);
+// }
+// }
+// /**
+// * 发送采集电表
+// * @param deviceManageEntity
+// * @param num
+// * @param IP
+// * @param port
+// * @param ctx
+// */
+// public static void sendMeterOrder(DeviceManageEntity deviceManageEntity,
+// int num,
+// String IP,
+// String port,
+// ChannelHandlerContext ctx) {
+//// String collectionNum = deviceManageEntity.getCollectionNum();
+//// String sendStr = GetReadOrder485.createMeterOrder();
+// String sendStr="";
+// ByteBuf buffer = getByteBuf(ctx, sendStr);
+// // 2.发送数据
+// ctx.channel().writeAndFlush(buffer);
+// log.info("客户端再次往服务端发送数据" + num);
+// }
+//
+// /**
+// * 发送采集冷量计工具类
+// * @param deviceManageEntity
+// * @param num
+// * @param IP
+// * @param port
+// * @param ctx
+// */
+// public static void sendCloudOrder(DeviceManageEntity deviceManageEntity,
+// int num,
+// String IP,
+// String port,
+// ChannelHandlerContext ctx) {
+// // 1.创建将要写出的数据
// String collectionNum = deviceManageEntity.getCollectionNum();
-// String sendStr = GetReadOrder485.createMeterOrder();
- String sendStr="";
- ByteBuf buffer = getByteBuf(ctx, sendStr);
- // 2.发送数据
- ctx.channel().writeAndFlush(buffer);
- log.info("客户端再次往服务端发送数据" + num);
- }
-
- /**
- * 发送采集冷量计工具类
- * @param deviceManageEntity
- * @param num
- * @param IP
- * @param port
- * @param ctx
- */
- public static void sendCloudOrder(DeviceManageEntity deviceManageEntity,
- int num,
- String IP,
- String port,
- ChannelHandlerContext ctx) {
- // 1.创建将要写出的数据
- String collectionNum = deviceManageEntity.getCollectionNum();
- String sendStr = GetReadOrder485.createCloudOrder(IP, port,
- deviceManageEntity.getDataCom(),
- collectionNum, "34");
-// String sendStr = "5803004900021914";
- ByteBuf buffer = getByteBuf(ctx, sendStr);
- // 2.发送数据
- ctx.channel().writeAndFlush(buffer);
- log.info("客户端再次往服务端发送数据" + sendStr);
- }
+// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
+// deviceManageEntity.getDataCom(),
+// collectionNum, "34");
+//// String sendStr = "5803004900021914";
+// ByteBuf buffer = getByteBuf(ctx, sendStr);
+// // 2.发送数据
+// ctx.channel().writeAndFlush(buffer);
+// log.info("客户端再次往服务端发送数据" + sendStr);
+// }
//向串口发指令数据
public static void sendSerialPort(DeviceCodeParamEntity deviceCodeParamEntity,SerialPort serialPort ) {
@@ -165,7 +158,6 @@ public class SendOrderUtils {
// orderParamModel.setDataValue(deviceCodeParamEntity.getDataValue());//传入数据
String deviceType=deviceCodeParamEntity.getDeviceType();
- String registerAddr=deviceCodeParamEntity.getRegisterAddr();
String sendStr=null;
switch (deviceType) {
case "电表":
@@ -205,11 +197,11 @@ public class SendOrderUtils {
- private static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
- // 申请一个数据结构存储信息
- ByteBuf buffer = ctx.alloc().buffer();
- // 将信息放入数据结构中
- buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
- return buffer;
- }
+// private static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
+// // 申请一个数据结构存储信息
+// ByteBuf buffer = ctx.alloc().buffer();
+// // 将信息放入数据结构中
+// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
+// return buffer;
+// }
}
diff --git a/user-service/src/main/java/com/mh/user/utils/ThreadPoolService.java b/user-service/src/main/java/com/mh/user/utils/ThreadPoolService.java
index f92e2dd..c115a31 100644
--- a/user-service/src/main/java/com/mh/user/utils/ThreadPoolService.java
+++ b/user-service/src/main/java/com/mh/user/utils/ThreadPoolService.java
@@ -12,16 +12,16 @@ import java.util.concurrent.*;
public class ThreadPoolService {
/** 线程池保持ALIVE状态线程数 */
- public static final int CORE_POOL_SIZE = 10;
+ public static final int CORE_POOL_SIZE = 5;
/** 线程池最大线程数 */
- public static final int MAX_POOL_SIZE = 50;
+ public static final int MAX_POOL_SIZE = 10;
/** 空闲线程回收时间 */
public static final int KEEP_ALIVE_TIME = 30000;
/** 线程池等待队列 */
- public static final int BLOCKING_QUEUE_SIZE = 1000;
+ public static final int BLOCKING_QUEUE_SIZE = 100;
// 私有化构造器
private ThreadPoolService(){}
diff --git a/user-service/src/main/resources/application-prod.yml b/user-service/src/main/resources/application-prod.yml
index 6ea6edf..e37e54e 100644
--- a/user-service/src/main/resources/application-prod.yml
+++ b/user-service/src/main/resources/application-prod.yml
@@ -1,6 +1,8 @@
server:
- port: 8761 #8761创新、8762广商、8763华厦、广州理工
+ port: 8763 #8761创新、8762广商、8763华厦、广州理工
spring:
+ application:
+ name: user-service
datasource:
name: druidDataSource
type: com.alibaba.druid.pool.DruidDataSource
@@ -12,20 +14,20 @@ spring:
# password: mh@803
## url: jdbc:sqlserver://120.25.220.177:32012;DatabaseName=M_CHWS;allowMultiQueries=true
#阿里云服务器-广州理工
- # url: jdbc:sqlserver://120.25.220.177:32012;DatabaseName=CHWS;allowMultiQueries=true
- # driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
- # username: test
- # password: minghan123456@
+ url: jdbc:sqlserver://120.25.220.177:32012;DatabaseName=CHWS;allowMultiQueries=true
+ driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
+ username: test
+ password: minghan123456@
#华厦云服务器
# url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=CHWS;allowMultiQueries=true
# driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
# username: chws
# password: minghan123456@
#创新服务器
- url: jdbc:sqlserver://119.29.33.133:2008;DatabaseName=chws_chx;allowMultiQueries=true
- driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
- username: chws
- password: mh@803
+# url: jdbc:sqlserver://119.29.33.133:2008;DatabaseName=chws_chx;allowMultiQueries=true
+# driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
+# username: chws
+# password: mh@803
#广商服务器
# url: jdbc:sqlserver://119.29.33.133:2008;DatabaseName=chws_gsh;allowMultiQueries=true
# driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
@@ -88,8 +90,6 @@ spring:
# port: 8500
# discovery:
# service-name: ${spring.application.name}
-# application:
-# name: user-service
# 开放健康检查接口
#management:
# endpoints:
@@ -102,22 +102,15 @@ spring:
#files:
# path: ${file-path:d:/files}
-log:
- level:
- root: info
- my: debug
- file:
- maxsize: 30MB
-
-#设置将SQL语句打印到控制台 level后面是 mybatis接口目录
logging:
- # level:
- # com:
- # mh:
- # user:
- # mapper: DEBUG
+ level:
+ com:
+ mh:
+ user:
+ mapper: DEBUG
file:
max-size: 30
+ path: logs/${spring.application.name}
##软件最后更新日期20230111
diff --git a/user-service/src/test/java/com/mh/user/UserServiceApplicationTests.java b/user-service/src/test/java/com/mh/user/UserServiceApplicationTests.java
index f4b6098..fa5edbd 100644
--- a/user-service/src/test/java/com/mh/user/UserServiceApplicationTests.java
+++ b/user-service/src/test/java/com/mh/user/UserServiceApplicationTests.java
@@ -2,17 +2,17 @@ package com.mh.user;
import com.mh.user.entity.DeviceManageEntity;
import com.mh.user.entity.GaugeEntity;
+import com.mh.user.serialport.SerialPortThread;
import com.mh.user.service.DeviceManageService;
import com.mh.user.service.GaugeService;
-import com.mh.user.utils.AnalysisReceiveOrder485;
-import com.mh.user.utils.GetReadOrder485;
-import com.mh.user.utils.PasswordEncoder;
-import com.mh.user.utils.PasswordUtils;
+import com.mh.user.utils.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ThreadPoolExecutor;
@SpringBootTest
class UserServiceApplicationTests {
@@ -59,7 +59,37 @@ class UserServiceApplicationTests {
// getReadOrder485.createOrderParam();
// analysis.analysisRelayOrder485("220611000000013A220611000000023B220611000000033C220611000000043D220611000000053E220611000000063F22061100000007402206110000000841","0017","中凯");
}
-
-
+ @Test
+ public void testHotWater() throws InterruptedException {
+ while (true) {
+ ThreadPoolExecutor comThreadPool = ComThreadPoolService.getInstance();
+ try {
+ for (int i = 1; i <= 4; i++) {
+ String threadName;
+ if (i == 1 || i == 3) {
+ threadName = "1";
+ System.out.println("------采集水位、水温!" + i + "------");
+ } else if (i == 2) {
+ threadName = "2";
+ System.out.println("------采集水、电、运行状态!" + i + "------");
+ } else {
+ threadName = "3";
+ System.out.println("------采集设定温度、设定水位、故障状态!" + i + "------");
+ }
+ CountDownLatch countDownLatch = new CountDownLatch(10);
+ for (int j = 1; j < 11; j++) {
+ SerialPortThread myThread = new SerialPortThread();
+ myThread.setName(threadName, String.valueOf(j), countDownLatch);
+ Thread thread = new Thread(myThread);
+ comThreadPool.submit(thread);
+ }
+ countDownLatch.await();
+ }
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ } finally {
+ }
+ }
+ }
}
diff --git a/user-service/src/test/java/com/mh/user/socket/NettyClientTest.java b/user-service/src/test/java/com/mh/user/socket/NettyClientTest.java
index fdbc7c7..9caf53a 100644
--- a/user-service/src/test/java/com/mh/user/socket/NettyClientTest.java
+++ b/user-service/src/test/java/com/mh/user/socket/NettyClientTest.java
@@ -1,44 +1,44 @@
-package com.mh.user.socket;
-
-import com.mh.user.netty.NettyClient;
-import com.mh.user.netty.NettyMeterClient;
-import lombok.extern.slf4j.Slf4j;
-import org.junit.jupiter.api.Test;
-import org.springframework.boot.test.context.SpringBootTest;
-
-/**
- * @author ljf
- * @title :
- * @description :
- * @updateTime 2020-05-13
- * @throws :
- */
-@Slf4j
-@SpringBootTest
-public class NettyClientTest {
-
- @Test
- void Test() throws InterruptedException {
- NettyClient nettyClient = new NettyClient();
- nettyClient.connect(1008,"192.168.1.222");
-// Thread.sleep(5000);
-// nettyClient.connect(10100,"192.168.1.222");
- }
-
- @Test
- void Test1() throws InterruptedException {
- NettyClient nettyClient = new NettyClient();
- nettyClient.connect(8080,"192.168.2.10");
-// Thread.sleep(5000);
-// nettyClient.connect(10100,"192.168.1.222");
- }
-
-
- @Test
- void testMeterChillers() throws InterruptedException {
- NettyMeterClient nettyMeterClient = new NettyMeterClient();
- nettyMeterClient.connect(8080,"192.168.2.10");
-// nettyMeterClient.connect(9000,"192.168.2.54");
- }
-
-}
+//package com.mh.user.socket;
+//
+//import com.mh.user.netty.NettyClient;
+//import com.mh.user.netty.NettyMeterClient;
+//import lombok.extern.slf4j.Slf4j;
+//import org.junit.jupiter.api.Test;
+//import org.springframework.boot.test.context.SpringBootTest;
+//
+///**
+// * @author ljf
+// * @title :
+// * @description :
+// * @updateTime 2020-05-13
+// * @throws :
+// */
+//@Slf4j
+//@SpringBootTest
+//public class NettyClientTest {
+//
+// @Test
+// void Test() throws InterruptedException {
+// NettyClient nettyClient = new NettyClient();
+// nettyClient.connect(1008,"192.168.1.222");
+//// Thread.sleep(5000);
+//// nettyClient.connect(10100,"192.168.1.222");
+// }
+//
+// @Test
+// void Test1() throws InterruptedException {
+// NettyClient nettyClient = new NettyClient();
+// nettyClient.connect(8080,"192.168.2.10");
+//// Thread.sleep(5000);
+//// nettyClient.connect(10100,"192.168.1.222");
+// }
+//
+//
+// @Test
+// void testMeterChillers() throws InterruptedException {
+// NettyMeterClient nettyMeterClient = new NettyMeterClient();
+// nettyMeterClient.connect(8080,"192.168.2.10");
+//// nettyMeterClient.connect(9000,"192.168.2.54");
+// }
+//
+//}
diff --git a/user-service/src/test/java/com/mh/user/socket/NettyEchoServer.java b/user-service/src/test/java/com/mh/user/socket/NettyEchoServer.java
index d7b285b..d43e757 100644
--- a/user-service/src/test/java/com/mh/user/socket/NettyEchoServer.java
+++ b/user-service/src/test/java/com/mh/user/socket/NettyEchoServer.java
@@ -1,182 +1,182 @@
-package com.mh.user.socket;
-
-import com.mh.user.utils.ExchangeStringUtil;
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioServerSocketChannel;
-import io.netty.handler.logging.LogLevel;
-import io.netty.handler.logging.LoggingHandler;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.util.StringUtils;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-
-
-/**
- * @author ljf
- * @title :Netty
- * @description :netty 使用
- * @updateTime 2020-04-21
- * @throws :
- */
-@Slf4j
-public class NettyEchoServer {
-
- public void bind(int port) throws Exception {
- // accept线程组,用来接收连接
- EventLoopGroup bossGroup = new NioEventLoopGroup(1);
- // IO 线程组,用来处理业务逻辑
- EventLoopGroup workerGroup = new NioEventLoopGroup(1);
-
- try {
- // 服务端启动引导
- ServerBootstrap serverBootstrap = new ServerBootstrap();
- serverBootstrap.group(bossGroup,workerGroup) // 绑定两个线程
- .channel(NioServerSocketChannel.class) // 指定通道类型
- .option(ChannelOption.SO_BACKLOG, 1024) // 设置TCP连接的缓冲区
- .handler(new LoggingHandler(LogLevel.INFO)) // 设置日志级别
- .childHandler(new ChannelInitializer() {
- @Override
- protected void initChannel(SocketChannel socketChannel) throws Exception {
- ChannelPipeline pipeline = socketChannel.pipeline(); // 获取处理器链
- pipeline.addLast(new EchoServerHandler()); // 添加新的事件处理器
- }
- });
- // 通过bind启动服务
- ChannelFuture f = serverBootstrap.bind(port).sync();
- // 阻塞主线程,知道网络服务被关闭
- f.channel().closeFuture().sync();
- } catch (Exception e){
- e.printStackTrace();
- } finally {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- }
-
- static class EchoServerHandler extends ChannelHandlerAdapter {
-
- // 每当从客户端收到新的数据时,这个方法会在收到消息时被调用
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- try {
- ByteBuf buf = (ByteBuf)msg;
- byte [] bytes = new byte[buf.readableBytes()];
- buf.readBytes(bytes);//复制内容到字节数组bytes
- String receiveStr = ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
- log.info("接收到的数据: "+ receiveStr);
- //返回16进制到客户端
- writeToClient(receiveStr,ctx,"测试");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-// ctx.write(Unpooled.wrappedBuffer("Server message".getBytes()));
-// ctx.fireChannelRead(msg);
- }
-
- // 数据读取完后被调用
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- ctx.flush();
- }
-
- // 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- cause.printStackTrace();
- ctx.close();
- }
-
- /**
- * 客户端与服务端第一次建立连接时 执行
- *
- * @param ctx
- * @throws Exception
- */
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException
- {
- super.channelActive(ctx);
- ctx.channel().read();
- InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
- String clientIp = ifsock.getAddress().getHostAddress();
- //此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
- log.info("channelActive: "+clientIp + ctx.name());
- }
-
- /**
- * 客户端与服务端 断连时 执行
- *
- * @param ctx
- * @throws Exception
- */
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException
- {
- super.channelInactive(ctx);
- InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
- String clientIp = ifsock.getAddress().getHostAddress();
- ctx.close(); //断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
- System.out.println("channelInactive:"+clientIp);
- }
-
- /**
- * 服务端当read超时, 会调用这个方法
- *
- * @param ctx
- * @param evt
- * @throws Exception
- */
- @Override
- public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException
- {
- super.userEventTriggered(ctx, evt);
- InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
- String clientIp = ifsock.getAddress().getHostAddress();
- ctx.close();//超时时断开连接
- System.out.println("userEventTriggered:"+clientIp);
- }
-
-
- /**
- * 公用回写数据到客户端的方法
- * @param channel
- * @param mark 用于打印/log的输出
- *
//channel.writeAndFlush(msg);//不行
- *
//channel.writeAndFlush(receiveStr.getBytes());//不行
- *
在netty里,进出的都是ByteBuf,楼主应确定服务端是否有对应的编码器,将字符串转化为ByteBuf
- */
- private void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark) {
- try {
- ByteBuf buff = Unpooled.buffer();//netty需要用ByteBuf传输
- buff.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(receiveStr));//对接需要16进制
- channel.writeAndFlush(buff).addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture future) throws Exception {
- StringBuilder sb = new StringBuilder("");
- if(!StringUtils.isEmpty(mark)){
- sb.append("【").append(mark).append("】");
- }
- if (future.isSuccess()) {
- System.out.println(sb.toString()+"回写成功"+receiveStr);
- log.info(sb.toString()+"回写成功"+receiveStr);
- } else {
- System.out.println(sb.toString()+"回写失败"+receiveStr);
- log.error(sb.toString()+"回写失败"+receiveStr);
- }
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("调用通用writeToClient()异常"+e.getMessage());
- log.error("调用通用writeToClient()异常:",e);
- }
- }
- }
-}
+//package com.mh.user.socket;
+//
+//import com.mh.user.utils.ExchangeStringUtil;
+//import io.netty.bootstrap.ServerBootstrap;
+//import io.netty.buffer.ByteBuf;
+//import io.netty.buffer.Unpooled;
+//import io.netty.channel.*;
+//import io.netty.channel.nio.NioEventLoopGroup;
+//import io.netty.channel.socket.SocketChannel;
+//import io.netty.channel.socket.nio.NioServerSocketChannel;
+//import io.netty.handler.logging.LogLevel;
+//import io.netty.handler.logging.LoggingHandler;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.util.StringUtils;
+//
+//import java.io.IOException;
+//import java.net.InetSocketAddress;
+//
+//
+///**
+// * @author ljf
+// * @title :Netty
+// * @description :netty 使用
+// * @updateTime 2020-04-21
+// * @throws :
+// */
+//@Slf4j
+//public class NettyEchoServer {
+//
+// public void bind(int port) throws Exception {
+// // accept线程组,用来接收连接
+// EventLoopGroup bossGroup = new NioEventLoopGroup(1);
+// // IO 线程组,用来处理业务逻辑
+// EventLoopGroup workerGroup = new NioEventLoopGroup(1);
+//
+// try {
+// // 服务端启动引导
+// ServerBootstrap serverBootstrap = new ServerBootstrap();
+// serverBootstrap.group(bossGroup,workerGroup) // 绑定两个线程
+// .channel(NioServerSocketChannel.class) // 指定通道类型
+// .option(ChannelOption.SO_BACKLOG, 1024) // 设置TCP连接的缓冲区
+// .handler(new LoggingHandler(LogLevel.INFO)) // 设置日志级别
+// .childHandler(new ChannelInitializer() {
+// @Override
+// protected void initChannel(SocketChannel socketChannel) throws Exception {
+// ChannelPipeline pipeline = socketChannel.pipeline(); // 获取处理器链
+// pipeline.addLast(new EchoServerHandler()); // 添加新的事件处理器
+// }
+// });
+// // 通过bind启动服务
+// ChannelFuture f = serverBootstrap.bind(port).sync();
+// // 阻塞主线程,知道网络服务被关闭
+// f.channel().closeFuture().sync();
+// } catch (Exception e){
+// e.printStackTrace();
+// } finally {
+// workerGroup.shutdownGracefully();
+// bossGroup.shutdownGracefully();
+// }
+// }
+//
+// static class EchoServerHandler extends ChannelHandlerAdapter {
+//
+// // 每当从客户端收到新的数据时,这个方法会在收到消息时被调用
+// @Override
+// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+// try {
+// ByteBuf buf = (ByteBuf)msg;
+// byte [] bytes = new byte[buf.readableBytes()];
+// buf.readBytes(bytes);//复制内容到字节数组bytes
+// String receiveStr = ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
+// log.info("接收到的数据: "+ receiveStr);
+// //返回16进制到客户端
+// writeToClient(receiveStr,ctx,"测试");
+// } catch (Exception e) {
+// // TODO Auto-generated catch block
+// e.printStackTrace();
+// }
+//// ctx.write(Unpooled.wrappedBuffer("Server message".getBytes()));
+//// ctx.fireChannelRead(msg);
+// }
+//
+// // 数据读取完后被调用
+// @Override
+// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+// ctx.flush();
+// }
+//
+// // 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用
+// @Override
+// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+// cause.printStackTrace();
+// ctx.close();
+// }
+//
+// /**
+// * 客户端与服务端第一次建立连接时 执行
+// *
+// * @param ctx
+// * @throws Exception
+// */
+// @Override
+// public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException
+// {
+// super.channelActive(ctx);
+// ctx.channel().read();
+// InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
+// String clientIp = ifsock.getAddress().getHostAddress();
+// //此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
+// log.info("channelActive: "+clientIp + ctx.name());
+// }
+//
+// /**
+// * 客户端与服务端 断连时 执行
+// *
+// * @param ctx
+// * @throws Exception
+// */
+// @Override
+// public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException
+// {
+// super.channelInactive(ctx);
+// InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
+// String clientIp = ifsock.getAddress().getHostAddress();
+// ctx.close(); //断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
+// System.out.println("channelInactive:"+clientIp);
+// }
+//
+// /**
+// * 服务端当read超时, 会调用这个方法
+// *
+// * @param ctx
+// * @param evt
+// * @throws Exception
+// */
+// @Override
+// public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException
+// {
+// super.userEventTriggered(ctx, evt);
+// InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
+// String clientIp = ifsock.getAddress().getHostAddress();
+// ctx.close();//超时时断开连接
+// System.out.println("userEventTriggered:"+clientIp);
+// }
+//
+//
+// /**
+// * 公用回写数据到客户端的方法
+// * @param channel
+// * @param mark 用于打印/log的输出
+// *
//channel.writeAndFlush(msg);//不行
+// *
//channel.writeAndFlush(receiveStr.getBytes());//不行
+// *
在netty里,进出的都是ByteBuf,楼主应确定服务端是否有对应的编码器,将字符串转化为ByteBuf
+// */
+// private void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark) {
+// try {
+// ByteBuf buff = Unpooled.buffer();//netty需要用ByteBuf传输
+// buff.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(receiveStr));//对接需要16进制
+// channel.writeAndFlush(buff).addListener(new ChannelFutureListener() {
+// @Override
+// public void operationComplete(ChannelFuture future) throws Exception {
+// StringBuilder sb = new StringBuilder("");
+// if(!StringUtils.isEmpty(mark)){
+// sb.append("【").append(mark).append("】");
+// }
+// if (future.isSuccess()) {
+// System.out.println(sb.toString()+"回写成功"+receiveStr);
+// log.info(sb.toString()+"回写成功"+receiveStr);
+// } else {
+// System.out.println(sb.toString()+"回写失败"+receiveStr);
+// log.error(sb.toString()+"回写失败"+receiveStr);
+// }
+// }
+// });
+// } catch (Exception e) {
+// e.printStackTrace();
+// System.out.println("调用通用writeToClient()异常"+e.getMessage());
+// log.error("调用通用writeToClient()异常:",e);
+// }
+// }
+// }
+//}