huang
2025-11-20 366ba040d2447bacd3455299425e3166f1f992bb
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
package com.mes.service;
 
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import com.mes.device.entity.DeviceConfig;
import com.mes.device.service.DeviceConfigService;
import com.mes.device.util.ConfigJsonHelper;
import com.mes.service.PlcDynamicDataService;
import com.mes.s7.enhanced.EnhancedS7Serializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
 
/**
 * PLC测试写入服务
 * 
 * 基于DeviceConfig的新API,用于模拟PLC行为进行测试
 * 
 * 推荐使用:DevicePlcOperationService(生产环境)
 * 
 * @author huang
 * @date 2025/10/29
 */
@Slf4j
@Service
public class PlcTestWriteService {
 
    @Resource
    private DeviceConfigService deviceConfigService;
    
    @Resource
    private PlcDynamicDataService plcDynamicDataService;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<Map<String, Object>>() {};
 
    private static final int ON = 1;
    private static final int OFF = 0;
    
    // 缓存不同设备的S7Serializer实例
    private final ConcurrentMap<String, EnhancedS7Serializer> serializerCache = new ConcurrentHashMap<>();
 
    // ==================== 基于DeviceConfig的新API(推荐使用) ====================
    
    /**
     * 根据设备ID模拟PLC发送请求字
     * 
     * @param deviceId 设备ID
     * @return 是否成功
     */
    public boolean simulatePlcRequestByDevice(Long deviceId) {
        DeviceConfig device = deviceConfigService.getDeviceById(deviceId);
        if (device == null) {
            log.error("设备不存在: deviceId={}", deviceId);
            return false;
        }
        try {
            EnhancedS7Serializer s7Serializer = getSerializerForDevice(device);
            if (s7Serializer == null) {
                log.error("获取S7Serializer失败: deviceId={}", deviceId);
                return false;
            }
            
            // 使用PlcDynamicDataService读取数据(支持addressMapping)
            Map<String, Object> currentData = plcDynamicDataService.readAllPlcData(device, s7Serializer);
            if (currentData == null || currentData.isEmpty()) {
                log.error("读取PLC数据失败,返回空: deviceId={}", deviceId);
                return false;
            }
            
            // 检查联机状态
            Object onlineStateObj = currentData.get("onlineState");
            Integer onlineState = null;
            if (onlineStateObj != null) {
                if (onlineStateObj instanceof Number) {
                    onlineState = ((Number) onlineStateObj).intValue();
                } else {
                    try {
                        String strValue = String.valueOf(onlineStateObj);
                        if (!strValue.isEmpty() && !"null".equalsIgnoreCase(strValue)) {
                            onlineState = Integer.parseInt(strValue);
                        }
                    } catch (NumberFormatException e) {
                        log.warn("解析onlineState失败: deviceId={}, value={}", deviceId, onlineStateObj, e);
                    }
                }
            }
            
            if (onlineState != null && onlineState == OFF) {
                log.info("当前PLC联机模式为0,停止联机: deviceId={}", deviceId);
                return false;
            }
            
            // 检查汇报字,如果为1则重置为0
            Object plcReportObj = currentData.get("plcReport");
            Integer plcReport = null;
            if (plcReportObj != null) {
                if (plcReportObj instanceof Number) {
                    plcReport = ((Number) plcReportObj).intValue();
                } else {
                    try {
                        String strValue = String.valueOf(plcReportObj);
                        if (!strValue.isEmpty() && !"null".equalsIgnoreCase(strValue)) {
                            plcReport = Integer.parseInt(strValue);
                        }
                    } catch (NumberFormatException e) {
                        log.warn("解析plcReport失败: deviceId={}, value={}", deviceId, plcReportObj, e);
                    }
                }
            }
            
            if (plcReport != null && plcReport == ON) {
                log.info("当前上片PLC汇报字为1,重置为0: deviceId={}", deviceId);
                currentData.put("plcReport", OFF);
            }
            
            // 设置请求字为1
            currentData.put("plcRequest", ON);
            
            // 使用PlcDynamicDataService写入数据
            plcDynamicDataService.writePlcData(device, currentData, s7Serializer);
            
            log.info("模拟PLC发送请求字成功:plcRequest=1, deviceId={}", deviceId);
            return true;
        } catch (Exception e) {
            log.error("根据设备模拟PLC请求字失败: deviceId={}", deviceId, e);
            return false;
        }
    }
    
