1
zhang
12 小时以前 6e7005a9c8f0e9c21f2d3a4d77a779381e859ac3
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
package com.zy.acs.conveyor.core.thread;
 
import HslCommunication.Core.Types.OperateResultExOne;
import HslCommunication.Profinet.Siemens.SiemensS7Net;
import com.zy.acs.common.utils.News;
import com.zy.acs.conveyor.core.constant.DeviceField;
import com.zy.acs.conveyor.core.constant.PlcAlarmDefinition;
import com.zy.acs.conveyor.core.constant.StationStatusField;
import com.zy.acs.conveyor.core.model.StaProtocol;
import com.zy.acs.conveyor.core.properties.DevpSlave;
import com.zy.acs.conveyor.core.service.DevpS7Service;
import com.zy.acs.conveyor.core.service.StationService;
import com.zy.acs.conveyor.entity.Devp;
import com.zy.acs.conveyor.service.DevpService;
import com.zy.acs.conveyor.utils.SpringContextUtil;
import com.zy.acs.framework.common.Cools;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
/**
 * 输送线线程
 * Created by vincent on 2020/8/4
 */
@Data
@Slf4j
public class SiemensDevpThread implements Runnable {
 
    private DevpSlave slave;
 
    private SiemensS7Net siemensS7Net;
 
    private Map<Integer, StaProtocol> station;
 
    private static final int WRITE_RETRY_MAX = 5;
 
    private static final int WRITE_RETRY_INTERVAL_MS = 200;
 
    private static final int READ_INTERVAL_MS = 100;
 
    private static final int DB_UPDATE_INTERVAL_MS = 2000; // 数据库更新间隔
 
