From 7fe5e6110fb2516a81c2258e8d29fc19ee781d76 Mon Sep 17 00:00:00 2001
From: jiazx0107@163.com <jiazx0107@163.com>
Date: 星期五, 05 一月 2024 13:07:27 +0800
Subject: [PATCH]  游仙分库协议提交,待调整

---
 src/main/java/com/fzzy/protocol/youxian1/client/ClientHandler.java                |   65 +++++
 src/main/java/com/fzzy/protocol/youxian1/analysis/AnalysisService.java            |  360 ++++++++++++++++++++++++++++++
 src/main/java/com/fzzy/protocol/youxian1/package-info.java                        |    4 
 src/main/java/com/fzzy/protocol/ProtocolScheduled.java                            |    2 
 src/main/java/com/fzzy/protocol/youxian1/service/Youxian1GatewayGrainService.java |  150 ++++++++++++
 src/main/java/com/fzzy/protocol/youxian1/client/ClientEngine.java                 |  114 +++++++++
 src/main/java/com/fzzy/protocol/youxian1/ServiceUtils.java                        |    9 
 7 files changed, 702 insertions(+), 2 deletions(-)

diff --git a/src/main/java/com/fzzy/protocol/ProtocolScheduled.java b/src/main/java/com/fzzy/protocol/ProtocolScheduled.java
index fb171da..8900973 100644
--- a/src/main/java/com/fzzy/protocol/ProtocolScheduled.java
+++ b/src/main/java/com/fzzy/protocol/ProtocolScheduled.java
@@ -80,6 +80,4 @@
 
         }
     }
-
-
 }
