YYC
2023-06-27 1f2c3a31d9652b5d07f852b6d8d2b1b378adcfc2
Merge remote-tracking branch 'origin/master'
已修改7个文件
已添加31个文件
2793 ■■■■■ 文件已修改
igds-core/src/main/java/com/ld/igds/io/constant/ProtocolEnum.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-core/src/main/java/com/ld/igds/view/Depot.view.xml 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/pom.xml 49 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/RemoteGrainV1ServiceImpl.java 70 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/ServerRunner.java 34 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/AnalysisService.java 474 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/builder/CommandBuild.java 178 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/builder/ReMessageBuilder.java 51 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/message/Content.java 43 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/message/IoMessage.java 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/package-info.java 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1HeartbeatImpl.java 42 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1MessageConsumer.java 57 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1ServerEngine.java 131 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1ServerUtils.java 103 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1SessionListener.java 68 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/RemoteGrainV2ServiceImpl.java 70 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/ServerRunner.java 34 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/AnalysisService.java 474 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/builder/CommandBuild.java 178 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/builder/ReMessageBuilder.java 51 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/message/Content.java 43 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/message/IoMessage.java 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/package-info.java 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2HeartbeatImpl.java 42 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2MessageConsumer.java 57 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2ServerEngine.java 131 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2ServerUtils.java 103 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2SessionListener.java 65 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/package-info.java 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-web/pom.xml 16 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-web/src/main/resources/application-dev.yml 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-web/src/main/resources/application-pro5324.yml 80 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-web/src/main/resources/application-pro5326.yml 80 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-web/src/main/resources/application.yml 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-web/src/main/resources/logback-spring.xml 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-web/src/main/resources/static/img/aerial-5326_001.png 补丁 | 查看 | 原始文档 | blame | 历史
pom.xml 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
igds-core/src/main/java/com/ld/igds/io/constant/ProtocolEnum.java
@@ -27,7 +27,8 @@
    TCP_FZZY_N2_V3("TCP_FZZY_N2_V3", "FZZY-制氮机协议"),
    TCP_LT_SAMPLE_V3("TCP_LT_SAMPLE_V3", "扦样机协议"),
    TCP_FZZY_QUANTITY_V35("TCP_FZZY_QUANTITY_V35", "数量检测V35"),
    TCP_BHZH_GRAIN_FM_V1("TCP_BHZH_GRAIN_FM_V1", "邦海智能无线主机版V1");
    TCP_BHZH_GRAIN_FM_V1("TCP_BHZH_GRAIN_FM_V1", "邦海智能无线主机版V1"),
    TCP_BHZH_GRAIN_V2("TCP_BHZH_GRAIN_V2", "邦海智能有线版V2");
    private String code;
    private String msg;
igds-core/src/main/java/com/ld/igds/view/Depot.view.xml
@@ -480,7 +480,7 @@
      <Property name="minWidth">500</Property>
      <Container layout="regionPadding:5">
        <DataSet id="dsFoodOrigin">
          <Property name="dataProvider">dicTriggerPR#pagFoodLocationData</Property>
          <Property name="dataProvider"></Property>
          <Property name="dataType">[dtFoodOrigin]</Property>
          <Property name="parameter"></Property>
          <Property name="pageSize">30</Property>
igds-protocol-bhzn/pom.xml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,49 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ld.igds</groupId>
    <artifactId>igds-protocol-bhzn</artifactId>
    <version>4.0.0-RELEASE</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <igds.version>4.0.0-RELEASE</igds.version>
    </properties>
    <dependencies>
        <!-- å¼•入义务核心包 -->
        <dependency>
            <groupId>com.ld.igds</groupId>
            <artifactId>igds-core</artifactId>
            <version>${igds.version}</version>
        </dependency>
        <!-- å¼•å…¥IO包 -->
        <dependency>
            <groupId>com.ld.base.io</groupId>
            <artifactId>base-io-netty</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
     <build>
         <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <configuration>
                     <source>1.8</source>
                     <target>1.8</target>
                     <compilerArguments>
                         <extdirs>src\main\webapp\WEB-INF\lib</extdirs>
                     </compilerArguments>
                 </configuration>
             </plugin>
         </plugins>
     </build>
</project>
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/RemoteGrainV1ServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,70 @@
package com.ld.igds.protocol.bhzn.grainv1;
import com.ld.igds.common.CoreSerService;
import com.ld.igds.io.RemoteGrainService;
import com.ld.igds.io.constant.OrderRespEnum;
import com.ld.igds.io.constant.ProtocolEnum;
import com.ld.igds.io.request.CheckGrainRequest;
import com.ld.igds.io.response.GrainResponse;
import com.ld.igds.protocol.bhzn.grainv1.msg.builder.CommandBuild;
import com.ld.igds.protocol.bhzn.grainv1.server.BhznGrainV1ServerEngine;
import com.ld.io.api.InvokeResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * @Desc: ç²®æƒ…业务接口
 * @author: Andy
 * @update-time: 2023/5/11
 */
@Slf4j
@Component(RemoteGrainV1ServiceImpl.BEAN_ID)
public class RemoteGrainV1ServiceImpl implements RemoteGrainService {
    public static final String BEAN_ID = "bhznGrain.remoteGrainService";
    @Autowired
    private CoreSerService coreSerService;
    @Autowired
    private BhznGrainV1ServerEngine bhznGrainServerEngine;
    @Override
    public String getProtocol() {
        return ProtocolEnum.TCP_BHZH_GRAIN_FM_V1.getCode();
    }
    @Override
    public GrainResponse checkGrain(CheckGrainRequest request) {
        try {
            // ç”Ÿæˆç²®æƒ…信息
            String hexStr = CommandBuild.getInstance().getMsgCheck(request.getSerId(), request.getDepotId());
//            //通讯使用的是主机通讯
//            DeviceSer mainSer = coreSerService.getCacheSer(ContextUtil.getDefaultCompanyId(), BhznGrainV1ServerUtils.DEFAULT_MAC_ID);
//            request.setIp(mainSer.getIp());
//            request.setPort(mainSer.getPort());
            // å‘送命令
            InvokeResult result = bhznGrainServerEngine.pushByMin(hexStr);
            log.error("平台------>>>>控制柜:粮情检测-{}", hexStr);
            // å°è£…返回信息
            if (InvokeResult.SUCCESS == result) {
                return new GrainResponse(OrderRespEnum.ORDER_SUCCESS.getCode(),
                        "粮情粮情发送成功!");
            } else {
                log.error("平台------>>>>控制柜:粮情检测-失败{}", result.getMessage());
                return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                        "命令发送异常:" + result.getMessage());
            }
        } catch (Exception e) {
            log.error("粮情检测异常:{}", e);
            return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(), "后端异常:" + e.getMessage());
        }
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/ServerRunner.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,34 @@
package com.ld.igds.protocol.bhzn.grainv1;
import com.ld.igds.data.ConfigData;
import com.ld.igds.protocol.bhzn.grainv1.server.BhznGrainV1ServerEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
 * é…ç½®éšç³»ç»Ÿè‡ªåŠ¨å¯åŠ¨æœåŠ¡ -- æ‰§è¡Œé¡ºåº20-29
 */