    private long lastDbUpdateTime = 0;
 
 
    public SiemensDevpThread(DevpSlave slave, SiemensS7Net siemensS7Net, Map<Integer, StaProtocol> station) {
        this.slave = slave;
        this.siemensS7Net = siemensS7Net;
        this.station = station;
    }
 
 
    @Override
    @SuppressWarnings("InfiniteLoopStatement")
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                read();
                Thread.sleep(READ_INTERVAL_MS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.warn("SiemensDevp线程被中断 [id:{}]", slave.getId());
                break;
            } catch (Exception e) {
                log.error("SiemensDevp线程运行异常 [id:{}]", slave.getId(), e);
            }
        }
        log.info("SiemensDevp读线程已退出 [id:{}]", slave.getId());
    }
 
    /**
     * 读取状态 ====> 整块plc
     */
    private void read() throws InterruptedException {
        if (siemensS7Net == null) {
            DevpS7Service devpS7Service = SpringContextUtil.getBean(DevpS7Service.class);
            if (devpS7Service != null) {
                siemensS7Net = devpS7Service.get(slave.getId());
            }
            log.warn("PLC未连接,跳过读取 [id:{}]", slave.getId());
            return;
        }
        if (station == null) {
            StationService stationService = SpringContextUtil.getBean(StationService.class);
            if (stationService != null) {
                station = stationService.getStationMap(slave.getId());
            }
            log.warn("站点未连接,跳过读取 [id:{}]", slave.getId());
            return;
        }
 
        List<Integer> staNos = slave.getStaNos();
        int staNoSize = staNos.size();
 
        // 读取站点状态
        OperateResultExOne<byte[]> result = siemensS7Net.Read(
                StationStatusField.ALL.buildAddress(),
                (short) (staNoSize * StationStatusField.ALL.getByteLength()));
 
        if (!result.IsSuccess) {
            log.error("读取站点状态失败 [id:{}] [error:{}]", slave.getId(), result.Message);
            return;
        }
 
        byte[] content = result.Content;
        for (int i = 0; i < staNoSize; i++) {
            StaProtocol staProtocol = station.get(staNos.get(staNoSize));
            parseStationStatus(content, i, staProtocol);
        }
 
        // 读取条码
        readBarcodes();
 
        // 称重
        readWeight();
 
        // 读取外形检测错误
        readDimensionErrors();
 
        // 读取PLC故障
        readPlcAlarms(staNos, staNoSize);
 
        // 定期更新数据库(降低频率)
        updateDatabaseIfNeeded();
    }
 
    /**
     * 解析单个站点状态
     */
    private void parseStationStatus(byte[] content, int index, StaProtocol staProtocol) {
        int offset = index * StationStatusField.ALL.getByteLength();
        staProtocol.setWorkNo(siemensS7Net.getByteTransform().TransInt32(content, offset));
        staProtocol.setStaNo((int) siemensS7Net.getByteTransform().TransInt16(
                content, offset + StationStatusField.FINAL_TARGET.getOffset()));
 
        boolean[] status = siemensS7Net.getByteTransform().TransBool(
                content, offset + StationStatusField.STATUS_WORD.getOffset(),
                StationStatusField.STATUS_WORD.getByteLength());
 
        staProtocol.setAutoing(status[0]);
        staProtocol.setLoading(status[1]);
        staProtocol.setInEnable(status[2]);
        staProtocol.setOutEnable(status[3]);
        staProtocol.setEmptyMk(status[4]);
        staProtocol.setFullPlt(status[5]);
        staProtocol.setHigh(status[6]);
        staProtocol.setLow(status[7]);
 
 
    }
 
    /**
     * 读取条码信息
     */
    private void readBarcodes() {
        List<Integer> barcodeArr = slave.getBarcodeArr();
        if (barcodeArr == null || barcodeArr.isEmpty()) {
            return;
        }
 
        OperateResultExOne<byte[]> result = siemensS7Net.Read(
                DeviceField.BARCODE.buildAddress(),
                (short) (barcodeArr.size() * DeviceField.BARCODE.getByteLength()));
 
        if (!result.IsSuccess) {
            log.warn("读取条码失败 [id:{}]", slave.getId());
            return;
        }
 
        byte[] content = result.Content;
        for (int i = 0; i < barcodeArr.size(); i++) {
            String barcode = siemensS7Net.getByteTransform().TransString(
                    content, i * DeviceField.BARCODE.getByteLength(),
                    DeviceField.BARCODE.getByteLength(), "UTF-8");
 
            if (!Cools.isEmpty(barcode)) {
                StaProtocol staProtocol = station.get(barcodeArr.get(i));
                if (staProtocol == null) {
                    log.warn("站点不存在 [id:{}] [staNo:{}]", slave.getId(), barcodeArr.get(i));
                    continue;
                }
                staProtocol.setBarcode(barcode);
                News.info("料箱码:{}", barcode);
            }
        }
    }
 
    /**
     * 读取条码信息
     */
    private void readWeight() {
        List<Integer> weightArr = slave.getWeightArr();
        if (weightArr == null || weightArr.isEmpty()) {
            return;
        }
 
        OperateResultExOne<byte[]> result = siemensS7Net.Read(
                DeviceField.WEIGHT.buildAddress(),
                (short) (weightArr.size() * DeviceField.WEIGHT.getByteLength()));
 
        if (!result.IsSuccess) {
            log.warn("读取重量失败 [id:{}]", slave.getId());
            return;
        }
        for (int i = 0; i < weightArr.size(); i++) {
            StaProtocol staProtocol = station.get(weightArr.get(i));
            if (staProtocol == null) {
                log.warn("站点不存在 [id:{}] [staNo:{}]", slave.getId(), weightArr.get(i));
                continue;
            }
            double weight = siemensS7Net.getByteTransform().TransSingle(result.Content, i * DeviceField.WEIGHT.getByteLength());
            staProtocol.setWeight(BigDecimal.valueOf(weight).setScale(4, RoundingMode.HALF_UP).doubleValue());
        }
    }
 
    /**
     * 读取外形检测错误
     */
    private void readDimensionErrors() {
        List<Integer> staNosError = slave.getStaNosError();
        if (staNosError == null || staNosError.isEmpty()) {
            return;
        }
 
        OperateResultExOne<byte[]> result = siemensS7Net.Read(
                DeviceField.DIMENSION_WORD.buildAddress(),
                (short) (staNosError.size() * DeviceField.DIMENSION_WORD.getByteLength()));
 
        if (!result.IsSuccess) {
            log.warn("读取外形检测错误失败 [id:{}]", slave.getId());
            return;
        }
 
        byte[] content = result.Content;
        for (int i = 0; i < staNosError.size(); i++) {
            Integer siteId = staNosError.get(i);
            StaProtocol staProtocol = station.get(siteId);
            if (staProtocol == null){
                log.warn("站点不存在 [id:{}] [staNo:{}]", slave.getId(), staNosError.get(i));
                continue;
            }
 
            boolean[] status = siemensS7Net.getByteTransform().TransBool(
                    content, i * DeviceField.DIMENSION_WORD.getByteLength(),
                    DeviceField.DIMENSION_WORD.getByteLength());
 
            staProtocol.setFrontErr(status[0]);
            staProtocol.setBackErr(status[1]);
            staProtocol.setHighErr(status[2]);
            staProtocol.setLeftErr(status[3]);
            staProtocol.setRightErr(status[4]);
            staProtocol.setWeightErr(status[5]);
            staProtocol.setBarcodeErr(status[6]);
        }
    }
 
    /**
     * 读取PLC故障信息
     */
    private void readPlcAlarms(List<Integer> staNos, int staNoSize) {
        OperateResultExOne<byte[]> result = siemensS7Net.Read(
                PlcAlarmDefinition.ALL.buildAddress(),
                (short) (staNoSize * PlcAlarmDefinition.ALL.getByteLength()));
 
        if (!result.IsSuccess) {
            log.warn("读取PLC故障信息失败 [id:{}]", slave.getId());
            return;
        }
 
        byte[] content = result.Content;
        for (int i = 0; i < staNoSize; i++) {
            Integer siteId = staNos.get(i);
            StaProtocol staProtocol = station.get(siteId);
            if (staProtocol == null) {
                log.warn("站点不存在 [id:{}] [staNo:{}]", slave.getId(), siteId);
                continue;
            }
 
            boolean[] status = siemensS7Net.getByteTransform().TransBool(
                    content, i * PlcAlarmDefinition.ALL.getByteLength(), 1);
 
            staProtocol.setBreakerErr(status[0]);
            staProtocol.setInfraredErr(status[1]);
            staProtocol.setOutTimeErr(status[2]);
            staProtocol.setSeizeSeatErr(status[3]);
            staProtocol.setWrkYgoodsN(status[4]);
            staProtocol.setInverterErr(status[5]);
            staProtocol.setContactErr(status[6]);
            staProtocol.setUpcontactErr(status[7]);
        }
    }
 
    /**
     * 按需更新数据库(降低更新频率)
     */
    private void updateDatabaseIfNeeded() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastDbUpdateTime < DB_UPDATE_INTERVAL_MS) {
            return;
        }
 
        try {
            List<Integer> staNos = slave.getStaNos();
            List<Devp> devps = new ArrayList<>(staNos.size());
            for (Integer siteId : staNos) {
                StaProtocol staProtocol = station.get(siteId);
                if (staProtocol != null) {
                    devps.add(staProtocol.toSqlModel());
                }
            }
 
            if (devps.isEmpty()) {
                return;
            }
 
            DevpService devpService = SpringContextUtil.getBean(DevpService.class);
            if (devpService != null) {
                devpService.updateBatchByDevpNo(devps);
                lastDbUpdateTime = currentTime;
                log.debug("批量更新数据库成功 [id:{}] [count:{}]", slave.getId(), devps.size());
            } else {
                log.error("DevpService未找到,无法更新数据库 [id:{}]", slave.getId());
            }
        } catch (Exception e) {
            log.error("更新数据库数据失败 [id:{}]", slave.getId(), e);
            News.error("SiemensDevp - 3 - 更新数据库数据失败 ===>> [id:{}]", slave.getId());
        }
    }
 
 
}