vince
2023-12-26 9a139b15be65dcd83ae187bb384627097c6a811a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package com.fzzy.protocol.youxian0.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.youxian0.ServiceUtils;
import com.fzzy.protocol.youxian0.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 Youxian0GatewayGrainService implements GatewaySyncGranService {
 
 
    @Override
    public String getGrainProtocol() {
        return GatewayDeviceProtocol.GRAIN_YOUXIAN0_2023.getCode();
    }
 
    /**
     * 发送[测温]命令 9精度的  返回温度数据是单个字节
     * 发送数据: 7e 01 00 00 01 0b 00 02 00 01 a0 ff ff 66 ff 05 4e 83 7e
     * 接收数据:    00 01 01 00 0B 00 00 A0 FF FF 66 FF 05 BE 01 64 78 7B 79 79 CC 02 A4 A8 A8 A9 A8 (去掉7e头7e尾  去掉最后两位crc校验)
     * 杆号:1  [ 26.5 27.0 26.0 26.0 ]
     * 杆号:2  [ 26.0 27.0 26.0 26.0 ]
     *
     * @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 {
            this.syncGrainTh(reqData);
            //Step 请求信息放入内存
            ProtocolUtils.addSyncReq2Map(device.getDepotIdSys(), reqData);
 
            // 判断数据有没有收取完整
            String[] attCable = device.getCableRule().split("-");
            int cableY = Integer.valueOf(attCable[1]);
            int cableX = Integer.valueOf(attCable[2]);
 
            int start = 0, length = cableY;
            // 生成粮情信息
            String  hexStr = "";
            InvokeResult message;
            for (int i = 1; i <= cableX; i++) {
                if (1 == i) {
                    start = 255;
                } else {
                    start = (i - 1) * cableY + 1;
                }
                hexStr = buildGrainCmd(device, i, start, length);
                // 发送命令 TODO----->>>暂时调整为每次创建一个新连接
                //Channel channel = ClientEngine.getChannel(device.getIp());
                Channel channel = null;
                if (null == channel) {
                    ClientEngine clientEngine = new ClientEngine(device.getIp(), device.getPort());
                    clientEngine.start();
                    Thread.sleep(300);
                    channel = clientEngine.getChannel();
                }
                message = ClientEngine.send2(hexStr, channel);
 
                log.error("平台------>>>>主控:发送粮情检测命令-{}---{}", message,hexStr);
 
                // 封装返回信息
                if (!InvokeResult.SUCCESS.getCode().equals(message.getCode())) {
                    log.error("平台------>>>>控制柜:发送粮情检测命令-失败{}", message.getMessage());
                    resp.setCode(500);
                    resp.setMsg("平台------>>>>控制柜:发送粮情检测命令-失败:" + message.getMessage());
                }
                Thread.sleep(500);
            }
        } catch (Exception e) {
            log.error("粮情检测异常:{}", e);
            resp.setCode(500);
            resp.setMsg("平台------>>>>控制柜:发送粮情检测命令:" + e.getMessage());
            return resp;
        }
        return resp;
    }
 
    @Override
    public BaseResp syncGrainTh(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);
            InvokeResult message;
            Channel channel = null;
            if (null == channel) {
                ClientEngine clientEngine = new ClientEngine(device.getIp(), device.getPort());
                clientEngine.start();
                Thread.sleep(300);
                channel = clientEngine.getChannel();
            }
            String hexStr = this.buildTHCmd(device);
            message = ClientEngine.send2(hexStr, channel);
                log.error("平台------>>>>主控:发送温湿度检测命令-{}---{}", message,hexStr);
                // 封装返回信息
                if (!InvokeResult.SUCCESS.getCode().equals(message.getCode())) {
                    log.error("平台------>>>>主控:发送温湿度检测命令-失败{}", message.getMessage());
                    resp.setCode(500);
                    resp.setMsg("平台------>>>>主控:发送温湿度检测命令-失败:" + message.getMessage());
                }
                Thread.sleep(500);
        } catch (Exception e) {
            log.error("温湿度检测异常:{}", e);
            resp.setCode(500);
            resp.setMsg("平台------>>>>控制柜:发送温湿度检测命令:" + e.getMessage());
            return resp;
        }
        return resp;
    }
 
    /**
     * 生成粮情采集命令
     *
     * @param device
     * @return
     */
    private String buildGrainCmd(GatewayDevice device, int cur, int startCur, int length) {
 
        String start = "7e";
        //测温命令--7e 01 00 00 01 00 00 02 00 01 a0 ff ff 66 ff 05 3a 59 7e
        String content = "{id}0000{id}{msgId}000200{id}a0ffff{funId}{start}{length}";
 
        //开始封装消息体-主机ID
        String deviceSn = device.getDeviceSn();
        deviceSn = BytesUtil.intToHexStr1(Integer.valueOf(deviceSn));
        content = content.replace("{id}", deviceSn);
        content = content.replace("{id}", deviceSn);
        content = content.replace("{id}", deviceSn);
        //命令ID
        String msgIdHex = BytesUtil.intToHexStr1(cur);
        content = content.replace("{msgId}", msgIdHex);
 
        //命令类型
        content = content.replace("{funId}", ServiceUtils.FUNCTION_66);
 
        //开始根号
        String startCurHex = BytesUtil.intToHexStr1(startCur);
        content = content.replace("{start}", startCurHex);
 
        //截取长度
        String lenHex = BytesUtil.intToHexStr1(length);
        content = content.replace("{length}", lenHex);
 
        //校验码
        String crcCode = this.getCRC(content);
 
        String end = "7e";
 
        return start + content + crcCode + end;
    }
    private String buildTHCmd(GatewayDevice device) {
 
        String start = "7e";
        //测温命令--7e 01 00 00 01 06 00 02 00 01 a0 ff ff 68 1a 05 88 5c 7e
        String content = "{id}0000{id}{msgId}000200{id}a0ffff{funId}{start}{length}";
 
        //开始封装消息体-主机ID
        String deviceSn = device.getDeviceSn();
        deviceSn = BytesUtil.intToHexStr1(Integer.valueOf(deviceSn));
        content = content.replace("{id}", deviceSn);
        content = content.replace("{id}", deviceSn);
        content = content.replace("{id}", deviceSn);
        //命令ID
        String msgIdHex = BytesUtil.intToHexStr1(20);
        content = content.replace("{msgId}", msgIdHex);
 
        //命令类型
        content = content.replace("{funId}", ServiceUtils.FUNCTION_68);
 
        //开始根号
        String startCurHex = BytesUtil.intToHexStr1(0);
        content = content.replace("{start}", startCurHex);
 
        //截取长度
        String lenHex = BytesUtil.intToHexStr1(0);
        content = content.replace("{length}", lenHex);
 
        //校验码
        String crcCode = this.getCRC(content);
 
        String end = "7e";
 
        return start + content + crcCode + end;
    }
    /**
     * 参考结果:http://www.ip33.com/crc.html
     * <p>
     * 7e 01 00 00 01 00 00 02 00 01 a0 ff ff 66 ff 05 3a 59 7e
     * <p>
     * 测试:010000010000020001a0ffff66ff05
     * 返回:3a59
     *
     * @param content
     * @return
     */
    private static String getCRC(String content) {
        byte[] bytes = HexStringToBytes(content);//16进制字符串转成16进制字符串数组
        int i = CRC16_XMODEM(bytes);//进行CRC—XMODEM校验得到十进制校验数
        String CRC = Integer.toHexString(i);//10进制转16进制
       if(CRC.length() < 4){
           CRC = "0"+CRC;
       }
        if(CRC.length() < 4){
            CRC = "0"+CRC;
        }
        //调整高位在右,地位在左侧
        CRC = tran_LH(CRC);
 
        return CRC;
    }
 
    public static void main(String[] args) {
        //System.out.println(getCRC("010000010400020001a0ffff661005"));
        //System.out.println(getCRC("010000010500020001a0ffff661505"));
        String strMsg = "7E00010100010000A0FFFF66FF05BE01635B696FCE02A38ABAB5CE03E3003131CE044383B7B6CE0583497276D9FA";
        int start = 15 * 2;
        strMsg = strMsg.substring(start);
        System.out.println(strMsg);
        String kyeNumBin = BytesUtil.toBinary8String(BytesUtil.hexToInt("A3"));
        System.out.println(kyeNumBin);
        String key = "00000" + kyeNumBin.substring(0, 3);
        int keyValue = BytesUtil.hexToInt(BytesUtil.bin2Hex(key));
        key = "0000" + kyeNumBin.substring(4);
        int numValue = BytesUtil.hexToInt(BytesUtil.bin2Hex(key));
        System.out.println((keyValue + ""));
        System.out.println((numValue + ""));
 
    }
 
    public static String tran_LH(String info) {
        return info.substring(2) + info.substring(0, 2);
    }
 
    public static int CRC16_XMODEM(byte[] buffer) {
        int wCRCin = 0x0000; // initial value 65535
        int wCPoly = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
        for (byte b : buffer) {
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((wCRCin >> 15 & 1) == 1);
                wCRCin <<= 1;
                if (c15 ^ bit)
                    wCRCin ^= wCPoly;
            }
        }
        wCRCin &= 0xffff;
        return wCRCin ^= 0x0000;
    }
 
    public static byte[] HexStringToBytes(String src) {
        int len = src.length() / 2;
        byte[] ret = new byte[len];
        byte[] tmp = src.getBytes();
        for (int i = 0; i < len; i++) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }
        return ret;
    }
 
    public static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[]{src0}))
                .byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[]{src1}))
                .byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }
 
 
    @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();
    }
}