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
package com.mes.device.controller;
 
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mes.device.entity.DeviceConfig;
import com.mes.device.request.DeviceConfigRequest;
import com.mes.device.service.DeviceConfigService;
import com.mes.device.vo.DeviceConfigVO;
import com.mes.device.vo.StatisticsVO;
import com.mes.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
 
/**
 * 设备配置管理控制器
 * 
 * @author mes
 * @since 2024-10-30
 */
@Slf4j
@RestController
@RequestMapping("device/config")
@Api(tags = "设备配置管理")
public class DeviceConfigController {
 
    @Autowired
    private DeviceConfigService deviceConfigService;
 
    @Autowired
    private ObjectMapper objectMapper;
 
    /**
     * 创建设备配置
     */
    @PostMapping("/devices")
    @ApiOperation("创建设备配置")
    public Result<DeviceConfig> createDevice(
            @Valid @RequestBody DeviceConfig deviceConfig) {
        try {
            boolean success = deviceConfigService.createDevice(deviceConfig);
            if (success) {
                // 创建成功后,重新获取设备对象
                DeviceConfig created = deviceConfigService.getDeviceByCode(deviceConfig.getDeviceCode());
                return Result.success(created);
            } else {
                return Result.error("设备配置已存在");
            }
        } catch (Exception e) {
            log.error("创建设备配置失败", e);
            return Result.error("创建设备配置失败");
        }
    }
 
