package com.mes.plc.client.impl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mes.connect.modbus.ModbusTcpClient;
import com.mes.device.entity.DeviceConfig;
import com.mes.device.util.ConfigJsonHelper;
import com.mes.plc.client.PlcClient;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.*;
/**
* Modbus协议PLC客户端实现
*
* 基于项目中已有的Modbus实现
*
*
* @author huang
* @date 2025/12/19
*/
@Slf4j
public class ModbusPlcClient implements PlcClient {
// PLC IP地址
private final String plcIp;
// PLC端口
private final int plcPort;
// 从站地址
private final int unitId;
// 设备配置
private final DeviceConfig device;
// Modbus客户端实例
private ModbusTcpClient modbusClient;
// 连接状态
private boolean connected = false;
// 超时时间(毫秒)
private int timeout = 5000;
// ObjectMapper用于JSON解析
private final ObjectMapper objectMapper = new ObjectMapper();
// 地址映射缓存:字段名 -> Modbus地址
private Map addressMappingCache;
/**
* 构造函数
*
* @param device 设备配置
*/
public ModbusPlcClient(DeviceConfig device) {
this.device = device;
this.plcIp = device.getPlcIp();
this.plcPort = device.getPlcPort() != null ? device.getPlcPort() : 502;
// 从配置中获取从站地址,默认1
int unitIdValue = 1;
try {
Map extraParams = parseExtraParams(device.getExtraParams());
if (extraParams != null) {
Object unitIdObj = extraParams.get("unitId");
if (unitIdObj instanceof Number) {
unitIdValue = ((Number) unitIdObj).intValue();
} else if (unitIdObj instanceof String) {
unitIdValue = Integer.parseInt((String) unitIdObj);
}
}
} catch (Exception e) {
log.warn("解析unitId失败,使用默认值1: deviceId={}", device.getId(), e);
}
this.unitId = unitIdValue;
// 初始化地址映射
this.addressMappingCache = loadAddressMapping();
}
/**
* 解析设备的extraParams
*
* @param extraParamsJson extraParams的JSON字符串
* @return 解析后的Map
*/
private Map parseExtraParams(String extraParamsJson) {
if (extraParamsJson == null || extraParamsJson.isEmpty()) {
return new HashMap<>();
}
try {
TypeReference