@Component(ServerRunner.BEAN_ID)
@Order(value = 24)
public class ServerRunner implements CommandLineRunner {
    public static final String BEAN_ID = "bhzn.serverRunnerV1";
    @Autowired
    private ConfigData configData;
    @Autowired
    private BhznGrainV1ServerEngine bhznGrainServerEngine;
    @Override
    public void run(String... strings) throws Exception {
        if (configData.getActive().indexOf("pro") >= 0) {
            //bhznGrainServerEngine.start(BhznGrainServerEngine.PORT);
        }
        if (configData.getActive().indexOf("dev") >= 0) {
            //bhznGrainServerEngine.start(BhznGrainServerEngine.PORT);
        }
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/AnalysisService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,474 @@
package com.ld.igds.protocol.bhzn.grainv1.msg;
import com.ld.igds.common.CoreCommonService;
import com.ld.igds.common.CoreSerService;
import com.ld.igds.common.dto.THDto;
import com.ld.igds.constant.BizType;
import com.ld.igds.constant.Constant;
import com.ld.igds.grain.GrainUtil;
import com.ld.igds.grain.dto.GrainItemInfo;
import com.ld.igds.io.notify.NotifyGrainInvoker;
import com.ld.igds.models.DepotConf;
import com.ld.igds.models.DeviceSer;
import com.ld.igds.models.DicSysConf;
import com.ld.igds.models.Grain;
import com.ld.igds.order.ExeOrderService;
import com.ld.igds.order.data.ExeRequest;
import com.ld.igds.protocol.bhzn.grainv1.msg.builder.CommandBuild;
import com.ld.igds.protocol.bhzn.grainv1.msg.builder.ReMessageBuilder;
import com.ld.igds.protocol.bhzn.grainv1.msg.message.IoMessage;
import com.ld.igds.protocol.bhzn.grainv1.server.BhznGrainV1ServerEngine;
import com.ld.igds.protocol.bhzn.grainv1.server.BhznGrainV1ServerUtils;
import com.ld.igds.util.BytesUtil;
import com.ld.igds.util.ContextUtil;
import com.ld.igds.warn.WarnUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
/**
 * åè®®è§£æž
 *
 * @author vince
 */
@Slf4j
@Component(AnalysisService.BEAN_ID)
public class AnalysisService {
    /**
     * é’ˆå¯¹åˆ†åŒ…粮情报文进行封装
     */
    public static Map<String, String> contextMapGrain = new HashMap<>();
    /**
     * ç”¨äºŽå­˜æ”¾è¿”回的仓温仓湿信息
     */
    public static Map<String, THDto> contextMapTH = new HashMap<>();
    public static final String BEAN_ID = "bhznGrainv1.analysisService";
    @Autowired
    private CoreSerService coreSerService;
    @Autowired
    private BhznGrainV1ServerEngine serverEngine;
    @Autowired
    private CoreCommonService commonService;
    @Autowired
    private NotifyGrainInvoker notifyGrainInvoker;
    @Autowired
    private GrainUtil grainUtil;
    @Autowired
    private WarnUtils warnUtils;
    @Autowired
    private ExeOrderService exeOrderService;
    /**
     * @param sessionKey ip:port
     */
    public void analysis(String sessionKey, IoMessage message) throws Exception {
        //注册
        if (BhznGrainV1ServerUtils.FUNCTION_ID_F1.equals(message.getFunctionId())) {
            //DO NOTHING
            log.info("主机------->>平台:注册信息报文={}", message);
            DeviceSer ser = coreSerService.getCacheSerBySn(ContextUtil.getDefaultCompanyId(),message.getAddr());
            if(ser!= null ){
                ser.setIp(message.getIp());
                ser.setPort(message.getPort());
                ser.setStatus(Constant.YN_Y);
                coreSerService.updateByData(ser);
            }
            return;
        }
        //心跳
        if (BhznGrainV1ServerUtils.FUNCTION_ID_F2.equals(message.getFunctionId())) {
            String hexStr = CommandBuild.getMsgHeartReply(message.getAddr());
            log.info("平台--------->>>主机,返回心跳收到信息,报文={}", hexStr);
            serverEngine.pushByMin(hexStr);
            return;
        }
        // 93 è§£æžä»“温仓湿,并返回收到报文
        if (BhznGrainV1ServerUtils.FUNCTION_ID_93.equals(message.getFunctionId())) {
            log.info("主机------->>平台:温湿度信息报文={}", message);
            analysisTh(message);
            return;
        }
        // 92 è§£æžç²®æ¸©ï¼Œå¹¶è¿”回收到报文
        if (BhznGrainV1ServerUtils.FUNCTION_ID_92.equals(message.getFunctionId())) {
            log.info("主机------->>平台:粮情信息报文={}", message);
            analysisGrain(message);
        }
    }
    private void analysisGrain(IoMessage message) {
        try {
            //根据分机地址获取分机信息
            DeviceSer ser = coreSerService.getCacheSer(ContextUtil.getDefaultCompanyId(), message.getAddr());
            if (ser == null) {
                replayGrain(message);
                log.error("主机-------->>平台,解析粮情失败,未获取到系统粮情主机配置:" + message.getAddr());
                return;
            }
            // é¦–先获取到系统参数,判断是否需要批次自动优化
            DicSysConf sysConf = commonService.getCacheSysConf(ser.getCompanyId());
            List<ExeRequest> list = exeOrderService.getInProgressOrderBySerId(BizType.GRAIN.getCode(), ser.getId());
            if (null == list || list.isEmpty()) {
                String info = "粮情解析失败:分机=" + ser.getName() + "没有获取到所属仓库信息。";
                log.error("分机------>>>平台:" + info);
                return;
            }
            //获取针对当前仓库的命令
            ExeRequest exeRequest = list.get(0);
            if (null == exeRequest) {
                String info = "粮情解析失败:分机=" + ser.getName() + "没有获取历史命令。";
                log.error("分机------>>>平台:" + info);
                return;
            }
            DepotConf depotConf = commonService.getCacheDepotConf(exeRequest.getCompanyId(), exeRequest.getDepotId());
            if (null == depotConf) {
                String info = "粮情解析失败:分机=" + ser.getName() + "没有获取到粮情参数配置信息。";
                log.error("分机------>>>平台:" + info);
                return;
            }
            // ç²®æƒ…的批次号重新根据频率调整
            String batchId = ContextUtil.getBatchIdByFireq(depotConf.getGrainFreq());
            // åˆ¤æ–­æ•°æ®æœ‰æ²¡æœ‰æ”¶å–完整
            String[] attCable = depotConf.getCableRule().split("-");
            int cableZ = Integer.valueOf(attCable[0]);
            int cableY = Integer.valueOf(attCable[1]);
            int cableX = Integer.valueOf(attCable[2]);
            int sumPoint = cableZ * cableY * cableX;
            //获取当前粮情温度报文
            String grainHex = message.getContent().substring(16);
            //当前报文温度点数
            int curPoint = BytesUtil.hexToInt(BytesUtil.tran_LH(message.getContent().substring(4, 8)));
            //如果当前包的数据个数大于等于当前仓库的配置点位则表示单包返回
            if (curPoint >= sumPoint) {
                //返回粮情接收信息
                replayGrain(message);
                analysisGrain2(ser, message, exeRequest, depotConf, sysConf, batchId, grainHex);
                return;
            }
            //表示分包传递
            String key = "GRAIN_" + message.getAddr();
            String oldGrainHex = contextMapGrain.get(key) == null ? "" : contextMapGrain.get(key);
            //获取当前包起始点的层行列
            int hang = BytesUtil.hexToInt(BytesUtil.tran_LH(message.getContent().substring(8, 10)));
            int lie = BytesUtil.hexToInt(BytesUtil.tran_LH(message.getContent().substring(10, 12)));
            int ceng = BytesUtil.hexToInt(BytesUtil.tran_LH(message.getContent().substring(12, 14)));
            if (hang > 0 || lie > 0 || ceng > 0) {
                //说明非第一包数据
                grainHex = oldGrainHex + grainHex;
            }
            if (grainHex.length() >= sumPoint * 4) {
                //返回粮情接收信息
                replayGrain(message);
                analysisGrain2(ser, message, exeRequest, depotConf, sysConf, batchId, grainHex);
                return;
            } else {
                contextMapGrain.put(key, grainHex);
                replayGrain(message);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    /**
     * è¿”回粮情收到报文信息,需要注意:如果存在分包情况下,需要等所有包收到后返回
     *
     * @param message
     */
    private void replayGrain(IoMessage message) {
        String hexStr = CommandBuild.getMsgGrainReply(message.getAddr());
        log.info("平台--------->>>主机,返回粮情报文收到信息,报文={}", hexStr);
        serverEngine.pushByMin(hexStr);
    }
    private void analysisGrain2(DeviceSer ser, IoMessage message, ExeRequest exeRequest, DepotConf depotConf, DicSysConf sysConf, String batchId, String grainStr) {
        // èŽ·å–å®Œæ•´çš„ç²®æƒ…åŒ…ä¿¡æ¯
        String[] attCable = depotConf.getCableRule().split("-");
        int cableZ = Integer.valueOf(attCable[0]);
        int cableY = Integer.valueOf(attCable[1]);
        int cableX = Integer.valueOf(attCable[2]);
        // æ ¹æ®å±‚行列获取指定长度
        int start = 4 * (depotConf.getCableStart() - ser.getCableStart())
                * cableZ * cableY;
        int len = 4 * cableZ * cableY * cableX;
        log.info("分机------>>>平台:返回粮情完整信息,所属组织={},分机={}", ser.getCompanyId(), ser.getName());
        String strPoints = grainStr.substring(start, start + len);
        // å°†ç²®æƒ…解析成数组
        List<Double> temps = new ArrayList<>();
        double tempValue;
        String temp;
        for (int i = 0; i < strPoints.length() / 4; i++) {
            temp = strPoints.substring(i * 4, i * 4 + 4);
            if (temp == null) {
                temp = "0000";
            }
            if (ReMessageBuilder.ERROR_TAG.equals(temp)) {
                tempValue = Constant.ERROR_TEMP;
            } else {
                tempValue = BytesUtil.hexToInt(BytesUtil.tran_LH(temp)) / 10.0;
            }
            // æ•…障值处理
            if (tempValue >= ReMessageBuilder.FAULT_CHECK_TAG) {
                tempValue = Constant.FAULT_TEMP;
            }
            temps.add(tempValue);
        }
        log.debug("-------CheckGrainRequest--={}", exeRequest.toString());
        THDto thDto = this.getTH(message);
        if (null != thDto) {
            log.debug("-------THDto--={}", thDto.toString());
        }
        //清空
        String key = "GRAIN_" + message.getAddr();
        contextMapGrain.put(key, null);
        // å°†é›†åˆè§£æžæˆåæ ‡æ•°æ®
        addPoint1(temps, depotConf, ser, exeRequest, thDto, sysConf, batchId);
    }
    /**
     * å¹³æˆ¿ä»“,解析第二步,解析到坐标数据
     *
     * @param temps
     * @throws Exception
     */
    private void addPoint1(List<Double> temps,
                           DepotConf depotConf, DeviceSer ser, ExeRequest exeRequest,
                           THDto thDto, DicSysConf sysConf, String batchId) {
        //根据电缆起始方位和布线方向,对粮情数据进行调整
        if (null != depotConf.getStartOrientation()) {
            temps = reversalGrainPoint(temps, depotConf);
        }
        //若起点点位为底部,则将粮情数据进行翻转
        if (null != depotConf.getStartPoint()
                && Constant.GRAIN_START_POINT_BELOW.equals(depotConf.getStartPoint())) {
            temps = grainUtil.reversalUpAndDown(temps, depotConf.getCableRule());
        }
        String[] attCable = depotConf.getCableRule().split("-");
        int cableZ = Integer.valueOf(attCable[0]);
        int cableY = Integer.valueOf(attCable[1]);
        int cableX = Integer.valueOf(attCable[2]);
        Grain grain = new Grain();
        grain.setDepotId(depotConf.getDepotId());
        grain.setCompanyId(depotConf.getCompanyId());
        grain.setCable(depotConf.getCableRule());
        grain.setBatchId(batchId);
        grain.setTempIn(Constant.ERROR_TEMP);
        grain.setHumidityIn(Constant.ERROR_TEMP);
        if (null != thDto) {
            log.debug("粮情解析中获取到的温湿度信息={}", thDto.toString());
            grain.setHumidityIn(thDto.getHumidityIn());
            grain.setTempIn(thDto.getTempIn());
        }
        grain.setReceiveDate(new Date());
        grain.setRemark("粮温正常");
        // èŽ·å–ç¼“å­˜ä¸­çš„å‘½ä»¤ä¿¡æ¯
        grain.setCheckUser(exeRequest.getExeUser());
        double max = ReMessageBuilder.MAX_TEMP, min = ReMessageBuilder.MIN_TEMP, sumT = 0.0, sumNum = cableX
                * cableY * cableZ;
        // æ ¡éªŒå’Œå®žçŽ°ç»Ÿè®¡ï¼Œç”Ÿæˆé‡‡é›†ç‚¹ä¿¡æ¯
        List<GrainItemInfo> listGrainItems = new ArrayList<>();
        int i = 1;
        for (Double temp : temps) {
            if (temp == Constant.ERROR_TEMP || temp == Constant.FAULT_TEMP || temp == Constant.ADD_TEMP) {
                sumNum--;
            } else {
                sumT += temp;
                if (temp > max) {
                    max = temp;
                }
                if (temp < min) {
                    min = temp;
                }
            }
            listGrainItems.add(new GrainItemInfo(i, temp));
            i++;
        }
        if (sumNum == 0) {
            sumNum = 1;
            grain.setRemark("当前粮情采集异常");
        }
        //过滤比较用的最大最小值
        if (max == ReMessageBuilder.MAX_TEMP) {
            max = 0.0;
        }
        if (min == ReMessageBuilder.MIN_TEMP) {
            min = 0.0;
        }
        if (null != depotConf.getTempMax() && max > depotConf.getTempMax()) {
            grain.setRemark("仓库配置高温警告值:" + depotConf.getTempMax() + ",当前检测高温值:"
                    + max);
            warnUtils.addGrainWarn(depotConf, grain);
        }
        grain.setTempAve(sumT / sumNum);
        grain.setTempMax(max);
        grain.setTempMin(min);
        grain.setPoints(org.apache.commons.lang3.StringUtils.join(temps, ","));
        String depotIds = exeRequest.getDepotIds();
        boolean notifyWeb = true;
        if (null != depotIds && depotIds.indexOf(depotConf.getDepotId()) == -1) {
            notifyWeb = false;
        }
        // ç”¨æˆ·å°è£…好数据即可
        notifyGrainInvoker.analysisSuccess(grain, listGrainItems, depotConf,
                sysConf, notifyWeb, exeRequest);
    }
    private List<Double> reversalGrainPoint(List<Double> temps, DepotConf conf) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartOrientation())) {
            //若起始方位为空,则默认起始方位和方向,直接返回
            return temps;
        }
        //起始方位为右边时
        if (Constant.GRAIN_START_ORIENTATION_RIGHT.equals(conf.getStartOrientation())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartDirection())) {
                //右边起始,默认纵向布线,直接返回
                return temps;
            }
            if (Constant.GRAIN_START_DIRECTION_TRANSVERSE.equals(conf.getStartDirection())) {
                //右边起始,横向布线
                return grainUtil.reversalRight1(temps, conf.getCableRule());
            }
            //右边起始,默认纵向布线,直接返回
            return temps;
        }
        //起始方位为右上时
        if (Constant.GRAIN_START_ORIENTATION_RIGHT_UP.equals(conf.getStartOrientation())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartDirection())) {
                //右上起始,默认纵向布线
                return grainUtil.reversalRightUp2(temps, conf.getCableRule());
            }
            if (Constant.GRAIN_START_DIRECTION_TRANSVERSE.equals(conf.getStartDirection())) {
                //右上起始,横向布线
                return grainUtil.reversalRightUp1(temps, conf.getCableRule());
            }
            //右上起始,默认纵向布线
            return grainUtil.reversalRightUp2(temps, conf.getCableRule());
        }
        //起始方位为左边时
        if (Constant.GRAIN_START_ORIENTATION_LEFT.equals(conf.getStartOrientation())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartDirection())) {
                //左边起始,默认纵向布线
                return grainUtil.reversalLeft2(temps, conf.getCableRule());
            }
            if (Constant.GRAIN_START_DIRECTION_TRANSVERSE.equals(conf.getStartDirection())) {
                //左边起始,横向布线
                return grainUtil.reversalLeft1(temps, conf.getCableRule());
            }
            //左边起始,默认纵向布线
            return grainUtil.reversalLeft2(temps, conf.getCableRule());
        }
        //起始方位为左上时
        if (Constant.GRAIN_START_ORIENTATION_LEFT_UP.equals(conf.getStartOrientation())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartDirection())) {
                //左上起始,默认纵向布线
                return grainUtil.reversalLeftUp2(temps, conf.getCableRule());
            }
            if (Constant.GRAIN_START_DIRECTION_TRANSVERSE.equals(conf.getStartDirection())) {
                //左上起始,横向布线
                return grainUtil.reversalLeftUp1(temps, conf.getCableRule());
            }
            //左上起始,默认纵向布线
            return grainUtil.reversalLeftUp2(temps, conf.getCableRule());
        }
        return temps;
    }
    private void analysisTh(IoMessage message) {
        try {
            THDto th = new THDto();
            th.setCompanyId(ContextUtil.getDefaultCompanyId());
            String data = message.getContent();
            String houseNo = data.substring(0, 2);
            String t = data.substring(4, 8);
            String h = data.substring(8, 12);
            double temp, humy;
            if (ReMessageBuilder.ERROR_TAG.equals(t)) {
                temp = 0.0;
            } else {
                temp = (double) BytesUtil.hexToBigInt(BytesUtil.tran_LH(t)) / 10;
            }
            if (ReMessageBuilder.ERROR_TAG.equals(h)) {
                humy = 0.0;
            } else {
                humy = (double) BytesUtil.hexToBigInt(BytesUtil.tran_LH(h)) / 10;
            }
            th.setTempIn(temp);
            th.setHumidityIn(humy);
            log.info("主机--------->>>平台,解析仓温仓湿信息,仓库={},结果={}", houseNo, th.toString());
            String key = "TH_" + houseNo;
            contextMapTH.put(key, th);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            String hexStr = CommandBuild.getMsgTHReply(message.getAddr());
            log.info("平台--------->>>主机,返回仓温仓湿收到信息,报文={}", hexStr);
            serverEngine.pushByMin(hexStr);
        }
    }
    private THDto getTH(IoMessage message) {
        String data = message.getContent();
        String houseNo = data.substring(0, 2);
        String key = "TH_" + houseNo;
        return contextMapTH.get(key);
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/builder/CommandBuild.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,178 @@
package com.ld.igds.protocol.bhzn.grainv1.msg.builder;
import com.ld.igds.protocol.bhzn.grainv1.server.BhznGrainV1ServerUtils;
import com.ld.igds.util.BytesUtil;
/**
 * å‘½ä»¤ç”Ÿæˆ
 *
 * @author vince
 */
public class CommandBuild {
    private final static CommandBuild instance = new CommandBuild();
    private CommandBuild() {
    }
    public static CommandBuild getInstance() {
        return instance;
    }
    /**
     * PC回复 å¿ƒè·³å•Š æ”¶åˆ°ä¿¡æ¯
     *
     * @param grainAddr
     * @return
     */
    public static String getMsgHeartReply(String grainAddr) {
        StringBuffer sb = new StringBuffer();
        //开始符号
        sb.append(BhznGrainV1ServerUtils.MSG_START);
        sb.append(BhznGrainV1ServerUtils.MSG_START2);
        //分机地址
        int i = Integer.parseInt(grainAddr);
        sb.append(BytesUtil.tran_LH(BytesUtil.intToHexStr(i)));
        //发送方地址
        sb.append("0000");
        //命令ID
        sb.append(BhznGrainV1ServerUtils.FUNCTION_ID_F2);
        //数据长度-01
        sb.append("01");
        //数据区--任意值
        sb.append("01");
        //获取校验码
        sb.append(BhznGrainV1ServerUtils.getCheck(sb.toString()));
        //结尾符
        sb.append(BhznGrainV1ServerUtils.MSG_END_16);
        return sb.toString();
    }
    /**
     * ç²®æƒ…采集命令
     *
     * @param grainAddr ç²®æƒ…分机地址
     * @param deptId    ä»“库编号地址
     * @return
     */
    public static String getMsgCheck(String grainAddr, String deptId) {
        StringBuffer sb = new StringBuffer();
        //开始符号
        sb.append(BhznGrainV1ServerUtils.MSG_START);
        sb.append(BhznGrainV1ServerUtils.MSG_START2);
        //分机地址
        int i = Integer.parseInt(grainAddr);
        sb.append(BytesUtil.tran_LH(BytesUtil.intToHexStr(i)));
        //发送方地址
        sb.append("0000");
        //命令ID
        sb.append(BhznGrainV1ServerUtils.FUNCTION_ID_83);
        //数据长度-01
        sb.append("01");
        //数据区--主机里面配置的仓库编码
        i = Integer.parseInt(deptId);
        sb.append(BytesUtil.intToHexStr1(i));
        //获取校验码
        sb.append(BhznGrainV1ServerUtils.getCheck(sb.toString()));
        //结尾符
        sb.append(BhznGrainV1ServerUtils.MSG_END_16);
        return sb.toString();
    }
    /**
     * PC回复 ä»“温仓湿 æ”¶åˆ°ä¿¡æ¯
     *
     * @param grainAddr
     * @return
     */
    public static String getMsgTHReply(String grainAddr) {
        StringBuffer sb = new StringBuffer();
        //开始符号
        sb.append(BhznGrainV1ServerUtils.MSG_START);
        sb.append(BhznGrainV1ServerUtils.MSG_START2);
        //分机地址
        int i = Integer.parseInt(grainAddr);
        sb.append(BytesUtil.tran_LH(BytesUtil.intToHexStr(i)));
        //发送方地址
        sb.append("0000");
        //命令ID
        sb.append(BhznGrainV1ServerUtils.FUNCTION_ID_93);
        //数据长度-01
        sb.append("01");
        //数据区--任意值
        sb.append("01");
        //获取校验码
        sb.append(BhznGrainV1ServerUtils.getCheck(sb.toString()));
        //结尾符
        sb.append(BhznGrainV1ServerUtils.MSG_END_16);
        return sb.toString();
    }
    /**
     * PC回复粮温收到信息
     *
     * @param grainAddr
     * @return
     */
    public static String getMsgGrainReply(String grainAddr) {
        StringBuffer sb = new StringBuffer();
        //开始符号
        sb.append(BhznGrainV1ServerUtils.MSG_START);
        sb.append(BhznGrainV1ServerUtils.MSG_START2);
        //分机地址
        int i = Integer.parseInt(grainAddr);
        sb.append(BytesUtil.tran_LH(BytesUtil.intToHexStr(i)));
        //发送方地址
        sb.append("0000");
        //命令ID
        sb.append(BhznGrainV1ServerUtils.FUNCTION_ID_92);
        //数据长度-01
        sb.append("01");
        //数据区--任意值
        sb.append("01");
        //获取校验码
        sb.append(BhznGrainV1ServerUtils.getCheck(sb.toString()));
        //结尾符
        sb.append(BhznGrainV1ServerUtils.MSG_END_16);
        return sb.toString();
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/builder/ReMessageBuilder.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,51 @@
package com.ld.igds.protocol.bhzn.grainv1.msg.builder;
import com.ld.igds.protocol.bhzn.grainv1.msg.message.IoMessage;
import com.ld.igds.util.BytesUtil;
/**
 * æ ¹æ®æŽ¥æ”¶åˆ°çš„信息进行封装
 *
 * @author vince
 */
public class ReMessageBuilder {
    public final static String ERROR_TAG = "3CF6";
    public static double FAULT_CHECK_TAG = 85.0;
    public static double MAX_TEMP = -50.0;
    public static double MIN_TEMP = 50.0;
    private final static ReMessageBuilder instance = new ReMessageBuilder();
    private ReMessageBuilder() {
    }
    public static ReMessageBuilder getInstance() {
        return instance;
    }
    /**
     * @param message
     * @return
     */
    public IoMessage buildMessage(String message) throws Exception {
        IoMessage ioMessage = new IoMessage();
        //转换为数字,高低位转换(4位)
        int i = BytesUtil.hexToBigInt(BytesUtil.tran_LH(message.substring(2, 6)));
        ioMessage.setPcAddr(i + "");
        i = BytesUtil.hexToBigInt(BytesUtil.tran_LH(message.substring(6, 10)));//高低位转换(4位)
        ioMessage.setAddr(i + "");
        ioMessage.setFunctionId(message.substring(10, 12));//功能码(2位),不用高低位转换
        i = BytesUtil.hexToBigInt(message.substring(12, 14));//长度(1位)
        ioMessage.setLength(i);
        //获取消息体
        ioMessage.setContent(message.substring(14, 14 + (i * 2)));
        ioMessage.setCheck(message.substring(message.length() - 2));
        return ioMessage;
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/message/Content.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,43 @@
package com.ld.igds.protocol.bhzn.grainv1.msg.message;
import lombok.Data;
/**
 * @author vince.xu
 * @Title: Content
 * @ProjectName igds-35
 * @Description: TODO
 * @date 2022-12-715:48
 */
@Data
public class Content {
    /**
     * çŠ¶æ€åå›ž
     */
    public  String result;
    /**
     * çº¯åº¦
     */
    public String purity;
    /**
     * æµé‡
     */
    public String flow;
    /**
     * åŽ‹åŠ›
     */
    public String pressure;
    /**
     * æ¸©åº¦
     */
    public String temperature;
    /**
     * æµé‡ç´¯è®¡
     */
    public String flowAll;
    /**
     * è¿è¡ŒçŠ¶æ€
     */
    public String isRun;
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/msg/message/IoMessage.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,20 @@
package com.ld.igds.protocol.bhzn.grainv1.msg.message;
import lombok.Data;
@Data
public class IoMessage {
    private String ip;
    private int port;
    private String pcAddr;
    private String addr;
    private String functionId;
    private int length;
    private String content;
    private String check;
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/package-info.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,4 @@
/**
 * é‚¦æµ·æ— çº¿çº¯ç²®æƒ…协议
 */
package com.ld.igds.protocol.bhzn.grainv1;
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1HeartbeatImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,42 @@
package com.ld.igds.protocol.bhzn.grainv1.server;
import com.ld.io.api.HeartbeatProvider;
import com.ld.io.api.IoSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
 * æä¾›å¿ƒè·³ä¿¡æ¯
 *
 * @author Andy
 */
@Slf4j
@Service
public class BhznGrainV1HeartbeatImpl implements HeartbeatProvider {
    @Override
    public byte[] provide(IoSession session) {
        //直接根据主机SESSIOn判断
        IoSession session1 = BhznGrainV1ServerUtils.getSession();
        Long lastBeatTime = BhznGrainV1ServerUtils.getHearBeat(session1);
        if (null == lastBeatTime) {
            return null;
        }
        //如果最后一次终端心跳时间距离当前时间大于 ç»ˆç«¯å¿ƒè·³æ—¶é—´çš„3次,则判断为离线
        long deTime = System.currentTimeMillis() - lastBeatTime;
        if (deTime > (BhznGrainV1ServerUtils.HEART_BEAT_TIME * 3 * 1000)) {
            log.info("-----------超过{}秒未获取到心跳信息,判定终端离线,踢出连接------------{}-{}", deTime, session.getAddress(), session.getPort());
            session.destroy();
        }
        return null;
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1MessageConsumer.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,57 @@
package com.ld.igds.protocol.bhzn.grainv1.server;
import com.ld.igds.protocol.bhzn.grainv1.msg.AnalysisService;
import com.ld.igds.protocol.bhzn.grainv1.msg.builder.ReMessageBuilder;
import com.ld.igds.protocol.bhzn.grainv1.msg.message.IoMessage;
import com.ld.igds.util.BytesUtil;
import com.ld.io.api.IoMsgConsumer;
import com.ld.io.api.IoSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 *
 */
@Slf4j
@Service
public class BhznGrainV1MessageConsumer implements IoMsgConsumer {
    @Autowired
    private AnalysisService analysisService;
    /**
     * å¤„理消息
     *
     * @param ioSession
     * @param bytes
     */
    @Override
    public void consume(IoSession ioSession, byte[] bytes) {
        if (null == bytes) {
            log.error("Reply bytes is null");
            return;
        }
        //添加信息心跳标记
        BhznGrainV1ServerUtils.addHeartBeat(ioSession);
        //默认设置主通讯服务
        BhznGrainV1ServerUtils.addSession(ioSession);
        try {
            String hexStr = BytesUtil.bytesToString(bytes);
            log.info("主机返回报文------->>平台:" + hexStr);
            hexStr = hexStr.substring(BhznGrainV1ServerUtils.MSG_START.length());
            IoMessage ioMessage = ReMessageBuilder.getInstance().buildMessage(hexStr);
            ioMessage.setIp(ioSession.getAddress());
            ioMessage.setPort(ioSession.getPort());
            analysisService.analysis(ioSession.getBusinessKey(), ioMessage);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1ServerEngine.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,131 @@
package com.ld.igds.protocol.bhzn.grainv1.server;
import com.ld.igds.util.BytesUtil;
import com.ld.io.api.*;
import com.ld.io.netty.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @Desc: é‚¦æµ·æ™ºèƒ½çº¯ç²®æƒ…协议
 * @author: Andy
 * @update-time: 2023/5/11
 */
@Slf4j
@Service
public class BhznGrainV1ServerEngine {
    public static final Integer PORT = 9309;
    @Autowired
    private BhznGrainV1MessageConsumer defaultMessageConsumer;
    @Autowired
    private BhznGrainV1SessionListener defaultSessionListener;
    // å¿ƒè·³æä¾›
    private static HeartbeatProvider heartbeatProvider = new BhznGrainV1HeartbeatImpl();
    private IoSessionQuery sessionQuery;
    public void start(Integer port) {
        IoServerOption ioServerOption = new IoServerOption();
        if (null != port) {
            ioServerOption.setPort(port);
        } else {
            ioServerOption.setPort(PORT);
        }
        //确认结尾标志
        ioServerOption.setDelimiter(BhznGrainV1ServerUtils.MSG_END.getBytes());
        // é…ç½®ç³»ç»Ÿå¿ƒè·³é—´éš”
        ioServerOption.setReaderIdleTime(5 * 60);
        NettyServer ioServer = new NettyServer(ioServerOption, defaultMessageConsumer, defaultSessionListener, heartbeatProvider);
        ioServer.startup();
        sessionQuery = ioServer.getSessionQuery();
        log.info("* ");
        log.info("* ========================");
        log.info("* ");
        log.info("* [GRAIN-SERVER:BHZN_GRAIN,PORT={}]", PORT);
        log.info("* ");
        log.info("* ========================");
        log.info("* ");
        System.out.println("* ========================");
        System.out.println("* ");
        System.out.println("* [GRAIN-SERVER:BHZN_GRAIN,PORT={}]" + port);
        System.out.println("* ");
        System.out.println("* ========================");
    }
    public IoSessionQuery getSessionQuery() {
        return sessionQuery;
    }
    /**
     * å‘送信息
     *
     * @param ip
     * @param port
     * @param msg
     * @return
     */
    public InvokeResult push(String ip, int port, byte[] msg) {
        IoSessionQuery sessionFactory = getSessionQuery();
        List<IoSession> sessions = sessionFactory.getAllSession();
        IoSession session = null;
        for (IoSession ioSession : sessions) {
            if (BhznGrainV1ServerUtils.getServerKey(ip, port).equals(ioSession.getBusinessKey())) {
                session = ioSession;
                break;
            }
        }
        if (null == session) {
            return InvokeResult.CHANNEL_CLOSED;
        }
        return session.invoke(msg);
    }
//    public InvokeResult push(String ip, int port, String hexStr) {
//
//        byte[] msg = BytesUtil.hexStrToBytes(hexStr);
//
//        IoSessionQuery sessionFactory = getSessionQuery();
//        List<IoSession> sessions = sessionFactory.getAllSession();
//        IoSession session = null;
//        for (IoSession ioSession : sessions) {
//            if (BhznGrainV1ServerUtils.getServerKey(ip, port).equals(ioSession.getBusinessKey())) {
//                session = ioSession;
//                break;
//            }
//        }
//
//        if (null == session) {
//            return InvokeResult.CHANNEL_CLOSED;
//        }
//        return session.invoke(msg);
//    }
    /**
     * ç›´æŽ¥ä½¿ç”¨å†…存的Session执行
     */
    public InvokeResult pushByMin(String hexStr) {
        IoSession session = BhznGrainV1ServerUtils.getSession();
        if (null == session) {
            return InvokeResult.CHANNEL_CLOSED;
        }
        byte[] msg = BytesUtil.hexStrToBytes(hexStr);
        return session.invoke(msg);
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1ServerUtils.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,103 @@
package com.ld.igds.protocol.bhzn.grainv1.server;
import com.ld.igds.util.BytesUtil;
import com.ld.io.api.IoSession;
import java.util.HashMap;
import java.util.Map;
/**
 * å·¥å…·ç±»
 *
 * @author vince
 */
public class BhznGrainV1ServerUtils {
    /**
     * è®°å½•每个连接的最后一次信息时间 key = è¿žæŽ¥çš„KYE,data =当前时间戳
     */
    public static Map<String, Long> contextMapHeart = new HashMap<>();
    public static Map<String, IoSession> contextIoSession = new HashMap<>();
    public static int HEART_BEAT_TIME = 30;//心跳间隔时间
    public static String MSG_START = "3C42485A4E3E";//<BHZN>
    public static String MSG_START2 = "AA";
    public static String MSG_END = "<END>";//<END>
    public static String MSG_END_16 = "3C454E443E";//<END>
    public static final String CHARSET = "UTF-8";
    /**
     * é’ˆå¯¹æ— çº¿ç²®æƒ…主机的默认ID配置
     */
    public static String DEFAULT_MAC_ID = "53681";
    public static String FUNCTION_ID_00 = "00";
    public static String FUNCTION_ID_F1 = "F1";
    public static String FUNCTION_ID_F2 = "F2";
    public static String FUNCTION_ID_83 = "83";
    public static String FUNCTION_ID_93 = "93";
    public static String FUNCTION_ID_92 = "92";
    /**
     * ç”ŸæˆTCP连接的KEY
     *
     * @param ip
     * @param port
     * @return
     */
    public static String getServerKey(String ip, Integer port) {
        return ip + ":" + port;
    }
    /**
     * æ·»åŠ æœ€æ–°å¿ƒè·³æ—¶é—´æˆ³
     *
     * @param session
     */
    public static void addHeartBeat(IoSession session) {
        contextMapHeart.put(getServerKey(session.getAddress(), session.getPort()), System.currentTimeMillis());
    }
    public static Long getHearBeat(IoSession session) {
        return contextMapHeart.get(getServerKey(session.getAddress(), session.getPort()));
    }
    /**
     * è®¡ç®—校验
     *
     * @param content
     * @return
     */
    public static String getCheck(String content) {
        int start = BhznGrainV1ServerUtils.MSG_START.length() + BhznGrainV1ServerUtils.MSG_START2.length();
        content = content.substring(start);
        int sum = 0;
        String hex;
        for (int i = 0; i < content.length() / 2; i++) {
            hex = content.substring(i * 2, i * 2 + 2);
            sum += BytesUtil.hexToInt(hex);
        }
        String hexSum = BytesUtil.intToHexStr(sum);
        int check = BytesUtil.hexToInt(hexSum.substring(hexSum.length() - 2));
        return BytesUtil.intToHexStr(256 - check).substring(2);
    }
    public static void addSession(IoSession session) {
        contextIoSession.put(DEFAULT_MAC_ID, session);
    }
    public static IoSession getSession() {
        return contextIoSession.get(DEFAULT_MAC_ID);
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv1/server/BhznGrainV1SessionListener.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,68 @@
package com.ld.igds.protocol.bhzn.grainv1.server;
import com.ld.igds.common.CoreSerService;
import com.ld.igds.constant.Constant;
import com.ld.igds.models.DeviceSer;
import com.ld.igds.util.ContextUtil;
import com.ld.io.api.IoSession;
import com.ld.io.api.IoSessionListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 *
 */
@Slf4j
@Service
public class BhznGrainV1SessionListener implements IoSessionListener {
    @Autowired
    private CoreSerService coreSerService;
    /**
     * è®¾å¤‡åˆ›å»ºåœ¨çº¿ï¼Œéœ€è¦æ³¨æ„å½“前使用主机模式,主机上线默认所有相同SN配置的分机全部上线
     *
     * @param session
     */
    @Override
    public void onCreate(IoSession session) {
        //添加到内存
        BhznGrainV1ServerUtils.addSession(session);
        log.info("++++新建连接++++-IP={},PORT={}", session.getAddress(), session.getPort());
        // æ·»åŠ è‡ªå®šä¹‰ä¸šåŠ¡ID
        session.setBusinessKey(BhznGrainV1ServerUtils.getServerKey(session.getAddress(), session.getPort()));
        //项目采用无线主机模式,直接获取默认设备
        DeviceSer deviceSer = coreSerService.getCacheSer(ContextUtil.getDefaultCompanyId(), BhznGrainV1ServerUtils.DEFAULT_MAC_ID);
        if (null == deviceSer) return;
        coreSerService.onlineBySn(session.getAddress(), session.getPort(), deviceSer.getSn(), Constant.YN_Y);
        //更新缓存
        coreSerService.refreshCache(deviceSer.getCompanyId());
    }
    /**
     * æ³¨æ„ï¼Œå½“前采用主机模式,主机离线所有相同SN配置的分机全部离线
     *
     * @param session
     */
    @Override
    public void onDestroy(IoSession session) {
        log.info("----连接断开-----IP={},PORT={}", session.getAddress(), session.getPort());
        //项目采用无线主机模式,直接获取默认设备
        DeviceSer deviceSer = coreSerService.getCacheSer(ContextUtil.getDefaultCompanyId(), BhznGrainV1ServerUtils.DEFAULT_MAC_ID);
        if (null == deviceSer) return;
        //由于设备掉线后自动调整
//        coreSerService.onlineBySn(session.getAddress(), session.getPort(), deviceSer.getSn(), Constant.YN_N);
//        //更新缓存
//        coreSerService.refreshCache(deviceSer.getCompanyId());
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/RemoteGrainV2ServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,70 @@
package com.ld.igds.protocol.bhzn.grainv2;
import com.ld.igds.common.CoreSerService;
import com.ld.igds.io.RemoteGrainService;
import com.ld.igds.io.constant.OrderRespEnum;
import com.ld.igds.io.constant.ProtocolEnum;
import com.ld.igds.io.request.CheckGrainRequest;
import com.ld.igds.io.response.GrainResponse;
import com.ld.igds.protocol.bhzn.grainv2.msg.builder.CommandBuild;
import com.ld.igds.protocol.bhzn.grainv2.server.BhznGrainV2ServerEngine;
import com.ld.io.api.InvokeResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * @Desc: ç²®æƒ…业务接口
 * @author: Andy
 * @update-time: 2023/5/11
 */
@Slf4j
@Component(RemoteGrainV2ServiceImpl.BEAN_ID)
public class RemoteGrainV2ServiceImpl implements RemoteGrainService {
    public static final String BEAN_ID = "bhznGrainv2.remoteGrainService";
    @Autowired
    private CoreSerService coreSerService;
    @Autowired
    private BhznGrainV2ServerEngine bhznGrainServerEngine;
    @Override
    public String getProtocol() {
        return ProtocolEnum.TCP_BHZH_GRAIN_V2.getCode();
    }
    @Override
    public GrainResponse checkGrain(CheckGrainRequest request) {
        try {
            // ç”Ÿæˆç²®æƒ…信息
            String hexStr = CommandBuild.getInstance().getMsgCheck(request.getSerId(), request.getDepotId());
//            //通讯使用的是主机通讯
//            DeviceSer mainSer = coreSerService.getCacheSer(ContextUtil.getDefaultCompanyId(), BhznGrainV1ServerUtils.DEFAULT_MAC_ID);
//            request.setIp(mainSer.getIp());
//            request.setPort(mainSer.getPort());
            // å‘送命令
            InvokeResult result = bhznGrainServerEngine.pushByMin(hexStr);
            log.error("平台------>>>>控制柜:粮情检测-{}", hexStr);
            // å°è£…返回信息
            if (InvokeResult.SUCCESS == result) {
                return new GrainResponse(OrderRespEnum.ORDER_SUCCESS.getCode(),
                        "粮情粮情发送成功!");
            } else {
                log.error("平台------>>>>控制柜:粮情检测-失败{}", result.getMessage());
                return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(),
                        "命令发送异常:" + result.getMessage());
            }
        } catch (Exception e) {
            log.error("粮情检测异常:{}", e);
            return new GrainResponse(OrderRespEnum.ORDER_ERROR.getCode(), "后端异常:" + e.getMessage());
        }
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/ServerRunner.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,34 @@
package com.ld.igds.protocol.bhzn.grainv2;
import com.ld.igds.data.ConfigData;
import com.ld.igds.protocol.bhzn.grainv2.server.BhznGrainV2ServerEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
 * é…ç½®éšç³»ç»Ÿè‡ªåŠ¨å¯åŠ¨æœåŠ¡ -- æ‰§è¡Œé¡ºåº20-29
 */
@Component(ServerRunner.BEAN_ID)
@Order(value = 24)
public class ServerRunner implements CommandLineRunner {
    public static final String BEAN_ID = "bhzn.serverRunnerV2";
    @Autowired
    private ConfigData configData;
    @Autowired
    private BhznGrainV2ServerEngine bhznGrainServerEngine;
    @Override
    public void run(String... strings) throws Exception {
        if (configData.getActive().indexOf("pro") >= 0) {
            bhznGrainServerEngine.start(BhznGrainV2ServerEngine.PORT);
        }
        if (configData.getActive().indexOf("dev") >= 0) {
            bhznGrainServerEngine.start(BhznGrainV2ServerEngine.PORT);
        }
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/AnalysisService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,474 @@
package com.ld.igds.protocol.bhzn.grainv2.msg;
import com.ld.igds.common.CoreCommonService;
import com.ld.igds.common.CoreSerService;
import com.ld.igds.common.dto.THDto;
import com.ld.igds.constant.BizType;
import com.ld.igds.constant.Constant;
import com.ld.igds.grain.GrainUtil;
import com.ld.igds.grain.dto.GrainItemInfo;
import com.ld.igds.io.notify.NotifyGrainInvoker;
import com.ld.igds.models.DepotConf;
import com.ld.igds.models.DeviceSer;
import com.ld.igds.models.DicSysConf;
import com.ld.igds.models.Grain;
import com.ld.igds.order.ExeOrderService;
import com.ld.igds.order.data.ExeRequest;
import com.ld.igds.protocol.bhzn.grainv1.server.BhznGrainV1ServerUtils;
import com.ld.igds.protocol.bhzn.grainv2.msg.builder.CommandBuild;
import com.ld.igds.protocol.bhzn.grainv2.msg.builder.ReMessageBuilder;
import com.ld.igds.protocol.bhzn.grainv2.msg.message.IoMessage;
import com.ld.igds.protocol.bhzn.grainv2.server.BhznGrainV2ServerEngine;
import com.ld.igds.util.BytesUtil;
import com.ld.igds.util.ContextUtil;
import com.ld.igds.warn.WarnUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
/**
 * åè®®è§£æž
 *
 * @author vince
 */
@Slf4j
@Component(AnalysisService.BEAN_ID)
public class AnalysisService {
    /**
     * é’ˆå¯¹åˆ†åŒ…粮情报文进行封装
     */
    public static Map<String, String> contextMapGrain = new HashMap<>();
    /**
     * ç”¨äºŽå­˜æ”¾è¿”回的仓温仓湿信息
     */
    public static Map<String, THDto> contextMapTH = new HashMap<>();
    public static final String BEAN_ID = "bhznGrainv2.analysisService";
    @Autowired
    private CoreSerService coreSerService;
    @Autowired
    private BhznGrainV2ServerEngine serverEngine;
    @Autowired
    private CoreCommonService commonService;
    @Autowired
    private NotifyGrainInvoker notifyGrainInvoker;
    @Autowired
    private GrainUtil grainUtil;
    @Autowired
    private WarnUtils warnUtils;
    @Autowired
    private ExeOrderService exeOrderService;
    /**
     * @param sessionKey ip:port
     */
    public void analysis(String sessionKey, IoMessage message) throws Exception {
        //注册
        if (BhznGrainV1ServerUtils.FUNCTION_ID_F1.equals(message.getFunctionId())) {
            //DO NOTHING
            log.info("主机------->>平台:注册信息报文={}", message);
            DeviceSer ser = coreSerService.getCacheSerBySn(ContextUtil.getDefaultCompanyId(),message.getAddr());
            if(ser!= null ){
                ser.setIp(message.getIp());
                ser.setPort(message.getPort());
                ser.setStatus(Constant.YN_Y);
                coreSerService.updateByData(ser);
            }
            return;
        }
        //心跳
        if (BhznGrainV1ServerUtils.FUNCTION_ID_F2.equals(message.getFunctionId())) {
            //String hexStr = CommandBuild.getMsgHeartReply(message.getAddr());
            //log.info("平台--------->>>主机,返回心跳收到信息,报文={}", hexStr);
           // serverEngine.pushByMin(hexStr);
            return;
        }
        // 93 è§£æžä»“温仓湿,并返回收到报文
        if (BhznGrainV1ServerUtils.FUNCTION_ID_93.equals(message.getFunctionId())) {
            log.info("主机------->>平台:温湿度信息报文={}", message);
            analysisTh(message);
            return;
        }
        // 92 è§£æžç²®æ¸©ï¼Œå¹¶è¿”回收到报文
        if (BhznGrainV1ServerUtils.FUNCTION_ID_92.equals(message.getFunctionId())) {
            log.info("主机------->>平台:粮情信息报文={}", message);
            analysisGrain(message);
        }
    }
    private void analysisGrain(IoMessage message) {
        try {
            //根据分机地址获取分机信息
            DeviceSer ser = coreSerService.getCacheSer(ContextUtil.getDefaultCompanyId(), message.getAddr());
            if (ser == null) {
                replayGrain(message);
                log.error("主机-------->>平台,解析粮情失败,未获取到系统粮情主机配置:" + message.getAddr());
                return;
            }
            // é¦–先获取到系统参数,判断是否需要批次自动优化
            DicSysConf sysConf = commonService.getCacheSysConf(ser.getCompanyId());
            List<ExeRequest> list = exeOrderService.getInProgressOrderBySerId(BizType.GRAIN.getCode(), ser.getId());
            if (null == list || list.isEmpty()) {
                String info = "粮情解析失败:分机=" + ser.getName() + "没有获取到所属仓库信息。";
                log.error("分机------>>>平台:" + info);
                return;
            }
            //获取针对当前仓库的命令
            ExeRequest exeRequest = list.get(0);
            if (null == exeRequest) {
                String info = "粮情解析失败:分机=" + ser.getName() + "没有获取历史命令。";
                log.error("分机------>>>平台:" + info);
                return;
            }
            DepotConf depotConf = commonService.getCacheDepotConf(exeRequest.getCompanyId(), exeRequest.getDepotId());
            if (null == depotConf) {
                String info = "粮情解析失败:分机=" + ser.getName() + "没有获取到粮情参数配置信息。";
                log.error("分机------>>>平台:" + info);
                return;
            }
            // ç²®æƒ…的批次号重新根据频率调整
            String batchId = ContextUtil.getBatchIdByFireq(depotConf.getGrainFreq());
            // åˆ¤æ–­æ•°æ®æœ‰æ²¡æœ‰æ”¶å–完整
            String[] attCable = depotConf.getCableRule().split("-");
            int cableZ = Integer.valueOf(attCable[0]);
            int cableY = Integer.valueOf(attCable[1]);
            int cableX = Integer.valueOf(attCable[2]);
            int sumPoint = cableZ * cableY * cableX;
            //获取当前粮情温度报文
            String grainHex = message.getContent().substring(16);
            //当前报文温度点数
            int curPoint = BytesUtil.hexToInt(BytesUtil.tran_LH(message.getContent().substring(4, 8)));
            //如果当前包的数据个数大于等于当前仓库的配置点位则表示单包返回
            if (curPoint >= sumPoint) {
                //返回粮情接收信息
                replayGrain(message);
                analysisGrain2(ser, message, exeRequest, depotConf, sysConf, batchId, grainHex);
                return;
            }
            //表示分包传递
            String key = "GRAIN_" + message.getAddr();
            String oldGrainHex = contextMapGrain.get(key) == null ? "" : contextMapGrain.get(key);
            //获取当前包起始点的层行列
            int hang = BytesUtil.hexToInt(BytesUtil.tran_LH(message.getContent().substring(8, 10)));
            int lie = BytesUtil.hexToInt(BytesUtil.tran_LH(message.getContent().substring(10, 12)));
            int ceng = BytesUtil.hexToInt(BytesUtil.tran_LH(message.getContent().substring(12, 14)));
            if (hang > 0 || lie > 0 || ceng > 0) {
                //说明非第一包数据
                grainHex = oldGrainHex + grainHex;
            }
            if (grainHex.length() >= sumPoint * 4) {
                //返回粮情接收信息
                replayGrain(message);
                analysisGrain2(ser, message, exeRequest, depotConf, sysConf, batchId, grainHex);
                return;
            } else {
                contextMapGrain.put(key, grainHex);
                replayGrain(message);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    /**
     * è¿”回粮情收到报文信息,需要注意:如果存在分包情况下,需要等所有包收到后返回
     *
     * @param message
     */
    private void replayGrain(IoMessage message) {
        String hexStr = CommandBuild.getMsgGrainReply(message.getAddr());
        log.info("平台--------->>>主机,返回粮情报文收到信息,报文={}", hexStr);
        serverEngine.pushByMin(hexStr);
    }
    private void analysisGrain2(DeviceSer ser, IoMessage message, ExeRequest exeRequest, DepotConf depotConf, DicSysConf sysConf, String batchId, String grainStr) {
        // èŽ·å–å®Œæ•´çš„ç²®æƒ…åŒ…ä¿¡æ¯
        String[] attCable = depotConf.getCableRule().split("-");
        int cableZ = Integer.valueOf(attCable[0]);
        int cableY = Integer.valueOf(attCable[1]);
        int cableX = Integer.valueOf(attCable[2]);
        // æ ¹æ®å±‚行列获取指定长度
        int start = 4 * (depotConf.getCableStart() - ser.getCableStart())
                * cableZ * cableY;
        int len = 4 * cableZ * cableY * cableX;
        log.info("分机------>>>平台:返回粮情完整信息,所属组织={},分机={}", ser.getCompanyId(), ser.getName());
        String strPoints = grainStr.substring(start, start + len);
        // å°†ç²®æƒ…解析成数组
        List<Double> temps = new ArrayList<>();
        double tempValue;
        String temp;
        for (int i = 0; i < strPoints.length() / 4; i++) {
            temp = strPoints.substring(i * 4, i * 4 + 4);
            if (temp == null) {
                temp = "0000";
            }
            if (ReMessageBuilder.ERROR_TAG.equals(temp)) {
                tempValue = Constant.ERROR_TEMP;
            } else {
                tempValue = BytesUtil.hexToInt(BytesUtil.tran_LH(temp)) / 10.0;
            }
            // æ•…障值处理
            if (tempValue >= ReMessageBuilder.FAULT_CHECK_TAG) {
                tempValue = Constant.FAULT_TEMP;
            }
            temps.add(tempValue);
        }
        log.debug("-------CheckGrainRequest--={}", exeRequest.toString());
        THDto thDto = this.getTH(message);
        if (null != thDto) {
            log.debug("-------THDto--={}", thDto.toString());
        }
        //清空
        String key = "GRAIN_" + message.getAddr();
        contextMapGrain.put(key, null);
        // å°†é›†åˆè§£æžæˆåæ ‡æ•°æ®
        addPoint1(temps, depotConf, ser, exeRequest, thDto, sysConf, batchId);
    }
    /**
     * å¹³æˆ¿ä»“,解析第二步,解析到坐标数据
     *
     * @param temps
     * @throws Exception
     */
    private void addPoint1(List<Double> temps,
                           DepotConf depotConf, DeviceSer ser, ExeRequest exeRequest,
                           THDto thDto, DicSysConf sysConf, String batchId) {
        //根据电缆起始方位和布线方向,对粮情数据进行调整
        if (null != depotConf.getStartOrientation()) {
            temps = reversalGrainPoint(temps, depotConf);
        }
        //若起点点位为底部,则将粮情数据进行翻转
        if (null != depotConf.getStartPoint()
                && Constant.GRAIN_START_POINT_BELOW.equals(depotConf.getStartPoint())) {
            temps = grainUtil.reversalUpAndDown(temps, depotConf.getCableRule());
        }
        String[] attCable = depotConf.getCableRule().split("-");
        int cableZ = Integer.valueOf(attCable[0]);
        int cableY = Integer.valueOf(attCable[1]);
        int cableX = Integer.valueOf(attCable[2]);
        Grain grain = new Grain();
        grain.setDepotId(depotConf.getDepotId());
        grain.setCompanyId(depotConf.getCompanyId());
        grain.setCable(depotConf.getCableRule());
        grain.setBatchId(batchId);
        grain.setTempIn(Constant.ERROR_TEMP);
        grain.setHumidityIn(Constant.ERROR_TEMP);
        if (null != thDto) {
            log.debug("粮情解析中获取到的温湿度信息={}", thDto.toString());
            grain.setHumidityIn(thDto.getHumidityIn());
            grain.setTempIn(thDto.getTempIn());
        }
        grain.setReceiveDate(new Date());
        grain.setRemark("粮温正常");
        // èŽ·å–ç¼“å­˜ä¸­çš„å‘½ä»¤ä¿¡æ¯
        grain.setCheckUser(exeRequest.getExeUser());
        double max = ReMessageBuilder.MAX_TEMP, min = ReMessageBuilder.MIN_TEMP, sumT = 0.0, sumNum = cableX
                * cableY * cableZ;
        // æ ¡éªŒå’Œå®žçŽ°ç»Ÿè®¡ï¼Œç”Ÿæˆé‡‡é›†ç‚¹ä¿¡æ¯
        List<GrainItemInfo> listGrainItems = new ArrayList<>();
        int i = 1;
        for (Double temp : temps) {
            if (temp == Constant.ERROR_TEMP || temp == Constant.FAULT_TEMP || temp == Constant.ADD_TEMP) {
                sumNum--;
            } else {
                sumT += temp;
                if (temp > max) {
                    max = temp;
                }
                if (temp < min) {
                    min = temp;
                }
            }
            listGrainItems.add(new GrainItemInfo(i, temp));
            i++;
        }
        if (sumNum == 0) {
            sumNum = 1;
            grain.setRemark("当前粮情采集异常");
        }
        //过滤比较用的最大最小值
        if (max == ReMessageBuilder.MAX_TEMP) {
            max = 0.0;
        }
        if (min == ReMessageBuilder.MIN_TEMP) {
            min = 0.0;
        }
        if (null != depotConf.getTempMax() && max > depotConf.getTempMax()) {
            grain.setRemark("仓库配置高温警告值:" + depotConf.getTempMax() + ",当前检测高温值:"
                    + max);
            warnUtils.addGrainWarn(depotConf, grain);
        }
        grain.setTempAve(sumT / sumNum);
        grain.setTempMax(max);
        grain.setTempMin(min);
        grain.setPoints(org.apache.commons.lang3.StringUtils.join(temps, ","));
        String depotIds = exeRequest.getDepotIds();
        boolean notifyWeb = true;
        if (null != depotIds && depotIds.indexOf(depotConf.getDepotId()) == -1) {
            notifyWeb = false;
        }
        // ç”¨æˆ·å°è£…好数据即可
        notifyGrainInvoker.analysisSuccess(grain, listGrainItems, depotConf,
                sysConf, notifyWeb, exeRequest);
    }
    private List<Double> reversalGrainPoint(List<Double> temps, DepotConf conf) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartOrientation())) {
            //若起始方位为空,则默认起始方位和方向,直接返回
            return temps;
        }
        //起始方位为右边时
        if (Constant.GRAIN_START_ORIENTATION_RIGHT.equals(conf.getStartOrientation())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartDirection())) {
                //右边起始,默认纵向布线,直接返回
                return temps;
            }
            if (Constant.GRAIN_START_DIRECTION_TRANSVERSE.equals(conf.getStartDirection())) {
                //右边起始,横向布线
                return grainUtil.reversalRight1(temps, conf.getCableRule());
            }
            //右边起始,默认纵向布线,直接返回
            return temps;
        }
        //起始方位为右上时
        if (Constant.GRAIN_START_ORIENTATION_RIGHT_UP.equals(conf.getStartOrientation())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartDirection())) {
                //右上起始,默认纵向布线
                return grainUtil.reversalRightUp2(temps, conf.getCableRule());
            }
            if (Constant.GRAIN_START_DIRECTION_TRANSVERSE.equals(conf.getStartDirection())) {
                //右上起始,横向布线
                return grainUtil.reversalRightUp1(temps, conf.getCableRule());
            }
            //右上起始,默认纵向布线
            return grainUtil.reversalRightUp2(temps, conf.getCableRule());
        }
        //起始方位为左边时
        if (Constant.GRAIN_START_ORIENTATION_LEFT.equals(conf.getStartOrientation())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartDirection())) {
                //左边起始,默认纵向布线
                return grainUtil.reversalLeft2(temps, conf.getCableRule());
            }
            if (Constant.GRAIN_START_DIRECTION_TRANSVERSE.equals(conf.getStartDirection())) {
                //左边起始,横向布线
                return grainUtil.reversalLeft1(temps, conf.getCableRule());
            }
            //左边起始,默认纵向布线
            return grainUtil.reversalLeft2(temps, conf.getCableRule());
        }
        //起始方位为左上时
        if (Constant.GRAIN_START_ORIENTATION_LEFT_UP.equals(conf.getStartOrientation())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(conf.getStartDirection())) {
                //左上起始,默认纵向布线
                return grainUtil.reversalLeftUp2(temps, conf.getCableRule());
            }
            if (Constant.GRAIN_START_DIRECTION_TRANSVERSE.equals(conf.getStartDirection())) {
                //左上起始,横向布线
                return grainUtil.reversalLeftUp1(temps, conf.getCableRule());
            }
            //左上起始,默认纵向布线
            return grainUtil.reversalLeftUp2(temps, conf.getCableRule());
        }
        return temps;
    }
    private void analysisTh(IoMessage message) {
        try {
            THDto th = new THDto();
            th.setCompanyId(ContextUtil.getDefaultCompanyId());
            String data = message.getContent();
            String houseNo = data.substring(0, 2);
            String t = data.substring(4, 8);
            String h = data.substring(8, 12);
            double temp, humy;
            if (ReMessageBuilder.ERROR_TAG.equals(t)) {
                temp = 0.0;
            } else {
                temp = (double) BytesUtil.hexToBigInt(BytesUtil.tran_LH(t)) / 10;
            }
            if (ReMessageBuilder.ERROR_TAG.equals(h)) {
                humy = 0.0;
            } else {
                humy = (double) BytesUtil.hexToBigInt(BytesUtil.tran_LH(h)) / 10;
            }
            th.setTempIn(temp);
            th.setHumidityIn(humy);
            log.info("主机--------->>>平台,解析仓温仓湿信息,仓库={},结果={}", houseNo, th.toString());
            String key = "TH_" + houseNo;
            contextMapTH.put(key, th);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            String hexStr = CommandBuild.getMsgTHReply(message.getAddr());
            log.info("平台--------->>>主机,返回仓温仓湿收到信息,报文={}", hexStr);
            serverEngine.pushByMin(hexStr);
        }
    }
    private THDto getTH(IoMessage message) {
        String data = message.getContent();
        String houseNo = data.substring(0, 2);
        String key = "TH_" + houseNo;
        return contextMapTH.get(key);
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/builder/CommandBuild.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,178 @@
package com.ld.igds.protocol.bhzn.grainv2.msg.builder;
import com.ld.igds.protocol.bhzn.grainv1.server.BhznGrainV1ServerUtils;
import com.ld.igds.util.BytesUtil;
/**
 * å‘½ä»¤ç”Ÿæˆ
 *
 * @author vince
 */
public class CommandBuild {
    private final static CommandBuild instance = new CommandBuild();
    private CommandBuild() {
    }
    public static CommandBuild getInstance() {
        return instance;
    }
    /**
     * PC回复 å¿ƒè·³å•Š æ”¶åˆ°ä¿¡æ¯
     *
     * @param grainAddr
     * @return
     */
    public static String getMsgHeartReply(String grainAddr) {
        StringBuffer sb = new StringBuffer();
        //开始符号
        sb.append(BhznGrainV1ServerUtils.MSG_START);
        sb.append(BhznGrainV1ServerUtils.MSG_START2);
        //分机地址
        int i = Integer.parseInt(grainAddr);
        sb.append(BytesUtil.tran_LH(BytesUtil.intToHexStr(i)));
        //发送方地址
        sb.append("0000");
        //命令ID
        sb.append(BhznGrainV1ServerUtils.FUNCTION_ID_F2);
        //数据长度-01
        sb.append("01");
        //数据区--任意值
        sb.append("01");
        //获取校验码
        sb.append(BhznGrainV1ServerUtils.getCheck(sb.toString()));
        //结尾符
        sb.append(BhznGrainV1ServerUtils.MSG_END_16);
        return sb.toString();
    }
    /**
     * ç²®æƒ…采集命令
     *
     * @param grainAddr ç²®æƒ…分机地址
     * @param deptId    ä»“库编号地址
     * @return
     */
    public static String getMsgCheck(String grainAddr, String deptId) {
        StringBuffer sb = new StringBuffer();
        //开始符号
        sb.append(BhznGrainV1ServerUtils.MSG_START);
        sb.append(BhznGrainV1ServerUtils.MSG_START2);
        //分机地址
        int i = Integer.parseInt(grainAddr);
        sb.append(BytesUtil.tran_LH(BytesUtil.intToHexStr(i)));
        //发送方地址
        sb.append("0000");
        //命令ID
        sb.append(BhznGrainV1ServerUtils.FUNCTION_ID_83);
        //数据长度-01
        sb.append("01");
        //数据区--主机里面配置的仓库编码
        i = Integer.parseInt(deptId);
        sb.append(BytesUtil.intToHexStr1(i));
        //获取校验码
        sb.append(BhznGrainV1ServerUtils.getCheck(sb.toString()));
        //结尾符
        sb.append(BhznGrainV1ServerUtils.MSG_END_16);
        return sb.toString();
    }
    /**
     * PC回复 ä»“温仓湿 æ”¶åˆ°ä¿¡æ¯
     *
     * @param grainAddr
     * @return
     */
    public static String getMsgTHReply(String grainAddr) {
        StringBuffer sb = new StringBuffer();
        //开始符号
        sb.append(BhznGrainV1ServerUtils.MSG_START);
        sb.append(BhznGrainV1ServerUtils.MSG_START2);
        //分机地址
        int i = Integer.parseInt(grainAddr);
        sb.append(BytesUtil.tran_LH(BytesUtil.intToHexStr(i)));
        //发送方地址
        sb.append("0000");
        //命令ID
        sb.append(BhznGrainV1ServerUtils.FUNCTION_ID_93);
        //数据长度-01
        sb.append("01");
        //数据区--任意值
        sb.append("01");
        //获取校验码
        sb.append(BhznGrainV1ServerUtils.getCheck(sb.toString()));
        //结尾符
        sb.append(BhznGrainV1ServerUtils.MSG_END_16);
        return sb.toString();
    }
    /**
     * PC回复粮温收到信息
     *
     * @param grainAddr
     * @return
     */
    public static String getMsgGrainReply(String grainAddr) {
        StringBuffer sb = new StringBuffer();
        //开始符号
        sb.append(BhznGrainV1ServerUtils.MSG_START);
        sb.append(BhznGrainV1ServerUtils.MSG_START2);
        //分机地址
        int i = Integer.parseInt(grainAddr);
        sb.append(BytesUtil.tran_LH(BytesUtil.intToHexStr(i)));
        //发送方地址
        sb.append("0000");
        //命令ID
        sb.append(BhznGrainV1ServerUtils.FUNCTION_ID_92);
        //数据长度-01
        sb.append("01");
        //数据区--任意值
        sb.append("01");
        //获取校验码
        sb.append(BhznGrainV1ServerUtils.getCheck(sb.toString()));
        //结尾符
        sb.append(BhznGrainV1ServerUtils.MSG_END_16);
        return sb.toString();
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/builder/ReMessageBuilder.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,51 @@
package com.ld.igds.protocol.bhzn.grainv2.msg.builder;
import com.ld.igds.protocol.bhzn.grainv2.msg.message.IoMessage;
import com.ld.igds.util.BytesUtil;
/**
 * æ ¹æ®æŽ¥æ”¶åˆ°çš„信息进行封装
 *
 * @author vince
 */
public class ReMessageBuilder {
    public final static String ERROR_TAG = "3CF6";
    public static double FAULT_CHECK_TAG = 85.0;
    public static double MAX_TEMP = -50.0;
    public static double MIN_TEMP = 50.0;
    private final static ReMessageBuilder instance = new ReMessageBuilder();
    private ReMessageBuilder() {
    }
    public static ReMessageBuilder getInstance() {
        return instance;
    }
    /**
     * @param message
     * @return
     */
    public IoMessage buildMessage(String message) throws Exception {
        IoMessage ioMessage = new IoMessage();
        //转换为数字,高低位转换(4位)
        int i = BytesUtil.hexToBigInt(BytesUtil.tran_LH(message.substring(2, 6)));
        ioMessage.setPcAddr(i + "");
        i = BytesUtil.hexToBigInt(BytesUtil.tran_LH(message.substring(6, 10)));//高低位转换(4位)
        ioMessage.setAddr(i + "");
        ioMessage.setFunctionId(message.substring(10, 12));//功能码(2位),不用高低位转换
        i = BytesUtil.hexToBigInt(message.substring(12, 14));//长度(1位)
        ioMessage.setLength(i);
        //获取消息体
        ioMessage.setContent(message.substring(14, 14 + (i * 2)));
        ioMessage.setCheck(message.substring(message.length() - 2));
        return ioMessage;
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/message/Content.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,43 @@
package com.ld.igds.protocol.bhzn.grainv2.msg.message;
import lombok.Data;
/**
 * @author vince.xu
 * @Title: Content
 * @ProjectName igds-35
 * @Description: TODO
 * @date 2022-12-715:48
 */
@Data
public class Content {
    /**
     * çŠ¶æ€åå›ž
     */
    public  String result;
    /**
     * çº¯åº¦
     */
    public String purity;
    /**
     * æµé‡
     */
    public String flow;
    /**
     * åŽ‹åŠ›
     */
    public String pressure;
    /**
     * æ¸©åº¦
     */
    public String temperature;
    /**
     * æµé‡ç´¯è®¡
     */
    public String flowAll;
    /**
     * è¿è¡ŒçŠ¶æ€
     */
    public String isRun;
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/msg/message/IoMessage.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,20 @@
package com.ld.igds.protocol.bhzn.grainv2.msg.message;
import lombok.Data;
@Data
public class IoMessage {
    private String ip;
    private int port;
    private String pcAddr;
    private String addr;
    private String functionId;
    private int length;
    private String content;
    private String check;
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/package-info.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,4 @@
/**
 * é‚¦æµ·æœ‰çº¿çº¯ç²®æƒ…协议
 */
package com.ld.igds.protocol.bhzn.grainv2;
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2HeartbeatImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,42 @@
package com.ld.igds.protocol.bhzn.grainv2.server;
import com.ld.io.api.HeartbeatProvider;
import com.ld.io.api.IoSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
 * æä¾›å¿ƒè·³ä¿¡æ¯
 *
 * @author Andy
 */
@Slf4j
@Service
public class BhznGrainV2HeartbeatImpl implements HeartbeatProvider {
    @Override
    public byte[] provide(IoSession session) {
        //直接根据主机SESSIOn判断
        IoSession session1 = BhznGrainV2ServerUtils.getSession();
        Long lastBeatTime = BhznGrainV2ServerUtils.getHearBeat(session1);
        if (null == lastBeatTime) {
            return null;
        }
        //如果最后一次终端心跳时间距离当前时间大于 ç»ˆç«¯å¿ƒè·³æ—¶é—´çš„3次,则判断为离线
        long deTime = System.currentTimeMillis() - lastBeatTime;
        if (deTime > (BhznGrainV2ServerUtils.HEART_BEAT_TIME * 3 * 1000)) {
            log.info("-----------超过{}秒未获取到心跳信息,判定终端离线,踢出连接------------{}-{}", deTime, session.getAddress(), session.getPort());
            session.destroy();
        }
        return null;
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2MessageConsumer.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,57 @@
package com.ld.igds.protocol.bhzn.grainv2.server;
import com.ld.igds.protocol.bhzn.grainv2.msg.AnalysisService;
import com.ld.igds.protocol.bhzn.grainv2.msg.builder.ReMessageBuilder;
import com.ld.igds.protocol.bhzn.grainv2.msg.message.IoMessage;
import com.ld.igds.util.BytesUtil;
import com.ld.io.api.IoMsgConsumer;
import com.ld.io.api.IoSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 *
 */
@Slf4j
@Service
public class BhznGrainV2MessageConsumer implements IoMsgConsumer {
    @Autowired
    private AnalysisService analysisService;
    /**
     * å¤„理消息
     *
     * @param ioSession
     * @param bytes
     */
    @Override
    public void consume(IoSession ioSession, byte[] bytes) {
        if (null == bytes) {
            log.error("Reply bytes is null");
            return;
        }
        //添加信息心跳标记
        BhznGrainV2ServerUtils.addHeartBeat(ioSession);
        //默认设置主通讯服务
        BhznGrainV2ServerUtils.addSession(ioSession);
        try {
            String hexStr = BytesUtil.bytesToString(bytes);
            log.info("【"+ioSession.getAddress()+"】主机返回报文------->>平台:" + hexStr);
            hexStr = hexStr.substring(BhznGrainV2ServerUtils.MSG_START.length());
            IoMessage ioMessage = ReMessageBuilder.getInstance().buildMessage(hexStr);
            ioMessage.setIp(ioSession.getAddress());
            ioMessage.setPort(ioSession.getPort());
            analysisService.analysis(ioSession.getBusinessKey(), ioMessage);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2ServerEngine.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,131 @@
package com.ld.igds.protocol.bhzn.grainv2.server;
import com.ld.igds.util.BytesUtil;
import com.ld.io.api.*;
import com.ld.io.netty.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @Desc: é‚¦æµ·æ™ºèƒ½çº¯ç²®æƒ…协议
 * @author: Andy
 * @update-time: 2023/5/11
 */
@Slf4j
@Service
public class BhznGrainV2ServerEngine {
    public static final Integer PORT = 9309;
    @Autowired
    private BhznGrainV2MessageConsumer defaultMessageConsumer;
    @Autowired
    private BhznGrainV2SessionListener defaultSessionListener;
    // å¿ƒè·³æä¾›
    private static HeartbeatProvider heartbeatProvider = new BhznGrainV2HeartbeatImpl();
    private IoSessionQuery sessionQuery;
    public void start(Integer port) {
        IoServerOption ioServerOption = new IoServerOption();
        if (null != port) {
            ioServerOption.setPort(port);
        } else {
            ioServerOption.setPort(PORT);
        }
        //确认结尾标志
        ioServerOption.setDelimiter(BhznGrainV2ServerUtils.MSG_END.getBytes());
        // é…ç½®ç³»ç»Ÿå¿ƒè·³é—´éš”
        ioServerOption.setReaderIdleTime(5 * 60);
        NettyServer ioServer = new NettyServer(ioServerOption, defaultMessageConsumer, defaultSessionListener, heartbeatProvider);
        ioServer.startup();
        sessionQuery = ioServer.getSessionQuery();
        log.info("* ");
        log.info("* ========================");
        log.info("* ");
        log.info("* [GRAIN-SERVER:BHZN_GRAIN,PORT={}]", PORT);
        log.info("* ");
        log.info("* ========================");
        log.info("* ");
        System.out.println("* ========================");
        System.out.println("* ");
        System.out.println("* [GRAIN-SERVER:BHZN_GRAIN,PORT={}]" + port);
        System.out.println("* ");
        System.out.println("* ========================");
    }
    public IoSessionQuery getSessionQuery() {
        return sessionQuery;
    }
    /**
     * å‘送信息
     *
     * @param ip
     * @param port
     * @param msg
     * @return
     */
    public InvokeResult push(String ip, int port, byte[] msg) {
        IoSessionQuery sessionFactory = getSessionQuery();
        List<IoSession> sessions = sessionFactory.getAllSession();
        IoSession session = null;
        for (IoSession ioSession : sessions) {
            if (BhznGrainV2ServerUtils.getServerKey(ip, port).equals(ioSession.getBusinessKey())) {
                session = ioSession;
                break;
            }
        }
        if (null == session) {
            return InvokeResult.CHANNEL_CLOSED;
        }
        return session.invoke(msg);
    }
//    public InvokeResult push(String ip, int port, String hexStr) {
//
//        byte[] msg = BytesUtil.hexStrToBytes(hexStr);
//
//        IoSessionQuery sessionFactory = getSessionQuery();
//        List<IoSession> sessions = sessionFactory.getAllSession();
//        IoSession session = null;
//        for (IoSession ioSession : sessions) {
//            if (BhznGrainV1ServerUtils.getServerKey(ip, port).equals(ioSession.getBusinessKey())) {
//                session = ioSession;
//                break;
//            }
//        }
//
//        if (null == session) {
//            return InvokeResult.CHANNEL_CLOSED;
//        }
//        return session.invoke(msg);
//    }
    /**
     * ç›´æŽ¥ä½¿ç”¨å†…存的Session执行
     */
    public InvokeResult pushByMin(String hexStr) {
        IoSession session = BhznGrainV2ServerUtils.getSession();
        if (null == session) {
            return InvokeResult.CHANNEL_CLOSED;
        }
        byte[] msg = BytesUtil.hexStrToBytes(hexStr);
        return session.invoke(msg);
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2ServerUtils.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,103 @@
package com.ld.igds.protocol.bhzn.grainv2.server;
import com.ld.igds.util.BytesUtil;
import com.ld.io.api.IoSession;
import java.util.HashMap;
import java.util.Map;
/**
 * å·¥å…·ç±»
 *
 * @author vince
 */
public class BhznGrainV2ServerUtils {
    /**
     * è®°å½•每个连接的最后一次信息时间 key = è¿žæŽ¥çš„KYE,data =当前时间戳
     */
    public static Map<String, Long> contextMapHeart = new HashMap<>();
    public static Map<String, IoSession> contextIoSession = new HashMap<>();
    public static int HEART_BEAT_TIME = 30;//心跳间隔时间
    public static String MSG_START = "3C42485A4E3E";//<BHZN>
    public static String MSG_START2 = "AA";
    public static String MSG_END = "<END>";//<END>
    public static String MSG_END_16 = "3C454E443E";//<END>
    public static final String CHARSET = "UTF-8";
    /**
     * é’ˆå¯¹æ— çº¿ç²®æƒ…主机的默认ID配置
     */
    public static String DEFAULT_MAC_ID = "53681";
    public static String FUNCTION_ID_00 = "00";
    public static String FUNCTION_ID_F1 = "F1";
    public static String FUNCTION_ID_F2 = "F2";
    public static String FUNCTION_ID_83 = "83";
    public static String FUNCTION_ID_93 = "93";
    public static String FUNCTION_ID_92 = "92";
    /**
     * ç”ŸæˆTCP连接的KEY
     *
     * @param ip
     * @param port
     * @return
     */
    public static String getServerKey(String ip, Integer port) {
        return ip + ":" + port;
    }
    /**
     * æ·»åŠ æœ€æ–°å¿ƒè·³æ—¶é—´æˆ³
     *
     * @param session
     */
    public static void addHeartBeat(IoSession session) {
        contextMapHeart.put(getServerKey(session.getAddress(), session.getPort()), System.currentTimeMillis());
    }
    public static Long getHearBeat(IoSession session) {
        return contextMapHeart.get(getServerKey(session.getAddress(), session.getPort()));
    }
    /**
     * è®¡ç®—校验
     *
     * @param content
     * @return
     */
    public static String getCheck(String content) {
        int start = BhznGrainV2ServerUtils.MSG_START.length() + BhznGrainV2ServerUtils.MSG_START2.length();
        content = content.substring(start);
        int sum = 0;
        String hex;
        for (int i = 0; i < content.length() / 2; i++) {
            hex = content.substring(i * 2, i * 2 + 2);
            sum += BytesUtil.hexToInt(hex);
        }
        String hexSum = BytesUtil.intToHexStr(sum);
        int check = BytesUtil.hexToInt(hexSum.substring(hexSum.length() - 2));
        return BytesUtil.intToHexStr(256 - check).substring(2);
    }
    public static void addSession(IoSession session) {
        contextIoSession.put(DEFAULT_MAC_ID, session);
    }
    public static IoSession getSession() {
        return contextIoSession.get(DEFAULT_MAC_ID);
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/grainv2/server/BhznGrainV2SessionListener.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,65 @@
package com.ld.igds.protocol.bhzn.grainv2.server;
import com.ld.igds.common.CoreSerService;
import com.ld.io.api.IoSession;
import com.ld.io.api.IoSessionListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 *
 */
@Slf4j
@Service
public class BhznGrainV2SessionListener implements IoSessionListener {
    @Autowired
    private CoreSerService coreSerService;
    /**
     * è®¾å¤‡åˆ›å»ºåœ¨çº¿ï¼Œéœ€è¦æ³¨æ„å½“前使用主机模式,主机上线默认所有相同SN配置的分机全部上线
     *
     * @param session
     */
    @Override
    public void onCreate(IoSession session) {
        //添加到内存
        BhznGrainV2ServerUtils.addSession(session);
        log.info("++++新建连接++++-IP={},PORT={}", session.getAddress(), session.getPort());
        // æ·»åŠ è‡ªå®šä¹‰ä¸šåŠ¡ID
        session.setBusinessKey(BhznGrainV2ServerUtils.getServerKey(session.getAddress(), session.getPort()));
        //项目采用无线主机模式,直接获取默认设备
       // DeviceSer deviceSer = coreSerService.getCacheSer(ContextUtil.getDefaultCompanyId(), BhznGrainV1ServerUtils.DEFAULT_MAC_ID);
        //if (null == deviceSer) return;
        //coreSerService.onlineBySn(session.getAddress(), session.getPort(), deviceSer.getSn(), Constant.YN_Y);
        //更新缓存
       // coreSerService.refreshCache(deviceSer.getCompanyId());
    }
    /**
     * æ³¨æ„ï¼Œå½“前采用主机模式,主机离线所有相同SN配置的分机全部离线
     *
     * @param session
     */
    @Override
    public void onDestroy(IoSession session) {
        log.info("----连接断开-----IP={},PORT={}", session.getAddress(), session.getPort());
//        //项目采用无线主机模式,直接获取默认设备
//        DeviceSer deviceSer = coreSerService.getCacheSer(ContextUtil.getDefaultCompanyId(), BhznGrainV1ServerUtils.DEFAULT_MAC_ID);
//
//        if (null == deviceSer) return;
        //由于设备掉线后自动调整
//        coreSerService.onlineBySn(session.getAddress(), session.getPort(), deviceSer.getSn(), Constant.YN_N);
//        //更新缓存
//        coreSerService.refreshCache(deviceSer.getCompanyId());
    }
}
igds-protocol-bhzn/src/main/java/com/ld/igds/protocol/bhzn/package-info.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,8 @@
/**
 * @Desc: é‚¦æµ·æ™ºèƒ½å…¬å¸ç›¸å…³åè®®
 * @author: Andy
 * @update-time: 2023/5/11
 */
package com.ld.igds.protocol.bhzn;
igds-web/pom.xml
@@ -167,7 +167,21 @@
                </exclusion>
            </exclusions>
        </dependency>-->
        <dependency>
            <groupId>com.ld.igds</groupId>
            <artifactId>igds-protocol-bhzn</artifactId>
            <version>${igds.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>log4j</artifactId>
                    <groupId>log4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
igds-web/src/main/resources/application-dev.yml
@@ -46,7 +46,7 @@
    database: 1
    host: 127.0.0.1
    port: 6379
    password: Abc123..
    password:
    pool:
      max-active: 200
      max-wait: -1
igds-web/src/main/resources/application-pro5324.yml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,80 @@
##########################  å¹¿ä¸œé«˜å·ž-邦海智能   ##########################
server:
  port: 8888
  context-path: /
  connection-timeout: 5000
  tomcat:
    uri-encoding: UTF-8
##########################  datasourcec   ##########################
spring:
  datasource:
    db-base:
      name: db-base
      type: com.alibaba.druid.pool.DruidDataSource
      url: jdbc:mysql://127.0.0.1:3306/igds_master?useUnicode=true&characterEncoding=utf-8
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: ukJp12Qf+elyBvGHkJ5MQMa95pfVm0oFBHefdEgDFKoFSjbgYa9PYfv5vlem5nvoXjQsP9tIIo53DvSbsl160Q==
      public-key:
      config-decrypt: true
      initial-size:  5
      min-idle:  5
      max-active:  50
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: select 1 from dual
      test-whileIdle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      filters: stat
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      use-global-data-source-stat: true
      removeAbandoned: true
      removeAbandonedTimeout: 90
      logAbandoned: true
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
    db-sqlite:
      name: db-sqlite
      url: jdbc:sqlite:D:/app/igds/db/iot_cfg.db
      driver-class-name: org.sqlite.JDBC
      type: com.alibaba.druid.pool.DruidDataSource
      username:
      password:
  # Redis相关配置
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password: Abc123..
    # è¿žæŽ¥æ± æœ€å¤§è¿žæŽ¥æ•°ï¼ˆä½¿ç”¨è´Ÿå€¼è¡¨ç¤ºæ²¡æœ‰é™åˆ¶ï¼‰
    pool:
      max-active: 200
      max-wait: -1
      max-idle: 10
      min-idle: 0
      timeout: 6000
license:
  subject: ld_license
  publicAlias: publicCert
  storePass: PUBLICFZZYXXJSGFYXGS888888
  licensePath: D:/IGDS/license/license.lic
  publicKeysStorePath: D:/IGDS/license/publicCerts.keystore
##########################  IGDS   ##########################
## ç³»ç»ŸæŽ¥å£è·¯ç”±é…ç½® æ³¨æ„æ•°å­—如果以0开头的话,后台会出现转义,请添加""
igds:
  default:
    companyId: 5324
    sys-name: æ™ºæ…§ç²®åº“管理系统
    logo: logo-default.png
    logo-title: logo-title-default.png
    support: æ™ºæ…§ç²®åº“综合管理平台
    grian-add-point: N
  file-path: D:/IGDS/FILE/
igds-web/src/main/resources/application-pro5326.yml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,80 @@
##########################  å¹¿ä¸œæƒ å·žæƒ æ–°ç²®åº“项目   ##########################
server:
  port: 8888
  context-path: /
  connection-timeout: 5000
  tomcat:
    uri-encoding: UTF-8
##########################  datasourcec   ##########################
spring:
  datasource:
    db-base:
      name: db-base
      type: com.alibaba.druid.pool.DruidDataSource
      url: jdbc:mysql://127.0.0.1:3306/igds_master?useUnicode=true&characterEncoding=utf-8
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: ukJp12Qf+elyBvGHkJ5MQMa95pfVm0oFBHefdEgDFKoFSjbgYa9PYfv5vlem5nvoXjQsP9tIIo53DvSbsl160Q==
      public-key:
      config-decrypt: true
      initial-size:  5
      min-idle:  5
      max-active:  50
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: select 1 from dual
      test-whileIdle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      filters: stat
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      use-global-data-source-stat: true
      removeAbandoned: true
      removeAbandonedTimeout: 90
      logAbandoned: true
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
    db-sqlite:
      name: db-sqlite
      url: jdbc:sqlite:D:/app/igds/db/iot_cfg.db
      driver-class-name: org.sqlite.JDBC
      type: com.alibaba.druid.pool.DruidDataSource
      username:
      password:
  # Redis相关配置
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password: Abc123..
    # è¿žæŽ¥æ± æœ€å¤§è¿žæŽ¥æ•°ï¼ˆä½¿ç”¨è´Ÿå€¼è¡¨ç¤ºæ²¡æœ‰é™åˆ¶ï¼‰
    pool:
      max-active: 200
      max-wait: -1
      max-idle: 10
      min-idle: 0
      timeout: 6000
license:
  subject: ld_license
  publicAlias: publicCert
  storePass: PUBLICFZZYXXJSGFYXGS888888
  licensePath: D:/IGDS/license/license.lic
  publicKeysStorePath: D:/IGDS/license/publicCerts.keystore
##########################  IGDS   ##########################
## ç³»ç»ŸæŽ¥å£è·¯ç”±é…ç½® æ³¨æ„æ•°å­—如果以0开头的话,后台会出现转义,请添加""
igds:
  default:
    companyId: 5326
    sys-name: æ™ºæ…§ç²®åº“管理系统
    logo: logo-default.png
    logo-title: logo-title-default.png
    support: æ™ºæ…§ç²®æƒ…粮情云管理平台
    grian-add-point: N
  file-path: D:/IGDS/FILE/
igds-web/src/main/resources/application.yml
@@ -1,7 +1,7 @@
##########################  Server   ##########################
spring:
  profiles:
    active: dev
    active: pro5324
  application:
    name: igds
  main:
igds-web/src/main/resources/logback-spring.xml
@@ -74,7 +74,7 @@
    </springProfile>
    <!-- ç”Ÿäº§çŽ¯å¢ƒ -->
    <springProfile name="pro">
    <springProfile name="pro5324">
        <!-- æ¯å¤©äº§ç”Ÿä¸€ä¸ªæ–‡ä»¶ -->
        <appender name="PRO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- æ–‡ä»¶è·¯å¾„ -->
igds-web/src/main/resources/static/img/aerial-5326_001.png
pom.xml
@@ -37,6 +37,8 @@
        <module>igds-warn</module>
        <module>igds-protocol-block</module>
        <module>igds-protocol-fzzy3</module>
        <!--邦海智能-->
        <module>igds-protocol-bhzn</module>
        <!--物联网拓展设备包-->
        <module>igds-protocol-iot</module>
        <!--    æ‰‹æœºåŒ…    -->