    /**
     * 更新设备配置
     */
    @PostMapping("/devices/update")
    @ApiOperation("更新设备配置")
    public Result<DeviceConfig> updateDevice(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            DeviceConfig deviceConfig;
            Object deviceConfigObj = request.getDeviceConfig();
            
            // 如果 deviceConfig 是 Map 类型(JSON 反序列化后的 LinkedHashMap),需要转换为 DeviceConfig
            if (deviceConfigObj instanceof Map) {
                deviceConfig = objectMapper.convertValue(deviceConfigObj, DeviceConfig.class);
            } else if (deviceConfigObj instanceof DeviceConfig) {
                deviceConfig = (DeviceConfig) deviceConfigObj;
            } else {
                log.error("不支持的 deviceConfig 类型: {}", deviceConfigObj != null ? deviceConfigObj.getClass() : "null");
                return Result.error("设备配置数据格式错误");
            }
            
            deviceConfig.setId(request.getDeviceId());
            boolean success = deviceConfigService.updateDevice(deviceConfig);
            if (success) {
                // 更新成功后,重新获取设备对象
                DeviceConfig updated = deviceConfigService.getDeviceById(request.getDeviceId());
                return Result.success(updated);
            } else {
                return Result.error("设备配置不存在");
            }
        } catch (Exception e) {
            log.error("更新设备配置失败", e);
            return Result.error("更新设备配置失败: " + e.getMessage());
        }
    }
 
    /**
     * 删除设备配置
     */
    @PostMapping("/devices/delete")
    @ApiOperation("删除设备配置")
    public Result<Void> deleteDevice(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            deviceConfigService.deleteDevice(request.getDeviceId());
            return Result.success(null);
        } catch (Exception e) {
            log.error("删除设备配置失败", e);
            return Result.error("删除设备配置失败");
        }
    }
 
    /**
     * 根据ID获取设备配置
     */
    @PostMapping("/devices/detail")
    @ApiOperation("获取设备配置详情")
    public Result<DeviceConfig> getDeviceById(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            DeviceConfig device = deviceConfigService.getDeviceById(request.getDeviceId());
            return Result.success(device);
        } catch (Exception e) {
            log.error("获取设备配置失败", e);
            return Result.error("获取设备配置失败");
        }
    }
 
    /**
     * 分页查询设备配置列表
     */
    @PostMapping("/devices/list")
    @ApiOperation("分页查询设备配置")
    public Result<Page<DeviceConfigVO.DeviceInfo>> getDeviceList(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            Page<DeviceConfigVO.DeviceInfo> pageResult = deviceConfigService.getDeviceList(
                request.getProjectId(),
                request.getDeviceType(),
                request.getDeviceStatus(),
                request.getKeyword(),
                request.getPage() != null ? request.getPage() : 1,
                request.getSize() != null ? request.getSize() : 10);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询设备配置列表失败", e);
            return Result.error("查询设备配置列表失败");
        }
    }
 
    /**
     * 启用设备
     */
    @PostMapping("/devices/enable")
    @ApiOperation("启用设备")
    public Result<Void> enableDevice(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            deviceConfigService.enableDevice(request.getDeviceId());
            return Result.success(null);
        } catch (Exception e) {
            log.error("启用设备失败", e);
            return Result.error("启用设备失败");
        }
    }
 
    /**
     * 禁用设备
     */
    @PostMapping("/devices/disable")
    @ApiOperation("禁用设备")
    public Result<Void> disableDevice(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            deviceConfigService.disableDevice(request.getDeviceId());
            return Result.success(null);
        } catch (Exception e) {
            log.error("禁用设备失败", e);
            return Result.error("禁用设备失败");
        }
    }
 
    /**
     * 批量启用设备
     */
    @PostMapping("/devices/batch-enable")
    @ApiOperation("批量启用设备")
    public Result<Void> batchEnableDevices(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            deviceConfigService.batchEnableDevices(request.getDeviceIds());
            return Result.success(null);
        } catch (Exception e) {
            log.error("批量启用设备失败", e);
            return Result.error("批量启用设备失败");
        }
    }
 
    /**
     * 批量禁用设备
     */
    @PostMapping("/devices/batch-disable")
    @ApiOperation("批量禁用设备")
    public Result<Void> batchDisableDevices(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            deviceConfigService.batchDisableDevices(request.getDeviceIds());
            return Result.success(null);
        } catch (Exception e) {
            log.error("批量禁用设备失败", e);
            return Result.error("批量禁用设备失败");
        }
    }
 
    /**
     * 获取设备统计信息
     */
    @PostMapping("/statistics/devices")
    @ApiOperation("获取设备统计信息")
    public Result<StatisticsVO.DeviceStatistics> getDeviceStatistics(
            @ApiParam("设备配置请求") @RequestBody(required = false) DeviceConfigRequest request) {
        try {
            StatisticsVO.DeviceStatistics statistics = deviceConfigService.getDeviceStatistics(request != null ? request.getProjectId() : null);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取设备统计信息失败", e);
            return Result.error("获取设备统计信息失败");
        }
    }
 
    /**
     * 检查设备编码是否已存在
     */
    @PostMapping("/devices/check-code")
    @ApiOperation("检查设备编码")
    public Result<Boolean> checkDeviceCodeExists(
            @ApiParam("设备配置请求") @RequestBody DeviceConfigRequest request) {
        try {
            boolean exists = deviceConfigService.isDeviceCodeExists(request.getDeviceCode(), request.getDeviceId());
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查设备编码失败", e);
            return Result.error("检查设备编码失败");
        }
    }
 
    /**
     * 获取设备类型列表
     */
    @PostMapping("/devices/types")
    @ApiOperation("获取设备类型列表")
    public Result<List<String>> getDeviceTypes(@RequestBody(required = false) Map<String, Object> request) {
        try {
            List<String> deviceTypes = deviceConfigService.getAllDeviceTypes();
            return Result.success(deviceTypes);
        } catch (Exception e) {
            log.error("获取设备类型列表失败", e);
            return Result.error("获取设备类型列表失败");
        }
    }
 
    /**
     * 获取设备状态列表
     */
    @PostMapping("/devices/statuses")
    @ApiOperation("获取设备状态列表")
    public Result<List<String>> getDeviceStatuses(@RequestBody(required = false) Map<String, Object> request) {
        try {
            List<String> deviceStatuses = deviceConfigService.getAllDeviceStatuses();
            return Result.success(deviceStatuses);
        } catch (Exception e) {
            log.error("获取设备状态列表失败", e);
            return Result.error("获取设备状态列表失败");
        }
    }
 
    /**
     * 获取设备配置树结构
     */
    @PostMapping("/devices/tree")
    @ApiOperation("获取设备配置树结构")
    public Result<List<DeviceConfigVO.DeviceTreeNode>> getDeviceTree(
            @ApiParam("设备配置请求") @RequestBody(required = false) DeviceConfigRequest request) {
        try {
            List<DeviceConfigVO.DeviceTreeNode> treeData = deviceConfigService.getDeviceTree(request != null ? request.getProjectId() : null);
            return Result.success(treeData);
        } catch (Exception e) {
            log.error("获取设备配置树结构失败", e);
            return Result.error("获取设备配置树结构失败");
        }
    }
 
    /**
     * 设备健康检查
     */
    @PostMapping("/devices/health-check")
    @ApiOperation("设备健康检查")
    public Result<DeviceConfigVO.HealthCheckResult> performHealthCheck(
            @Valid @RequestBody DeviceConfigRequest request) {
        try {
            DeviceConfigVO.HealthCheckResult result = deviceConfigService.performHealthCheck(request.getDeviceId());
            return Result.success(result);
        } catch (Exception e) {
            log.error("设备健康检查失败", e);
            return Result.error("设备健康检查失败");
        }
    }
 
    /**
     * 测试设备PLC连接
     * 支持两种方式:
     * 1. 传入 deviceId,根据已保存的设备配置测试
     * 2. 直接传入 plcIp / plcPort / timeout 进行一次性测试
     */
    @PostMapping("/devices/test-connection")
    @ApiOperation("测试设备PLC连接")
    public Result<String> testDeviceConnection(@RequestBody Map<String, Object> body) {
        try {
            String plcIp = null;
            Integer plcPort = null;
            Integer timeoutMs = null;
 
            // 优先根据 deviceId 读取已保存配置
            Object deviceIdObj = body.get("deviceId");
            if (deviceIdObj != null) {
                Long deviceId = deviceIdObj instanceof Number
                        ? ((Number) deviceIdObj).longValue()
                        : Long.parseLong(deviceIdObj.toString());
                DeviceConfig device = deviceConfigService.getDeviceById(deviceId);
                if (device == null) {
                    return Result.error("设备不存在: " + deviceId);
                }
                plcIp = device.getPlcIp();
                plcPort = device.getPlcPort();
                timeoutMs = 3000;
            } else {
                // 直接从请求体中获取测试参数
                Object ipObj = body.get("plcIp");
                Object portObj = body.get("plcPort");
                Object timeoutObj = body.get("timeout");
                if (ipObj != null) {
                    plcIp = String.valueOf(ipObj);
                }
                if (portObj instanceof Number) {
                    plcPort = ((Number) portObj).intValue();
                } else if (portObj != null) {
                    plcPort = Integer.parseInt(portObj.toString());
                }
                if (timeoutObj instanceof Number) {
                    timeoutMs = ((Number) timeoutObj).intValue() * 1000;
                } else if (timeoutObj != null) {
                    timeoutMs = Integer.parseInt(timeoutObj.toString()) * 1000;
                }
            }
 
            if (plcIp == null || plcIp.trim().isEmpty()) {
                return Result.error("PLC IP不能为空");
            }
            if (plcPort == null || plcPort <= 0 || plcPort > 65535) {
                plcPort = 102;
            }
            if (timeoutMs == null || timeoutMs <= 0) {
                timeoutMs = 3000;
            }
 
            boolean ok = testTcpConnection(plcIp, plcPort, timeoutMs);
            if (ok) {
                String msg = String.format("连接测试成功:%s:%d", plcIp, plcPort);
                log.info(msg);
                return Result.success(msg);
            } else {
                String msg = String.format("连接测试失败:%s:%d", plcIp, plcPort);
                log.warn(msg);
                return Result.error(msg);
            }
        } catch (Exception e) {
            log.error("设备PLC连接测试失败", e);
            return Result.error("连接测试异常: " + e.getMessage());
        }
    }
 
    private boolean testTcpConnection(String ip, int port, int timeoutMs) {
        java.net.Socket socket = null;
        try {
            socket = new java.net.Socket();
            socket.connect(new java.net.InetSocketAddress(ip, port), timeoutMs);
            return true;
        } catch (Exception e) {
            log.warn("TCP连接测试失败: {}:{}, err={}", ip, port, e.getMessage());
            return false;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception ignore) {
                }
            }
        }
    }
}