vince
2023-12-19 c8a4f3f8327b4a2290d719503211adb8845e6fd8
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package com.fzzy.protocol.bhzn.analysis;
 
import com.alibaba.fastjson.JSONObject;
import com.fzzy.api.Constant;
import com.fzzy.api.data.ApiCommonDevice;
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.CommandBuild;
import com.fzzy.protocol.bhzn.cmd.ReMessageBuilder;
import com.fzzy.protocol.bhzn.data.IoMessage;
import com.fzzy.protocol.data.THDto;
import com.fzzy.protocol.bhzn.server.BhznGrainV2ServerEngine;
import com.fzzy.protocol.bhzn.server.BhznGrainV2ServerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.util.*;
 
/**
 * 协议解析
 *
 * @author vince
 */
@Slf4j
@Component(AnalysisService.BEAN_ID)
public class AnalysisService {
 
 
    public static final String BEAN_ID = "bhzn2.analysisService";
 
    @Resource
    private GatewayRemoteManager gatewayRemoteManager;
 
    /**
     * 针对分包粮情报文进行封装
     */
    public static Map<String, String> contextMapGrain = new HashMap<>();
 
    /**
     * 用于存放返回的仓温仓湿信息
     */
    public static Map<String, THDto> contextMapTH = new HashMap<>();
 
    /**
     * @param sessionKey ip:port
     */
    public void analysis(String sessionKey, IoMessage message) throws Exception {
 
        //注册
        if (BhznGrainV2ServerUtils.FUNCTION_ID_F1.equals(message.getFunctionId())) {
 
            log.info("主机------->>平台:注册信息报文={}", message);
 
            //DO NOTHING
 
            return;
        }
 
        //心跳
        if (BhznGrainV2ServerUtils.FUNCTION_ID_F2.equals(message.getFunctionId())) {
 
            //DO NOTHING
 
            return;
        }
 
        // 93 解析仓温仓湿,并返回收到报文
        if (BhznGrainV2ServerUtils.FUNCTION_ID_93.equals(message.getFunctionId())) {
            log.info("主机------->>平台:温湿度信息报文={}", message);
            analysisTh(message);
            return;
        }
 
        // 92 解析粮温,并返回收到报文
        if (BhznGrainV2ServerUtils.FUNCTION_ID_92.equals(message.getFunctionId())) {
            log.info("主机------->>平台:粮情信息报文={}", message);
            analysisGrain(message);
        }
    }
 
 
    /**
     * 暂时不支持义分机多仓模式,--平房仓
     *
     * @param message
     */
    private void analysisGrain(IoMessage message) {
        try {
 
            //根据分机SN获取设备配置信息
            GatewayDevice gatewayDevice = GatewayUtils.getCacheByDeviceSn(message.getAddr());
            if (null == gatewayDevice) {
                replayGrain(message);
                log.error("主机-------->>平台,解析粮情失败,未获取到系统设备配置信息:" + message.getAddr());
                return;
            }
            //根据分机地址获取分机信息
            ApiCommonDevice commonDevice = Constant.getCommonDeviceCache(message.getIp());
            if (commonDevice == null) {
                replayGrain(message);
                log.error("主机-------->>平台,解析粮情失败,未获取到系统粮情主机配置:" + message.getAddr());
                return;
            }
 
 
 
            //获取请求信息
            BaseReqData reqData = ProtocolUtils.getSyncReq(gatewayDevice.getDepotIdSys());
            if (null == reqData) {
                replayGrain(message);
                log.error("主机-------->>平台,解析粮情失败,未获取到粮情请求信息:" + message.getAddr());
                return;
            }
 
            // 判断数据有没有收取完整
            String[] attCable = gatewayDevice.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) {
                log.info("分机------>>>平台:粮情数据单包=" + grainHex);
                //返回粮情接收信息
                replayGrain(message);
                analysisGrain2(message, reqData, 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);
                log.info("分机------>>>平台:粮情数据多包,完整数据=" + grainHex);
                analysisGrain2(message, reqData, grainHex);
                return;
 
            } else {
                log.info("分机------>>>平台:将第一包数据存入内存=" + grainHex);
                contextMapGrain.put(key, grainHex);
                replayGrain(message);
            }
 
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
 
    /**
     * 返回粮情收到报文信息,需要注意:如果存在分包情况下,需要等所有包收到后返回
     *
     * @param message
     */
    private void replayGrain(IoMessage message) throws InterruptedException {
        Thread.sleep(50);
        String hexStr = CommandBuild.getMsgGrainReply(message.getAddr());
        log.info("平台--------->>>主机,返回粮情报文收到信息,报文={}", hexStr);
 
        BhznGrainV2ServerEngine.push(message.getIp(), message.getPort(), BytesUtil.hexStrToBytes(hexStr));
    }
 
    private void analysisGrain2(IoMessage message, BaseReqData reqData, String grainStr) {
 
        GatewayDevice device = reqData.getDevice();
        // 获取完整的粮情包信息
        String[] attCable = device.getCableRule().split("-");
        int cableZ = Integer.valueOf(attCable[0]);
        int cableY = Integer.valueOf(attCable[1]);
        int cableX = Integer.valueOf(attCable[2]);
 
        // 根据层行列获取指定长度
        int start = 0;
        int len = 4 * cableZ * cableY * cableX;
 
        log.info("分机------>>>平台:返回粮情完整信息,分机={}", device.getDeviceName());
 
        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 = ProtocolUtils.ERROR_TEMP;
            } else {
                tempValue = BytesUtil.hexToInt(BytesUtil.tran_LH(temp)) / 10.0;
            }
            // 故障值处理
            if (tempValue >= ReMessageBuilder.FAULT_CHECK_TAG) {
                tempValue = ProtocolUtils.FAULT_TEMP;
            }
            temps.add(tempValue);
        }
 
 
        THDto thDto = this.getTH(message);
        if (null != thDto) {
            log.debug("-------THDto--={}", thDto);
        }
        //清空
        String key = "GRAIN_" + message.getAddr();
        contextMapGrain.put(key, null);
 