    /**
     * 根据设备ID模拟PLC任务完成汇报
     * 
     * @param deviceId 设备ID
     * @return 是否成功
     */
    public boolean simulatePlcReportByDevice(Long deviceId) {
        DeviceConfig device = deviceConfigService.getDeviceById(deviceId);
        if (device == null) {
            log.error("设备不存在: deviceId={}", deviceId);
            return false;
        }
        try {
            EnhancedS7Serializer s7Serializer = getSerializerForDevice(device);
            if (s7Serializer == null) {
                log.error("获取S7Serializer失败: deviceId={}", deviceId);
                return false;
            }
            
            // 使用PlcDynamicDataService读取数据
            Map<String, Object> currentData = plcDynamicDataService.readAllPlcData(device, s7Serializer);
            if (currentData == null || currentData.isEmpty()) {
                log.error("读取PLC数据失败,返回空: deviceId={}", deviceId);
                return false;
            }
            
            // 设置汇报字为1,请求字清0
            currentData.put("plcReport", ON);
            currentData.put("plcRequest", OFF);
            currentData.put("mesGlassCount", 10);
            
            // 使用PlcDynamicDataService写入数据
            plcDynamicDataService.writePlcData(device, currentData, s7Serializer);
            
            log.info("模拟PLC任务完成汇报:plcReport=1, mesGlassCount=10, deviceId={}", deviceId);
            return true;
        } catch (Exception e) {
            log.error("根据设备模拟PLC汇报失败: deviceId={}", deviceId, e);
            return false;
        }
    }
    
    /**
     * 根据设备ID重置PLC所有状态
     * 
     * @param deviceId 设备ID
     * @return 是否成功
     */
    public boolean resetPlcByDevice(Long deviceId) {
        DeviceConfig device = deviceConfigService.getDeviceById(deviceId);
        if (device == null) {
            log.error("设备不存在: deviceId={}", deviceId);
            return false;
        }
        try {
            EnhancedS7Serializer s7Serializer = getSerializerForDevice(device);
            if (s7Serializer == null) {
                log.error("获取S7Serializer失败: deviceId={}", deviceId);
                return false;
            }
            
            // 构建重置数据
            Map<String, Object> resetData = new HashMap<>();
            resetData.put("plcRequest", OFF);
            resetData.put("plcReport", OFF);
            resetData.put("mesSend", OFF);
            resetData.put("mesConfirm", OFF);
            resetData.put("onlineState", ON);
            resetData.put("mesGlassCount", 0);
            resetData.put("alarmInfo", OFF);
            
            // 使用PlcDynamicDataService写入数据
            plcDynamicDataService.writePlcData(device, resetData, s7Serializer);
            
            log.info("PLC状态已重置, deviceId={}", deviceId);
            return true;
        } catch (Exception e) {
            log.error("根据设备重置PLC状态失败: deviceId={}", deviceId, e);
            return false;
        }
    }
    
    /**
     * 根据设备ID读取PLC当前状态
     * 
     * @param deviceId 设备ID
     * @return PLC状态数据
     */
    public Map<String, Object> readPlcStatusByDevice(Long deviceId) {
        DeviceConfig device = deviceConfigService.getDeviceById(deviceId);
        if (device == null) {
            log.error("设备不存在: deviceId={}", deviceId);
            return null;
        }
        try {
            EnhancedS7Serializer s7Serializer = getSerializerForDevice(device);
            if (s7Serializer == null) {
                log.error("获取S7Serializer失败: deviceId={}", deviceId);
                return null;
            }
            // 使用PlcDynamicDataService读取所有数据(支持addressMapping)
            Map<String, Object> data = plcDynamicDataService.readAllPlcData(device, s7Serializer);
            return data;
        } catch (Exception e) {
            log.error("读取设备PLC状态失败: deviceId={}", deviceId, e);
            return null;
        }
    }
    
    /**
     * 根据设备ID写入PLC字段
     * 
     * @param deviceId 设备ID
     * @param fieldValues 字段名->值 的Map
     * @return 是否成功
     */
    public boolean writeFieldsByDevice(Long deviceId, Map<String, Object> fieldValues) {
        DeviceConfig device = deviceConfigService.getDeviceById(deviceId);
        if (device == null) {
            log.error("设备不存在: deviceId={}", deviceId);
            return false;
        }
        
        try {
            // 获取对应的S7Serializer(使用设备配置)
            EnhancedS7Serializer s7Serializer = getSerializerForDevice(device);
            if (s7Serializer == null) {
                log.error("获取S7Serializer失败: deviceId={}", deviceId);
                return false;
            }
            
            // 使用动态数据服务写入字段(基于DeviceConfig)
            plcDynamicDataService.writePlcData(device, fieldValues, s7Serializer);
            
            log.info("写入PLC字段成功: deviceId={}, fields={}", deviceId, fieldValues.keySet());
            return true;
        } catch (Exception e) {
            log.error("写入PLC字段失败: deviceId={}", deviceId, e);
            return false;
        }
    }
    