diff --git a/src/main/java/com/fzzy/protocol/youxian1/ServiceUtils.java b/src/main/java/com/fzzy/protocol/youxian1/ServiceUtils.java
new file mode 100644
index 0000000..2ba35ab
--- /dev/null
+++ b/src/main/java/com/fzzy/protocol/youxian1/ServiceUtils.java
@@ -0,0 +1,9 @@
+package com.fzzy.protocol.youxian1;
+
+
+/**
+ * 宸ュ叿绫�
+ */
+public class ServiceUtils {
+
+}
diff --git a/src/main/java/com/fzzy/protocol/youxian1/analysis/AnalysisService.java b/src/main/java/com/fzzy/protocol/youxian1/analysis/AnalysisService.java
new file mode 100644
index 0000000..eecfd5a
--- /dev/null
+++ b/src/main/java/com/fzzy/protocol/youxian1/analysis/AnalysisService.java
@@ -0,0 +1,360 @@
+package com.fzzy.protocol.youxian1.analysis;
+
+import com.alibaba.fastjson.JSONObject;
+import com.fzzy.api.data.GatewayDeviceType;
+import com.fzzy.api.utils.BytesUtil;
+import com.fzzy.api.utils.NumberUtil;
+import com.fzzy.gateway.GatewayUtils;
+import com.fzzy.gateway.api.GatewayDeviceReportService;
+import com.fzzy.gateway.api.GatewayRemoteManager;
+import com.fzzy.gateway.data.BaseReqData;
+import com.fzzy.gateway.data.WeatherWebDto;
+import com.fzzy.gateway.entity.GatewayDevice;
+import com.fzzy.gateway.hx2023.ScConstant;
+import com.fzzy.gateway.hx2023.data.*;
+import com.fzzy.protocol.ProtocolUtils;
+import com.fzzy.protocol.bhzn.cmd.ReMessageBuilder;
+import com.fzzy.protocol.data.THDto;
+import com.fzzy.protocol.youxian0.ServiceUtils;
+import com.fzzy.protocol.youxian0.data.GrainRoot;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import javax.persistence.criteria.CriteriaBuilder;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 娓镐粰鍒嗗簱锛岃繑鍥炴姤鏂囪В鏋�
+ */
+@Slf4j
+@Component(AnalysisService.BEAN_ID)
+public class AnalysisService {
+
+    public static final String BEAN_ID = "youxian1.analysisService";
+
+    @Resource
+    private GatewayRemoteManager gatewayRemoteManager;
+
+    /**
+     * 鐢ㄤ簬瀛樻斁杩斿洖鐨勪粨娓╀粨婀夸俊鎭�
+     */
+    public static Map<String, THDto> contextMapTH = new HashMap<>();
+
+
+    /**
+     * 鍗忚瑙f瀽
+     * <p>
+     * 80 80 80 80 80 90 41   --90浠h〃鍒嗘満缂栫爜
+     * 39 39 39 35 39 39 39 39 39 39 39 39  --鍥涚粍婀垮害
+     * B4 30 30 31 30 30 B4 30 30 B4 30 30 --鍥涚粍娓╁害
+     * ---浠ヤ笅涓虹伯娓╋紝3涓�艰浆鎹负涓�涓偣
+     * 31 30 35 31 37 32 32 31 34 32 30 33 31 30 38 31 36 34 32 32 35 32 31 38 31 30 34 31 36 36 32 32 33 32 31 34 31 30 32 31 35 39 32 31 37 32 30 34 31 30 37 31 33 37 32 32 34 32 31 37 31 31 30
+     *
+     * @param address
+     * @param port
+     * @param strMsg
+     */
+    public void analysis(InetAddress address, int port, String strMsg) {
+
+        //鍒嗘満ID
+        int start = 5 * 2;
+        int end = start + 1 * 2;
+        String deviceSn = strMsg.substring(start, end);
+        // deviceSn =  璋冩暣杞崲瑙勫垯 ---TODO
+
+        GatewayDevice device = GatewayUtils.getCacheByDeviceSn(deviceSn);
+
+
+        //瑙f瀽娓╂箍搴�
+        this.analysisGrainTh(device, strMsg);
+
+
+        //瑙f瀽绮儏
+        this.analysisGrainStep1(device, strMsg);
+
+    }
+
+    private void analysisGrainTh(GatewayDevice device, String strMsg) {
+        //婀垮害淇℃伅锛屽洓缁勶紝鑾峰彇鏈夋晥鐨勪竴缁勬暟鎹�
+        int start = 7 * 2;
+        int end = start + 12 * 2;
+        String hHex = strMsg.substring(start, end);
+
+        THDto thDto = new THDto();
+        double h = getGrainTemp(hHex.substring(0, 6));
+        if (h < 99.9) {
+            thDto.setHumidityIn(h);
+        }
+        h = getGrainTemp(hHex.substring(6, 12));
+        if (h < 99.9) {
+            thDto.setHumidityIn(h);
+        }
+        h = getGrainTemp(hHex.substring(12, 18));
+        if (h < 99.9) {
+            thDto.setHumidityIn(h);
+        }
+        h = getGrainTemp(hHex.substring(18, 24));
+        if (h < 99.9) {
+            thDto.setHumidityIn(h);
+        }
+
+        //婀垮害淇℃伅
+        start = 19 * 2;
+        end = start + 12 * 2;
+        String tHex = strMsg.substring(start, end);
+        double t = getGrainTemp(tHex.substring(0, 6));
+        if (t > -40.0) {
+            thDto.setTempIn(t);
+        }
+        t = getGrainTemp(tHex.substring(6, 12));
+        if (t > -40.0) {
+            thDto.setTempIn(t);
+        }
+        t = getGrainTemp(tHex.substring(12, 18));
+        if (t > -40.0) {
+            thDto.setTempIn(t);
+        }
+        t = getGrainTemp(tHex.substring(18, 24));
+        if (t > -40.0) {
+            thDto.setTempIn(t);
+        }
+
+        this.add2Map(device.getDeviceSn(), thDto);
+    }
+
+
+    /**
+     * 鍗忚瑙f瀽
+     * <p>
+     * 80 80 80 80 80 90 41   --90浠h〃鍒嗘満缂栫爜
+     * 39 39 39 35 39 39 39 39 39 39 39 39  --鍥涚粍婀垮害
+     * B4 30 30 31 30 30 B4 30 30 B4 30 30 --鍥涚粍娓╁害
+     * ---浠ヤ笅涓虹伯娓╋紝3涓�艰浆鎹负涓�涓偣
+     * 31 30 35 31 37 32 32 31 34 32 30 33 31 30 38 31 36 34 32 32 35 32 31 38 31 30 34 31 36 36 32 32 33 32 31 34 31 30 32 31 35 39 32 31 37 32 30 34 31 30 37 31 33 37 32 32 34 32 31 37 31 31 30
+     *
+     * @param device
+     * @Param strMsg
+     */
+    private void analysisGrainStep1(GatewayDevice device, String strMsg) {
+
+        String[] attCable = device.getCableRule().split("-");
+        int cableZ = Integer.valueOf(attCable[0]);
+        int cableY = Integer.valueOf(attCable[1]);
+        int cableX = Integer.valueOf(attCable[2]);
+        log.info("z={},x={},y={}", cableZ, cableX, cableY);
+
+        //鑾峰彇璇锋眰淇℃伅
+        BaseReqData reqData = ProtocolUtils.getSyncReq(device.getDepotIdSys());
+        if (null == reqData) {
+            log.error("---------娌℃湁鑾峰彇鍒拌姹備俊鎭紝涓嶆墽琛岃В鏋�------{}", device.getDeviceName());
+            return;
+        }
+
+        //鍙繚鐣欑伯鎯呬俊鎭�
+        int start = 31 * 2;
+        strMsg = strMsg.substring(start);
+        int num = cableZ * cableY * cableX;
+        String tempStr = "";
+        List<Double> points = new ArrayList<>();
+        double point = 0;
+        for (int i = 0; i < num; i++) {
+            tempStr = strMsg.substring(i * 3 * 2, i * 3 * 2 + 3 * 2);
+            point = this.getGrainTemp(tempStr);
+
+            //澶勭悊鏃犳晥鐨勬暟鎹�
+            if (point > 50) {
+                point = -100.0;
+            }
+
+            points.add(point);
+        }
+
+
+        analysisGrainStep2(reqData, cableZ, cableY, cableX, points);
+    }
+
+
+    /**
+     * 鏁版嵁杞崲
+     *
+     * @param reqData
+     * @param cableZ
+     * @param cableY
+     * @param cableX
+     * @param points
+     */
+    private void analysisGrainStep2(BaseReqData reqData, int cableZ, int cableY, int cableX, List<Double> points) {
+
+        GatewayDevice device = reqData.getDevice();
+        //鏁版嵁灏佽
+        GrainData grain = new GrainData();
+        grain.setMessageId(ScConstant.getMessageId());
+        grain.setDeviceId(device.getDeviceId());
+        grain.setTimestamp(System.currentTimeMillis() + "");
+
+        ClientHeaders headers = new ClientHeaders();
+        headers.setDeviceName(device.getDeviceName());
+        headers.setProductId(device.getProductId());
+        headers.setOrgId(device.getOrgId());
+        headers.setMsgId(reqData.getMessageId());
+        grain.setHeaders(headers);
+
+
+        GrainOutPut outPut = new GrainOutPut();
+
+
+        double max = ReMessageBuilder.MAX_TEMP, min = ReMessageBuilder.MIN_TEMP, sumT = 0.0, sumNum = cableX * cableY * cableZ;
+
+        List<GrainTemp> temperature = new ArrayList<>();
+        //鏍瑰彿
+        int cableNum = 1, position = 0;
+
+        double curTemp;
+        int x = 0, y = 0, z = 0;
+        for (int i = 0; i < points.size(); i++) {
+            curTemp = points.get(i);
+            position = i;
+            z = i % cableZ + 1;
+            x = i / (cableZ * cableY);
+            y = x * (cableZ * cableY);
+            y = (i - y) / cableZ;
+            //鏍瑰彿
+            cableNum = (i / cableZ) + 1;
+
+            temperature.add(new GrainTemp(cableNum + "", z + "", curTemp + "", position + ""));
+
+            sumT += curTemp;
+            if (curTemp > max) {
+                max = curTemp;
+            }
+            if (curTemp < min) {
+                min = curTemp;
+            }
+        }
+
+        if (sumNum == 0) {
+            sumNum = 1;
+            log.warn("---褰撳墠绮儏閲囬泦寮傚父--");
+        }
+        //杩囨护姣旇緝鐢ㄧ殑鏈�澶ф渶灏忓��
+        if (max == ReMessageBuilder.MAX_TEMP) {
+            max = 0.0;
+        }
+        if (min == ReMessageBuilder.MIN_TEMP) {
+            min = 0.0;
+        }
+
+        outPut.setTemperature(temperature);
+        outPut.setAvgTemperature(NumberUtil.keepPrecision((sumT / sumNum), 1) + "");
+        outPut.setMinTemperature(min + "");
+        outPut.setMaxTemperature(min + "");
+        List<GrainTH> ths = new ArrayList<>();
+
+
+        //鑾峰彇娓╂箍搴�
+        THDto thDto = this.getTH(device.getDeviceSn());
+
+        ths.add(new GrainTH(thDto.getTempIn() != null ? thDto.getTempIn() + "" : "", thDto.getHumidityIn() != null ? thDto.getHumidityIn() + "" : "", "1"));
+        outPut.setTemperatureAndhumidity(ths);
+        grain.setOutput(JSONObject.toJSONString(outPut));
+
+        GatewayDevice gatewayDeviceWeather = GatewayUtils.getCacheByDeviceTypeOne(GatewayDeviceType.TYPE_09.getCode());
+
+        //绯荤粺姘旇薄绔欎俊鎭�
+        WeatherWebDto weather = WeatherWebDto.contextMap.get("default");
+
+        //姘旇薄淇℃伅
+        GrainWeather weatherStation = new GrainWeather();
+        weatherStation.setMessageId(ScConstant.getMessageId());
+        weatherStation.setMessgeId(weatherStation.getMessageId());
+
+        if (null != gatewayDeviceWeather) {
+            weatherStation.setId(gatewayDeviceWeather.getDeviceId());
+        } else {
+            weatherStation.setId(device.getDeviceId());
+        }
+        weatherStation.setAirPressure(weather.getPressure());
+        weatherStation.setHumidity(weather.getHumidity());
+        weatherStation.setPm(weather.getAir_pm25());
+        weatherStation.setRadiation("0");
+        weatherStation.setRainfallAmount(weather.getWea());
+        weatherStation.setTemperature(weather.getTem());
+        weatherStation.setWindDirection(weather.getWin());
+        weatherStation.setWindPower(weather.getWin_meter());
+        weatherStation.setWindSpeed(weather.getWin_speed());
+
+        grain.setWeatherStation(JSONObject.toJSONString(weatherStation));
+
+        //灏佽濂界殑鏁版嵁
+        log.info("---绮儏淇℃伅灏佽瀹屾垚-寮�濮嬫墽琛屾帹閫�");
+
+        reqData.setData(JSONObject.toJSONString(grain));
+
+        doPushGrain(reqData);
+    }
+
+
+    private void doPushGrain(BaseReqData reqData) {
+
+        GatewayDeviceReportService reportService = gatewayRemoteManager.getDeviceReportService(reqData.getDevice().getPushProtocol());
+        if (null == reportService) {
+            log.error("------------绮儏鎺ㄩ�佸け璐ワ紝绯荤粺涓嶅瓨鍦ㄥ綋鍓嶅崗璁墽琛岀被----{}", reqData.getDevice().getDeviceName());
+            return;
+        }
+
+        reportService.reportGrainData(reqData);
+    }
+
+
+    /**
+     * 璁$畻绮儏娓╁害 3缁勬俯搴�
+     *
+     * @param tempHex
+     * @return
+     */
+    public static double getGrainTemp(String tempHex) {
+        String strAscii = "";
+        strAscii += toAscii(tempHex.substring(0, 2));
+        strAscii += toAscii(tempHex.substring(2, 4));
+        strAscii += toAscii(tempHex.substring(4, 6));
+
+        Integer value = Integer.valueOf(strAscii);
+
+        return value / 10.0;
+    }
+
+    private void add2Map(String deviceSn, THDto thDto) {
+        contextMapTH.put("TH_" + deviceSn, thDto);
+    }
+
+    private THDto getTH(String deviceSn) {
+        return contextMapTH.get("TH_" + deviceSn);
+    }
+
+
+    public static void main(String[] args) {
+        String strMsg = "31 30 35 31 37 32 32 31 34 32 30 33 31 30 38 31 36 34 32 32 35 32 31 38 31 30 34 31 36 36 32 32 33 32 31 34 31 30 32 31 35 39 32 31 37 32 30 34 31 30 37 31 33 37 32 32 34 32 31 37 31 31 30";
+        strMsg = strMsg.replaceAll(" ", "");
+        System.out.println("---" + strMsg);
+        int num = 20;
+        String tempStr = "";
+        double tem;
+        for (int i = 0; i < num; i++) {
+            tempStr = strMsg.substring(i * 3 * 2, i * 3 * 2 + 3 * 2);
+            System.out.println("---" + tempStr);
+            tem = getGrainTemp(tempStr);
+            System.out.println("-tem--" + tem);
+        }
+    }
+
+    public static char toAscii(String hexString) {
+        int decimal = Integer.parseInt(hexString, 16);
+        return (char) decimal;
+    }
+
+}
diff --git a/src/main/java/com/fzzy/protocol/youxian1/client/ClientEngine.java b/src/main/java/com/fzzy/protocol/youxian1/client/ClientEngine.java
new file mode 100644
index 0000000..a5dcac0
--- /dev/null
+++ b/src/main/java/com/fzzy/protocol/youxian1/client/ClientEngine.java
@@ -0,0 +1,114 @@
+package com.fzzy.protocol.youxian1.client;
+
+import com.ld.io.api.InvokeResult;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.*;
+import io.netty.channel.oio.OioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.oio.OioSocketChannel;
+import io.netty.handler.codec.bytes.ByteArrayDecoder;
+import io.netty.handler.codec.bytes.ByteArrayEncoder;
+import lombok.extern.slf4j.Slf4j;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 娓镐粰鍒嗗簱锛岄�氳鍗忚
+ */
+@Slf4j
+public class ClientEngine {
+
+    /**
+     * 瀹㈡埛绔ā寮忓垱寤虹殑杩炴帴閫氶亾
+     */
+    public static Map<String, Channel> clientChannelMap = new HashMap<>();
+
+
+    public static Channel defaultChannel;
+
+    public static void start(String ip, Integer port) throws Exception {
+        if (defaultChannel != null) {
+            log.info("-----IP={},杩炴帴瀛樺湪锛岀洿鎺ヤ娇鐢�", ip);
+            return;
+        }
+        EventLoopGroup group = new OioEventLoopGroup();
+        Bootstrap b = new Bootstrap();
+        //榛樿闀胯繛鎺�
+        b.option(ChannelOption.SO_KEEPALIVE, true);
+        b.group(group).channel(OioSocketChannel.class)
+                .handler(new ChannelInitializer<SocketChannel>() {
+                    @Override
+                    protected void initChannel(SocketChannel ch)
+                            throws Exception {
+                        ChannelPipeline p = ch.pipeline();
+                        // 瀛楃涓茶В鐮� 鍜� 缂栫爜
+                        p.addLast("decoder", new ByteArrayDecoder());
+                        p.addLast("encoder", new ByteArrayEncoder());
+                        // 鑷繁鐨勯�昏緫Handler
+                        p.addLast("handler", new ClientHandler());
+                    }
+                });
+
+        // 鍙戣捣寮傛杩炴帴璇锋眰锛岀粦瀹氳繛鎺ョ鍙e拰host淇℃伅
+        ChannelFuture channelFuture = b.connect(ip, port);
+
+        defaultChannel = channelFuture.channel();
+
+        // channelFuture.channel().closeFuture().sync();
+
+        add2ChannelMap(ip, defaultChannel);
+
+        channelFuture.addListener(new ChannelFutureListener() {
+            @Override
+            public void operationComplete(ChannelFuture arg0) throws Exception {
+                if (channelFuture.isSuccess()) {
+                    log.info("-----IP={},杩炴帴鎴愬姛", ip);
+                } else {
+                    log.info("-----IP={},杩炴帴澶辫触锛岃嚜鍔ㄥ叧闂嚎绋�", ip);
+                    channelFuture.cause().printStackTrace();
+                    group.shutdownGracefully(); // 鍏抽棴绾跨▼缁�
+                }
+            }
+        });
+    }
+
+    public static InvokeResult send(byte[] array) throws InterruptedException {
+
+        if (null == defaultChannel) {
+            return InvokeResult.SOCKET_NOT_CREATE;
+        }
+        if (!defaultChannel.isActive()) {
+            return InvokeResult.CHANNEL_CLOSED;
+        }
+        defaultChannel.writeAndFlush(Unpooled.copiedBuffer(array)).sync();
+        return InvokeResult.SUCCESS;
+    }
+
+
+    public static Channel getChannel() {
+        return defaultChannel;
+    }
+
+    public static void add2ChannelMap(String key, Channel channel) {
+        clientChannelMap.put(key, channel);
+    }
+
+    /**
+     * 濡傛灉
+     *
+     * @param key
+     * @return
+     */
+    public static Channel getChannel(String key) {
+        Channel channel = clientChannelMap.get(key);
+        if (null == channel) return null;
+        if (channel.isActive()) {
+            return channel;
+        } else {
+            channel.close();
+        }
+        return null;
+    }
+}
diff --git a/src/main/java/com/fzzy/protocol/youxian1/client/ClientHandler.java b/src/main/java/com/fzzy/protocol/youxian1/client/ClientHandler.java
new file mode 100644
index 0000000..1dd8b09
--- /dev/null
+++ b/src/main/java/com/fzzy/protocol/youxian1/client/ClientHandler.java
@@ -0,0 +1,65 @@
+package com.fzzy.protocol.youxian1.client;
+
+import com.fzzy.api.utils.BytesUtil;
+import com.fzzy.api.utils.SpringUtil;
+import com.fzzy.protocol.youxian1.analysis.AnalysisService;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import lombok.extern.slf4j.Slf4j;
+
+import java.net.InetSocketAddress;
+
+
+@Slf4j
+public class ClientHandler extends SimpleChannelInboundHandler<Object> {
+
+    private AnalysisService analysisService;
+
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) {
+        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel()
+                .remoteAddress();
+
+        log.info("杩炴帴缁堟垚鍔燂紝IP={},port={}", socketAddress.getAddress()
+                .getHostAddress(), socketAddress.getPort());
+    }
+
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+        super.channelInactive(ctx);
+
+        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
+
+        log.info("杩炴帴缁堢鎺夌嚎锛孖P={},port={}", socketAddress.getAddress(), socketAddress.getPort());
+
+
+    }
+
+    @Override
+    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
+        byte[] bytes = (byte[]) msg;
+
+        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
+
+        String strMsg = BytesUtil.bytesToString(bytes);
+
+        log.info("缁堢杩斿洖淇℃伅锛孖P={},port={}锛宮sg={}", socketAddress.getAddress(), socketAddress.getPort(), strMsg);
+
+        if (null == analysisService) {
+            analysisService = SpringUtil.getBean(AnalysisService.class);
+        }
+
+       try{
+           analysisService.analysis(socketAddress.getAddress(), socketAddress.getPort(), strMsg);
+       }catch (Exception e){
+           log.error(e.getMessage(),e);
+       }
+
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+        ctx.close();
+    }
+
+}
diff --git a/src/main/java/com/fzzy/protocol/youxian1/package-info.java b/src/main/java/com/fzzy/protocol/youxian1/package-info.java
new file mode 100644
index 0000000..e1c2650
--- /dev/null
+++ b/src/main/java/com/fzzy/protocol/youxian1/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * 娓镐粰鍒嗗簱
+ */
+package com.fzzy.protocol.youxian1;
\ No newline at end of file
diff --git a/src/main/java/com/fzzy/protocol/youxian1/service/Youxian1GatewayGrainService.java b/src/main/java/com/fzzy/protocol/youxian1/service/Youxian1GatewayGrainService.java
new file mode 100644
index 0000000..4d038fd
--- /dev/null
+++ b/src/main/java/com/fzzy/protocol/youxian1/service/Youxian1GatewayGrainService.java
@@ -0,0 +1,150 @@
+package com.fzzy.protocol.youxian1.service;
+
+import com.fzzy.api.data.GatewayDeviceProtocol;
+import com.fzzy.api.utils.BytesUtil;
+import com.fzzy.gateway.api.GatewaySyncGranService;
+import com.fzzy.gateway.data.BaseReqData;
+import com.fzzy.gateway.data.BaseResp;
+import com.fzzy.gateway.entity.GatewayDevice;
+import com.fzzy.protocol.ProtocolUtils;
+import com.fzzy.protocol.youxian1.client.ClientEngine;
+import com.ld.io.api.InvokeResult;
+import io.netty.channel.Channel;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+/**
+ * 娓镐粰鍒嗗簱鍗忚-绮儏閲囬泦鍏ュ彛
+ */
+@Slf4j
+@Component
+public class Youxian1GatewayGrainService implements GatewaySyncGranService {
+
+
+    @Override
+    public String getGrainProtocol() {
+        return GatewayDeviceProtocol.GRAIN_YOUXIAN1_2023.getCode();
+    }
+
+    /**
+     * @param reqData
+     * @return
+     */
+    @Override
+    public synchronized BaseResp syncGrain(BaseReqData reqData) {
+
+        BaseResp resp = new BaseResp();
+
+        GatewayDevice device = reqData.getDevice();
+
+        if (null == device) {
+            resp.setCode(500);
+            resp.setMsg("绯荤粺鏈幏鍙栧埌涓嬭杩炴帴璁惧淇℃伅锛屾棤娉曟墽琛�");
+            log.error("----------------绯荤粺鏈幏鍙栧埌涓嬭杩炴帴璁惧淇℃伅,鏃犳硶鎵ц---------");
+            return resp;
+        }
+        try {
+            //Step 璇锋眰淇℃伅鏀惧叆鍐呭瓨
+            ProtocolUtils.addSyncReq2Map(device.getDepotIdSys(), reqData);
+
+            // 鍒ゆ柇鏁版嵁鏈夋病鏈夋敹鍙栧畬鏁�
+            String[] attCable = device.getCableRule().split("-");
+            int cableZ = Integer.valueOf(attCable[0]);
+            int cableY = Integer.valueOf(attCable[1]);
+            int cableX = Integer.valueOf(attCable[2]);
+
+            // 鐢熸垚绮儏淇℃伅
+            String hexCmd = buildGrainCmd(device, cableX, cableY, cableZ);
+
+            Channel channel = ClientEngine.getChannel(device.getIp());
+
+            if (null == channel) {
+                ClientEngine.start(device.getIp(), device.getPort());
+                Thread.sleep(500);
+            }
+
+            InvokeResult message = ClientEngine.send(BytesUtil.hexStrToBytes(hexCmd));
+
+            log.error("骞冲彴------>>>>涓绘帶锛氬彂閫佺伯鎯呮娴嬪懡浠�-{}---{}", message, hexCmd);
+            // 灏佽杩斿洖淇℃伅
+            if (!InvokeResult.SUCCESS.getCode().equals(message.getCode())) {
+                log.error("骞冲彴------>>>>鎺у埗鏌滐細鍙戦�佺伯鎯呮娴嬪懡浠�-澶辫触{}", message.getMessage());
+                resp.setCode(500);
+                resp.setMsg("骞冲彴------>>>>鎺у埗鏌滐細鍙戦�佺伯鎯呮娴嬪懡浠�-澶辫触锛�" + message.getMessage());
+            }
+
+        } catch (Exception e) {
+            log.error("绮儏妫�娴嬪紓甯革細{}", e);
+            resp.setCode(500);
+            resp.setMsg("骞冲彴------>>>>鎺у埗鏌滐細鍙戦�佺伯鎯呮娴嬪懡浠わ細" + e.getMessage());
+            return resp;
+        }
+        return resp;
+    }
+
+
+    /**
+     * 锛堝彂閲囬泦鍛戒护锛夛細 A5 A5 A5 80 8X 41 8Y 8Z 8M
+     * 8 X--鍒嗘満鍙�(90--16鍙峰垎鏈�)  8Y---璧峰闂�  8Z---鏈粨闂存暟  8M---姣忛棿鐐规暟
+     * <p>
+     * X--鎺у埗鍣ㄥ彿锛沋--璧峰闂达紱Z--缁撴潫闂达紱M--鐐规暟
+     * 鐢熸垚绮儏閲囬泦鍛戒护
+     *
+     * @param device
+     * @return
+     */
+    private String buildGrainCmd(GatewayDevice device, int cableX, int cableY, int cableZ) {
+
+        String hexCmd = "A5A5A580{id}41{start}{end}{num}";
+
+        //鍒嗘満鍙凤紝寰呮牴鎹厤缃繘琛岃皟鏁达紝鏆傛椂鏈煡璁$畻瑙勫垯 TODO
+        String hexId = "90";
+        hexCmd = hexCmd.replace("{id}", hexId);
+
+
+        //寮�濮嬪垪锛岄粯璁や粠1寮�濮�
+        String hexStart = "81";
+        hexCmd = hexCmd.replace("{start}", hexStart);
+
+        //鎴嚦鍒�
+        String hexEnd = "8" + cableX;
+        hexCmd = hexCmd.replace("{end}", hexEnd);
+
+        //鐐逛綅鏁帮紝鐩墠鏈煡鍏蜂綋璁$畻瑙勫垯 TODO
+        int num = cableX * cableY * cableZ;
+        String hexNum = BytesUtil.intToHexStr1(num);
+        hexCmd = hexCmd.replace("{num}", hexNum);
+
+        return hexCmd;
+    }
+
+    @Override
+    public BaseResp syncGrainTh(BaseReqData reqData) {
+        return new BaseResp();
+    }
+
+    @Override
+    public BaseResp syncConf(BaseReqData reqData) {
+        return new BaseResp();
+    }
+
+    @Override
+    public BaseResp writeConf(BaseReqData reqData) {
+        return new BaseResp();
+    }
+
+    @Override
+    public BaseResp initCable(BaseReqData reqData) {
+        return new BaseResp();
+    }
+
+    @Override
+    public BaseResp disconnect(BaseReqData reqData) {
+        return new BaseResp();
+    }
+
+    @Override
+    public BaseResp transparent(BaseReqData reqData) {
+        return new BaseResp();
+    }
+}

--
Gitblit v1.9.3