        // 将集合解析成坐标数据
        addPoint1(temps, reqData, thDto);
    }
 
 
    /**
     * 平房仓,解析第二步,解析到坐标数据
     *
     * @param temps
     * @throws Exception
     */
    private void addPoint1(List<Double> temps, BaseReqData reqData, THDto thDto) {
 
        GatewayDevice device = reqData.getDevice();
 
        String[] attCable = device.getCableRule().split("-");
        int cableZ = Integer.valueOf(attCable[0]);
        int cableY = Integer.valueOf(attCable[1]);
        int cableX = Integer.valueOf(attCable[2]);
 
        //数据封装
        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 < temps.size(); i++) {
            curTemp = temps.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 + ""));
 
            //求最大最小值
            if (curTemp < -900) {
                sumNum--;
            } else {
                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<>();
 
        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);
    }
 
 
    private void analysisTh(IoMessage message) {
        try {
            THDto th = new THDto();
            String data = message.getContent();
            String houseNo = data.substring(0, 4);
            int depotId = BytesUtil.hexToInt(BytesUtil.tran_LH(houseNo));
            String t = data.substring(4, 8);
            String h = data.substring(8, 12);
            double humy;
            String temp;
            int symbol = 0; //符号位
            double tempValue;
            if (ReMessageBuilder.ERROR_TAG.equals(t)) {
                temp = "0000";
            } else {
                temp = BytesUtil.tran_LH(t);
            }
            temp = BytesUtil.hexString2binaryString(temp, 16);
 
            //符号位
            symbol = Integer.valueOf(temp.substring(0, 1));
            //获取温度值
            tempValue = BytesUtil.biannary2Decimal(temp.substring(6)) / 10;
            //若为负,则补码:取反加1
            if (symbol == 1) {
                tempValue = 0.0 - BytesUtil.twoToString(temp) / 10;
            }
            th.setTempIn(tempValue);
            if (ReMessageBuilder.ERROR_TAG.equals(h)) {
                humy = 0.0;
            } else {
                humy = (double) BytesUtil.hexToBigInt(BytesUtil.tran_LH(h)) / 10;
            }
            th.setHumidityIn(humy);
            log.info("主机--------->>>平台,解析仓温仓湿信息,仓库={},结果={}", depotId, th.toString());
 
            String key = "TH_" + depotId;
            contextMapTH.put(key, th);
 
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            String hexStr = CommandBuild.getMsgTHReply(message.getAddr());
            log.info("平台--------->>>主机,返回仓温仓湿收到信息,报文={}", hexStr);
            BhznGrainV2ServerEngine.push(message.getIp(), message.getPort(), BytesUtil.hexStrToBytes(hexStr));
        }
    }
 
    private THDto getTH(IoMessage message) {
        String data = message.getContent();
        String houseNo = data.substring(0, 2);
        Integer depotId = BytesUtil.hexToInt(houseNo);
        String key = "TH_" + depotId;
        return contextMapTH.get(key);
    }
}