huang
9 小时以前 fc4e5c458094c6bf5238d7d21291325f19a57adb
mes-processes/mes-plcSend/src/main/java/com/mes/plc/client/impl/ModbusPlcClient.java
@@ -1,5 +1,6 @@
package com.mes.plc.client.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mes.connect.modbus.ModbusTcpClient;
import com.mes.device.entity.DeviceConfig;
import com.mes.plc.client.PlcClient;
@@ -30,6 +31,9 @@
    // 从站地址
    private final int unitId;
    
    // 设备配置
    private final DeviceConfig device;
    // Modbus客户端实例
    private ModbusTcpClient modbusClient;
    
@@ -39,12 +43,19 @@
    // 超时时间(毫秒)
    private int timeout = 5000;
    
    // ObjectMapper用于JSON解析
    private final ObjectMapper objectMapper = new ObjectMapper();
    // 地址映射缓存:字段名 -> Modbus地址
    private Map<String, String> addressMappingCache;
    /**
     * 构造函数
     *
     * @param device 设备配置
     */
    public ModbusPlcClient(DeviceConfig device) {
        this.device = device;
        this.plcIp = device.getPlcIp();
        this.plcPort = device.getPlcPort() != null ? device.getPlcPort() : 502;
        
@@ -74,7 +85,7 @@
     */
    private Map<String, Object> parseExtraParams(String extraParamsJson) {
        if (extraParamsJson == null || extraParamsJson.isEmpty()) {
            return null;
            return new HashMap<>();
        }
        
        try {
@@ -150,6 +161,10 @@
            return Collections.emptyMap();
        }
        
        if (fields == null || fields.length == 0) {
            return readAllData();
        }
        try {
            // TODO: 实现Modbus读取指定字段数据
            // 这里暂时返回空Map,后续完善
@@ -161,12 +176,17 @@
            return Collections.emptyMap();
        }
    }
    @Override
    public boolean writeData(Map<String, Object> data) {
        if (!isConnected() && !connect()) {
            log.error("Modbus PLC未连接,无法写入数据: {}:{}", this.plcIp, this.plcPort);
            return false;
        }
        if (data == null || data.isEmpty()) {
            log.warn("写入数据为空,跳过操作: deviceId={}", device.getId());
            return true;
        }
        
        try {
@@ -180,7 +200,7 @@
            return false;
        }
    }
    @Override
    public boolean isConnected() {
        try {
@@ -208,6 +228,5 @@
    @Override
    public void setTimeout(int timeout) {
        this.timeout = timeout;
        // ModbusTcpClient不支持直接设置超时,这里仅记录超时时间
    }
}