    /**
     * 获取设备对应的S7Serializer实例
     * 
     * @param device 设备配置
     * @return S7Serializer实例
     */
    private EnhancedS7Serializer getSerializerForDevice(DeviceConfig device) {
        if (device == null) {
            log.error("设备配置为空,无法创建S7Serializer");
            return null;
        }
        
        try {
            String cacheKey;
            if (device.getId() != null) {
                cacheKey = "device:" + device.getId();
            } else {
                try {
                    cacheKey = "device:" + resolveProjectId(device);
                } catch (Exception e) {
                    cacheKey = "device:" + (device.getDeviceCode() != null ? device.getDeviceCode() : "unknown");
                }
            }
            
            return serializerCache.computeIfAbsent(cacheKey, id -> {
                try {
                    // 解析PLC类型(仅取实体字段)
                    EPlcType plcType = EPlcType.S1200;
                    String plcTypeValue = device.getPlcType();
                    if (plcTypeValue == null || plcTypeValue.isEmpty()) {
                        log.warn("设备未配置PLC类型,使用默认类型S1200, deviceId={}", device.getId());
                    } else {
                        try {
                            plcType = EPlcType.valueOf(plcTypeValue);
                        } catch (IllegalArgumentException e) {
                            log.warn("未知的PLC类型: {}, 使用默认类型 S1200", plcTypeValue);
                        }
                    }
                    
                    // 创建S7PLC实例(仅取实体字段)
                    String plcIp = device.getPlcIp();
                    if (plcIp == null || plcIp.isEmpty()) {
                        log.warn("设备未配置PLC IP,使用默认 192.168.10.21, deviceId={}", device.getId());
                        plcIp = "192.168.10.21";
                    }
                    S7PLC s7Plc = new S7PLC(plcType, plcIp);
                    
                    // 创建并返回EnhancedS7Serializer实例
                    EnhancedS7Serializer serializer = EnhancedS7Serializer.newInstance(s7Plc);
                    if (serializer == null) {
                        log.error("创建EnhancedS7Serializer失败: deviceId={}, plcIp={}, plcType={}", 
                            device.getId(), plcIp, plcType);
                    }
                    return serializer;
                } catch (Exception e) {
                    log.error("创建S7Serializer异常: deviceId={}", device.getId(), e);
                    return null;
                }
            });
        } catch (Exception e) {
            log.error("获取S7Serializer失败: deviceId={}", device.getId(), e);
            return null;
        }
    }
    
 
    private Map<String, Object> parseExtraParams(DeviceConfig device) {
        if (device.getExtraParams() == null || device.getExtraParams().trim().isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            return objectMapper.readValue(device.getExtraParams(), MAP_TYPE);
        } catch (Exception e) {
            log.warn("解析设备extraParams失败, deviceId={}", device.getId(), e);
            return Collections.emptyMap();
        }
    }
 
    @SuppressWarnings("unchecked")
    private Map<String, Object> getPlcConfigParams(DeviceConfig device) {
        Map<String, Object> extraParams = parseExtraParams(device);
        Object plcConfig = extraParams.get("plcConfig");
        if (plcConfig instanceof Map) {
            return (Map<String, Object>) plcConfig;
        }
        if (plcConfig instanceof String) {
            try {
                return objectMapper.readValue((String) plcConfig, MAP_TYPE);
            } catch (Exception e) {
                log.warn("解析extraParams.plcConfig失败, deviceId={}", device.getId(), e);
            }
        }
        return Collections.emptyMap();
    }
 
    private int parseInteger(Object value) {
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.parseInt(String.valueOf(value));
        } catch (NumberFormatException ex) {
            log.warn("无法解析整型值: {}", value);
            return 0;
        }
    }
 
    /**
     * 从设备配置中解析项目标识
     * 
     * @param device 设备配置
     * @return 项目标识
     */
    private String resolveProjectId(DeviceConfig device) {
        if (device == null) {
            throw new IllegalArgumentException("设备信息为空");
        }
        
        // 1. 优先使用实体上的projectId
        if (device.getProjectId() != null) {
            return String.valueOf(device.getProjectId());
        }
 
        // 2. 从extraParams中读取
        Map<String, Object> extraParams = parseExtraParams(device);
        Object plcProjectId = extraParams.get("plcProjectId");
        if (plcProjectId != null) {
            return String.valueOf(plcProjectId);
        }
 
        // 3. 兼容旧结构:configJson或extraParams内嵌
        Map<String, Object> configParams = ConfigJsonHelper.parseToMap(device.getConfigJson(), objectMapper);
        Object legacyProjectId = configParams.get("plcProjectId");
        if (legacyProjectId != null) {
            return String.valueOf(legacyProjectId);
        }
        
        // 最后使用设备编号
        if (device.getDeviceCode() != null && !device.getDeviceCode().isEmpty()) {
            return device.getDeviceCode();
        }
        
        throw new IllegalStateException("无法解析设备的PLC项目标识, deviceId=" + device.getId());
    }
}