Procházet zdrojové kódy

修改协议关联机制

xiaoguohua před 2 měsíci
rodič
revize
b64cb0dd04

+ 0 - 69
gateway/forecast-modbus-rtu/src/main/java/cn/oleauto/modbus/rtu/uitl/ConfigValidator.java

@@ -1,69 +0,0 @@
-//package cn.oleauto.modbus.tcp.uitl;
-//
-//import cn.oleauto.modbus.tcp.dto.ModbusConfig;
-//import cn.oleauto.modbus.tcp.dto.RegisterConfig;
-//import org.slf4j.Logger;
-//import org.slf4j.LoggerFactory;
-//
-//import java.util.*;
-//
-//public class ConfigValidator {
-//    private static final Logger logger = LoggerFactory.getLogger(ConfigValidator.class);
-//
-//    /**
-//     * 验证配置完整性
-//     */
-//    public static List<String> validate(ModbusConfig config) {
-//        List<String> errors = new ArrayList<>();
-//
-//        if (config.getDevice() == null) {
-//            errors.add("设备信息不能为空");
-//        } else {
-//            if (config.getDevice().getSlaveId() < 0 || config.getDevice().getSlaveId() > 255) {
-//                errors.add("从站ID必须在0-255之间");
-//            }
-//            if (config.getDevice().getPort() < 1 || config.getDevice().getPort() > 65535) {
-//                errors.add("端口号必须在1-65535之间");
-//            }
-//        }
-//
-//        if (config.getRegisters() == null || config.getRegisters().isEmpty()) {
-//            errors.add("寄存器配置列表不能为空");
-//        } else {
-//            // 检查地址和名称重复
-//            Set<Integer> addresses = new HashSet<>();
-//            Set<String> names = new HashSet<>();
-//
-//            for (RegisterConfig reg : config.getRegisters()) {
-//                if (reg.getName() == null || reg.getName().trim().isEmpty()) {
-//                    errors.add("寄存器名称不能为空");
-//                } else if (!names.add(reg.getName())) {
-//                    errors.add("寄存器名称重复: " + reg.getName());
-//                }
-//
-//                if (reg.getAddress() < 0) {
-//                    errors.add("寄存器地址不能为负数: " + reg.getName());
-//                } else if (!addresses.add(reg.getAddress())) {
-//                    errors.add("寄存器地址重复: " + reg.getName() + " (地址: " + reg.getAddress() + ")");
-//                }
-//
-//                if (reg.getArea() == null) {
-//                    errors.add("寄存器区域不能为空: " + reg.getName());
-//                }
-//
-//                if (reg.getType() == null) {
-//                    errors.add("数据类型不能为空: " + reg.getName());
-//                }
-//            }
-//        }
-//
-//        if (!errors.isEmpty()) {
-//            logger.warn("配置验证发现{}个问题", errors.size());
-//            errors.forEach(logger::warn);
-//        } else {
-//            logger.info("配置验证通过");
-//        }
-//
-//        return errors;
-//    }
-//}

+ 0 - 514
gateway/forecast-modbus-rtu/src/main/java/cn/oleauto/modbus/rtu/uitl/ModbusDataReader.java

@@ -1,514 +0,0 @@
-//package cn.oleauto.modbus.tcp.uitl;
-//
-//import cn.oleauto.modbus.tcp.dto.*;
-//import cn.oleauto.modbus.tcp.exception.ModbusDataException;
-//import cn.oleauto.modbus.tcp.service.DataParser;
-//import com.serotonin.modbus4j.ModbusMaster;
-//import com.serotonin.modbus4j.exception.ErrorResponseException;
-//import com.serotonin.modbus4j.exception.ModbusTransportException;
-//import com.serotonin.modbus4j.locator.BaseLocator;
-//import org.slf4j.Logger;
-//import org.slf4j.LoggerFactory;
-//
-//import java.util.*;
-//import java.util.concurrent.ConcurrentHashMap;
-//import java.util.concurrent.ExecutorService;
-//import java.util.concurrent.Executors;
-//import java.util.stream.Collectors;
-//
-//public class ModbusDataReader {
-//    private static final Logger logger = LoggerFactory.getLogger(ModbusDataReader.class);
-//
-//    private final ModbusMasterManager masterManager;
-//    private final Map<String, ParseResult> cacheMap = new ConcurrentHashMap<>();
-//    private final Map<AreaType, List<RegisterConfig>> areaGroupMap = new ConcurrentHashMap<>();
-//    private final Map<String, RegisterConfig> configMap = new ConcurrentHashMap<>();
-//
-//    // 异步读取线程池
-//    private final ExecutorService readExecutor = Executors.newFixedThreadPool(4);
-//
-//    // 统计数据
-//    private long totalReadCount = 0;
-//    private long successReadCount = 0;
-//    private long failedReadCount = 0;
-//
-//    public ModbusDataReader(ModbusMasterManager masterManager) {
-//        this.masterManager = masterManager;
-//    }
-//
-//    /**
-//     * 构建索引
-//     */
-//    public void buildIndex(List<RegisterConfig> registers) {
-//        areaGroupMap.clear();
-//        configMap.clear();
-//
-//        for (RegisterConfig config : registers) {
-//            if (!config.isActive()) continue;
-//
-//            configMap.put(config.getName(), config);
-//            AreaType area = config.getArea();
-//            areaGroupMap.computeIfAbsent(area, k -> new ArrayList<>()).add(config);
-//        }
-//
-//        // 按地址排序
-//        for (List<RegisterConfig> list : areaGroupMap.values()) {
-//            list.sort(Comparator.comparingInt(RegisterConfig::getAddress));
-//        }
-//
-//        logger.info("索引构建完成,共{}个区域分组,{}个配置项",
-//                areaGroupMap.size(), configMap.size());
-//    }
-//
-//    /**
-//     * 读取所有有效数据(同步)
-//     */
-//    public Map<String, ParseResult> readAll() {
-//        Map<String, ParseResult> results = new LinkedHashMap<>();
-//
-//        for (Map.Entry<AreaType, List<RegisterConfig>> entry : areaGroupMap.entrySet()) {
-//            AreaType area = entry.getKey();
-//            List<RegisterConfig> configs = entry.getValue();
-//
-//            try {
-//                Map<String, ParseResult> areaResults = readByArea(area, configs);
-//                results.putAll(areaResults);
-//            } catch (Exception e) {
-//                logger.error("读取区域失败: {}", area, e);
-//                // 为每个配置创建错误结果
-//                for (RegisterConfig config : configs) {
-//                    ParseResult errorResult = new ParseResult();
-//                    errorResult.setName(config.getName());
-//                    errorResult.setAddress(config.getAddress());
-//                    errorResult.setArea(config.getArea());
-//                    errorResult.setType(config.getType());
-//                    errorResult.setSuccess(false);
-//                    errorResult.setErrorMessage("读取失败: " + e.getMessage());
-//                    results.put(config.getName(), errorResult);
-//                }
-//            }
-//        }
-//
-//        // 更新缓存
-//        cacheMap.putAll(results);
-//        updateStatistics(results);
-//
-//        return results;
-//    }
-//
-//    /**
-//     * 异步读取所有数据
-//     */
-//    public void readAllAsync(DataReadCallback callback) {
-//        readExecutor.submit(() -> {
-//            try {
-//                Map<String, ParseResult> results = readAll();
-//                if (callback != null) {
-//                    callback.onSuccess(results);
-//                }
-//            } catch (Exception e) {
-//                logger.error("异步读取失败", e);
-//                if (callback != null) {
-//                    callback.onError(e);
-//                }
-//            }
-//        });
-//    }
-//
-//    /**
-//     * 按区域读取数据
-//     */
-//    private Map<String, ParseResult> readByArea(AreaType area, List<RegisterConfig> configs)
-//            throws ModbusTransportException, ErrorResponseException {
-//
-//        Map<String, ParseResult> results = new LinkedHashMap<>();
-//
-//        if (configs == null || configs.isEmpty()) {
-//            return results;
-//        }
-//
-//        ModbusMaster master = masterManager.getMaster();
-//        int slaveId = getSlaveId();
-//
-//        // 过滤出可读的配置
-//        List<RegisterConfig> readableConfigs = configs.stream()
-//                .filter(RegisterConfig::isReadable)
-//                .collect(Collectors.toList());
-//
-//        if (readableConfigs.isEmpty()) {
-//            return results;
-//        }
-//
-//        // 按连续地址分组
-//        List<List<RegisterConfig>> groups = groupContinuousAddresses(readableConfigs);
-//
-//        for (List<RegisterConfig> group : groups) {
-//            try {
-//                Map<String, ParseResult> groupResults = readGroup(master, slaveId, area, group);
-//                results.putAll(groupResults);
-//            } catch (Exception e) {
-//                logger.error("批量读取组失败: area={}, startAddress={}",
-//                        area, group.get(0).getAddress(), e);
-//
-//                // 回退到单个读取
-//                for (RegisterConfig config : group) {
-//                    try {
-//                        ParseResult result = readSingle(master, slaveId, config);
-//                        if (result != null) {
-//                            results.put(config.getName(), result);
-//                        }
-//                    } catch (Exception ex) {
-//                        logger.error("单个读取失败: {}", config.getName(), ex);
-//                        ParseResult errorResult = createErrorResult(config, ex.getMessage());
-//                        results.put(config.getName(), errorResult);
-//                    }
-//                }
-//            }
-//        }
-//
-//        return results;
-//    }
-//
-//    /**
-//     * 按连续地址分组
-//     */
-//    private List<List<RegisterConfig>> groupContinuousAddresses(List<RegisterConfig> configs) {
-//        List<List<RegisterConfig>> groups = new ArrayList<>();
-//
-//        if (configs == null || configs.isEmpty()) {
-//            return groups;
-//        }
-//
-//        // 按地址排序
-//        List<RegisterConfig> sorted = new ArrayList<>(configs);
-//        sorted.sort(Comparator.comparingInt(RegisterConfig::getAddress));
-//
-//        List<RegisterConfig> currentGroup = new ArrayList<>();
-//
-//        for (int i = 0; i < sorted.size(); i++) {
-//            RegisterConfig current = sorted.get(i);
-//
-//            if (currentGroup.isEmpty()) {
-//                currentGroup.add(current);
-//                continue;
-//            }
-//
-//            RegisterConfig previous = sorted.get(i - 1);
-//            int previousEnd = previous.getAddress() + previous.getType().getRegisterCount();
-//
-//            // 检查地址是否连续(且类型相同)
-//            if (current.getAddress() == previousEnd &&
-//                    current.getType() == previous.getType() &&
-//                    current.getArea() == previous.getArea()) {
-//                currentGroup.add(current);
-//            } else {
-//                if (!currentGroup.isEmpty()) {
-//                    groups.add(new ArrayList<>(currentGroup));
-//                }
-//                currentGroup.clear();
-//                currentGroup.add(current);
-//            }
-//        }
-//
-//        if (!currentGroup.isEmpty()) {
-//            groups.add(currentGroup);
-//        }
-//
-//        return groups;
-//    }
-//
-//    /**
-//     * 批量读取一组配置
-//     */
-//    private Map<String, ParseResult> readGroup(ModbusMaster master, int slaveId,
-//                                               AreaType area, List<RegisterConfig> group)
-//            throws ModbusTransportException, ErrorResponseException {
-//
-//        Map<String, ParseResult> results = new LinkedHashMap<>();
-//        int startAddress = group.get(0).getAddress();
-//
-//        if (area.isBitType()) {
-//            // 读取位类型(线圈/离散输入)
-//            int count = group.size();
-//            boolean[] bitValues;
-//
-//            if (area == AreaType.COIL) {
-//                bitValues = master.getCoils(slaveId, startAddress, count);
-//            } else {
-//                bitValues = master.getDiscreteInputs(slaveId, startAddress, count);
-//            }
-//
-//            for (int i = 0; i < group.size(); i++) {
-//                RegisterConfig config = group.get(i);
-//                boolean value = (i < bitValues.length) ? bitValues[i] : false;
-//                ParseResult result = DataParser.parseBitValue(config, value);
-//                results.put(config.getName(), result);
-//            }
-//
-//        } else {
-//            // 读取寄存器类型
-//            int count = calculateGroupCount(group);
-//            short[] rawData;
-//
-//            if (area == AreaType.HOLDING) {
-//                rawData = master.getHoldingRegisters(slaveId, startAddress, count);
-//            } else {
-//                rawData = master.getInputRegisters(slaveId, startAddress, count);
-//            }
-//
-//            // 解析每个寄存器
-//            for (RegisterConfig config : group) {
-//                ParseResult result = DataParser.parseRegister(config, rawData, startAddress);
-//                if (result != null) {
-//                    results.put(config.getName(), result);
-//                }
-//            }
-//        }
-//
-//        return results;
-//    }
-//
-//    /**
-//     * 计算组需要读取的寄存器数量
-//     */
-//    private int calculateGroupCount(List<RegisterConfig> group) {
-//        if (group.isEmpty()) return 0;
-//        RegisterConfig last = group.get(group.size() - 1);
-//        RegisterConfig first = group.get(0);
-//        return last.getAddress() + last.getType().getRegisterCount() - first.getAddress();
-//    }
-//
-//    /**
-//     * 读取单个数据点
-//     */
-//    private ParseResult readSingle(ModbusMaster master, int slaveId, RegisterConfig config)
-//            throws ModbusTransportException, ErrorResponseException {
-//
-//        if (!config.isReadable()) {
-//            return createErrorResult(config, "配置为只写,不可读");
-//        }
-//
-//        if (config.isBitType()) {
-//            boolean value;
-//            if (config.getArea() == AreaType.COIL) {
-//                value = master.getCoil(slaveId, config.getAddress());
-//            } else {
-//                value = master.getDiscreteInput(slaveId, config.getAddress());
-//            }
-//            return DataParser.parseBitValue(config, value);
-//        } else {
-//            // 寄存器类型
-//            if (config.getType() == DataTypeEnum.BINARY) {
-//                throw new IllegalArgumentException("寄存器不能使用BINARY类型: " + config.getName());
-//            }
-//
-//            BaseLocator<Number> locator = createLocator(slaveId, config);
-//            Number rawValue = master.getValue(locator);
-//            return DataParser.parseNumberValue(config, rawValue);
-//        }
-//    }
-//
-//    /**
-//     * 创建BaseLocator
-//     */
-//    private BaseLocator<Number> createLocator(int slaveId, RegisterConfig config) {
-//        if (config.getArea() == AreaType.HOLDING) {
-//            return BaseLocator.holdingRegister(slaveId, config.getAddress(),
-//                    config.getType().getModbus4jDataType());
-//        } else if (config.getArea() == AreaType.INPUT) {
-//            return BaseLocator.inputRegister(slaveId, config.getAddress(),
-//                    config.getType().getModbus4jDataType());
-//        } else {
-//            throw new IllegalArgumentException("不支持的寄存器区域: " + config.getArea());
-//        }
-//    }
-//
-//    /**
-//     * 读取单个寄存器(公开方法)
-//     */
-//    public ParseResult readRegister(String name) throws ModbusDataException {
-//        RegisterConfig config = configMap.get(name);
-//        if (config == null) {
-//            throw new ModbusDataException("未找到寄存器配置: " + name);
-//        }
-//
-//        try {
-//            ModbusMaster master = masterManager.getMaster();
-//            int slaveId = getSlaveId();
-//            return readSingle(master, slaveId, config);
-//        } catch (ModbusTransportException | ErrorResponseException e) {
-//            throw new ModbusDataException("读取失败: " + name, e, name, config.getAddress());
-//        } catch (Exception e) {
-//            throw new ModbusDataException("读取异常: " + name, e);
-//        }
-//    }
-//
-//    /**
-//     * 读取单个寄存器(带配置对象)
-//     */
-//    public ParseResult readRegister(RegisterConfig config) throws ModbusDataException {
-//        try {
-//            ModbusMaster master = masterManager.getMaster();
-//            int slaveId = getSlaveId();
-//            return readSingle(master, slaveId, config);
-//        } catch (ModbusTransportException | ErrorResponseException e) {
-//            throw new ModbusDataException("读取失败: " + config.getName(), e,
-//                    config.getName(), config.getAddress());
-//        } catch (Exception e) {
-//            throw new ModbusDataException("读取异常: " + config.getName(), e);
-//        }
-//    }
-//
-//    /**
-//     * 读取指定区域的多个寄存器
-//     */
-//    public Map<String, ParseResult> readRegistersByArea(AreaType area) {
-//        List<RegisterConfig> configs = areaGroupMap.get(area);
-//        if (configs == null || configs.isEmpty()) {
-//            return Collections.emptyMap();
-//        }
-//
-//        try {
-//            return readByArea(area, configs);
-//        } catch (Exception e) {
-//            logger.error("读取区域失败: {}", area, e);
-//            Map<String, ParseResult> errorResults = new LinkedHashMap<>();
-//            for (RegisterConfig config : configs) {
-//                errorResults.put(config.getName(), createErrorResult(config, e.getMessage()));
-//            }
-//            return errorResults;
-//        }
-//    }
-//
-//    /**
-//     * 获取缓存的读取结果
-//     */
-//    public ParseResult getCachedResult(String name) {
-//        return cacheMap.get(name);
-//    }
-//
-//    /**
-//     * 获取所有缓存结果
-//     */
-//    public Map<String, ParseResult> getAllCachedResults() {
-//        return new LinkedHashMap<>(cacheMap);
-//    }
-//
-//    /**
-//     * 清除缓存
-//     */
-//    public void clearCache() {
-//        cacheMap.clear();
-//    }
-//
-//    /**
-//     * 获取从站ID
-//     */
-//    private int getSlaveId() {
-//        ModbusConfig config = masterManager.getCurrentConfig();
-//        return config != null && config.getDevice() != null ?
-//                config.getDevice().getSlaveId() : 1;
-//    }
-//
-//    /**
-//     * 创建错误结果
-//     */
-//    private ParseResult createErrorResult(RegisterConfig config, String errorMessage) {
-//        ParseResult result = new ParseResult();
-//        result.setName(config.getName());
-//        result.setAddress(config.getAddress());
-//        result.setArea(config.getArea());
-//        result.setType(config.getType());
-//        result.setUnit(config.getUnit());
-//        result.setSuccess(false);
-//        result.setErrorMessage(errorMessage);
-//        return result;
-//    }
-//
-//    /**
-//     * 更新统计数据
-//     */
-//    private void updateStatistics(Map<String, ParseResult> results) {
-//        totalReadCount++;
-//        long success = results.values().stream().filter(ParseResult::isSuccess).count();
-//        long failed = results.size() - success;
-//
-//        successReadCount += success;
-//        failedReadCount += failed;
-//    }
-//
-//    /**
-//     * 获取统计信息
-//     */
-//    public Map<String, Object> getStatistics() {
-//        Map<String, Object> stats = new HashMap<>();
-//        stats.put("totalReadCount", totalReadCount);
-//        stats.put("successReadCount", successReadCount);
-//        stats.put("failedReadCount", failedReadCount);
-//        stats.put("successRate", totalReadCount > 0 ?
-//                (double) successReadCount / totalReadCount * 100 : 0);
-//        stats.put("cacheSize", cacheMap.size());
-//        stats.put("configCount", configMap.size());
-//        return stats;
-//    }
-//
-//    /**
-//     * 获取所有配置
-//     */
-//    public List<RegisterConfig> getAllConfigs() {
-//        return new ArrayList<>(configMap.values());
-//    }
-//
-//    /**
-//     * 根据名称获取配置
-//     */
-//    public RegisterConfig getConfig(String name) {
-//        return configMap.get(name);
-//    }
-//
-//    /**
-//     * 根据区域获取配置列表
-//     */
-//    public List<RegisterConfig> getConfigsByArea(AreaType area) {
-//        return areaGroupMap.getOrDefault(area, Collections.emptyList());
-//    }
-//
-//    /**
-//     * 检查是否包含指定名称的配置
-//     */
-//    public boolean hasConfig(String name) {
-//        return configMap.containsKey(name);
-//    }
-//
-//    /**
-//     * 获取配置数量
-//     */
-//    public int getConfigCount() {
-//        return configMap.size();
-//    }
-//
-//    /**
-//     * 关闭资源
-//     */
-//    public void shutdown() {
-//        readExecutor.shutdown();
-//        try {
-//            if (!readExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
-//                readExecutor.shutdownNow();
-//            }
-//        } catch (InterruptedException e) {
-//            readExecutor.shutdownNow();
-//            Thread.currentThread().interrupt();
-//        }
-//        clearCache();
-//        logger.info("ModbusDataReader已关闭");
-//    }
-//
-//    /**
-//     * 数据读取回调接口
-//     */
-//    public interface DataReadCallback {
-//        void onSuccess(Map<String, ParseResult> results);
-//        void onError(Exception e);
-//    }
-//}

+ 0 - 339
gateway/forecast-modbus-rtu/src/main/java/cn/oleauto/modbus/rtu/uitl/ModbusMasterManager.java

@@ -1,339 +0,0 @@
-//package cn.oleauto.modbus.tcp.uitl;
-//
-//import cn.oleauto.modbus.tcp.dto.ModbusConfig;
-//import cn.oleauto.modbus.tcp.exception.ModbusConfigException;
-//import com.serotonin.modbus4j.ModbusFactory;
-//import com.serotonin.modbus4j.ModbusMaster;
-//import com.serotonin.modbus4j.exception.ModbusInitException;
-//import com.serotonin.modbus4j.ip.IpParameters;
-//import org.slf4j.Logger;
-//import org.slf4j.LoggerFactory;
-//
-//import java.util.Map;
-//import java.util.concurrent.atomic.AtomicBoolean;
-//import java.util.concurrent.atomic.AtomicReference;
-//
-//public class ModbusMasterManager {
-//    private static final Logger logger = LoggerFactory.getLogger(ModbusMasterManager.class);
-//
-//    private final ModbusFactory modbusFactory = new ModbusFactory();
-//    private final AtomicReference<ModbusMaster> masterRef = new AtomicReference<>();
-//    private final AtomicBoolean connected = new AtomicBoolean(false);
-//
-//    // 当前配置
-//    private ModbusConfig currentConfig;
-//
-//    // 连接参数
-//    private String connectionType = "tcp"; // tcp 或 rtu
-//    private String host;
-//    private int port = 502;
-//    private String serialPort;
-//    private int baudRate = 9600;
-//    private int dataBits = 8;
-//    private int stopBits = 1;
-//    private int parity = 0; // 0:无, 1:奇, 2:偶
-//
-//    // 协议参数
-//    private int timeout = 1000;
-//    private int retries = 3;
-//
-//    /**
-//     * 初始化并连接(从配置加载)
-//     */
-//    public void connect(ModbusConfig config) throws ModbusInitException {
-//        this.currentConfig = config;
-//
-//        // 从配置中提取连接参数
-//        if (config.getDevice() != null) {
-//            this.host = config.getDevice().getIpAddress();
-//            this.port = config.getDevice().getPort();
-//        }
-//
-//        if (config.getProtocol() != null) {
-//            this.timeout = config.getProtocol().getTimeout();
-//            this.retries = config.getProtocol().getRetry();
-//        }
-//
-//        ModbusMaster master = createMaster();
-//        master.init();
-//
-//        // 关闭旧的连接
-//        disconnect();
-//
-//        masterRef.set(master);
-//        connected.set(true);
-//
-//        logger.info("Modbus连接成功: {}:{} (从站ID: {})",
-//                host, port, config.getDevice() != null ? config.getDevice().getSlaveId() : 1);
-//    }
-//
-//    /**
-//     * 连接(TCP/IP)
-//     */
-//    public void connectTcp(String host, int port, int slaveId) throws ModbusInitException {
-//        this.host = host;
-//        this.port = port;
-//        this.connectionType = "tcp";
-//
-//        // 创建临时配置
-//        ModbusConfig config = new ModbusConfig();
-//        ModbusConfig.DeviceInfo device = new ModbusConfig.DeviceInfo();
-//        device.setSlaveId(slaveId);
-//        config.setDevice(device);
-//        this.currentConfig = config;
-//
-//        connect(currentConfig);
-//    }
-//
-//    /**
-//     * 连接(RTU串口)
-//     */
-//    public void connectRtu(String serialPort, int baudRate, int slaveId) throws ModbusInitException {
-//        this.serialPort = serialPort;
-//        this.baudRate = baudRate;
-//        this.connectionType = "rtu";
-//
-//        // 创建临时配置
-//        ModbusConfig config = new ModbusConfig();
-//        ModbusConfig.DeviceInfo device = new ModbusConfig.DeviceInfo();
-//        device.setSlaveId(slaveId);
-//        device.setIpAddress(serialPort); // 复用字段存储串口名
-//        config.setDevice(device);
-//        this.currentConfig = config;
-//
-//        ModbusMaster master = createRtuMaster();
-//        master.init();
-//
-//        disconnect();
-//        masterRef.set(master);
-//        connected.set(true);
-//
-//        logger.info("Modbus RTU连接成功: {} (从站ID: {})", serialPort, slaveId);
-//    }
-//
-//    /**
-//     * 创建ModbusMaster实例(TCP/IP)
-//     */
-//    private ModbusMaster createMaster() {
-//        if (host == null || host.isEmpty()) {
-//            throw new ModbusConfigException("主机地址不能为空");
-//        }
-//
-//        IpParameters ipParams = new IpParameters();
-//        ipParams.setHost(host);
-//        ipParams.setPort(port);
-//
-//        ModbusMaster master = modbusFactory.createTcpMaster(ipParams, true);
-//        master.setTimeout(timeout);
-//        master.setRetries(retries);
-//
-//        logger.debug("创建TCP Master: {}:{}", host, port);
-//        return master;
-//    }
-//
-//    /**
-//     * 创建ModbusMaster实例(RTU串口)
-//     */
-//    private ModbusMaster createRtuMaster() {
-////        if (serialPort == null || serialPort.isEmpty()) {
-////            throw new ModbusConfigException("串口名称不能为空");
-////        }
-////
-////        RtuParameters rtuParams = new RtuParameters();
-////        rtuParams.setPort(serialPort);
-////        rtuParams.setBaudRate(baudRate);
-////        rtuParams.setDataBits(dataBits);
-////        rtuParams.setStopBits(stopBits);
-////        rtuParams.setParity(parity);
-////
-////        ModbusMaster master = modbusFactory.createRtuMaster(rtuParams);
-////        master.setTimeout(timeout);
-////        master.setRetries(retries);
-////
-////        logger.debug("创建RTU Master: {} {}bps", serialPort, baudRate);
-////        return master;
-//        return null;
-//    }
-//
-//    /**
-//     * 重新连接
-//     */
-//    public void reconnect() throws ModbusInitException {
-//        if (currentConfig == null) {
-//            throw new IllegalStateException("配置未初始化,请先调用connect()");
-//        }
-//
-//        logger.info("正在重新连接...");
-//        disconnect();
-//        connect(currentConfig);
-//        logger.info("重新连接成功");
-//    }
-//
-//    /**
-//     * 断开连接
-//     */
-//    public void disconnect() {
-//        ModbusMaster master = masterRef.get();
-//        if (master != null) {
-//            try {
-//                master.destroy();
-//                logger.debug("Modbus连接已断开");
-//            } catch (Exception e) {
-//                logger.warn("断开连接时发生错误", e);
-//            }
-//        }
-//        masterRef.set(null);
-//        connected.set(false);
-//    }
-//
-//    /**
-//     * 获取ModbusMaster实例
-//     */
-//    public ModbusMaster getMaster() {
-//        ModbusMaster master = masterRef.get();
-//        if (master == null || !connected.get()) {
-//            throw new IllegalStateException("ModbusMaster未连接,请先调用connect()");
-//        }
-//        return master;
-//    }
-//
-//    /**
-//     * 检查是否已连接
-//     */
-//    public boolean isConnected() {
-//        return connected.get() && masterRef.get() != null;
-//    }
-//
-//    /**
-//     * 获取当前配置
-//     */
-//    public ModbusConfig getCurrentConfig() {
-//        return currentConfig;
-//    }
-//
-//    /**
-//     * 更新配置
-//     */
-//    public void updateConfig(ModbusConfig newConfig) {
-//        this.currentConfig = newConfig;
-//        if (newConfig.getDevice() != null) {
-//            this.host = newConfig.getDevice().getIpAddress();
-//            this.port = newConfig.getDevice().getPort();
-//        }
-//        if (newConfig.getProtocol() != null) {
-//            this.timeout = newConfig.getProtocol().getTimeout();
-//            this.retries = newConfig.getProtocol().getRetry();
-//        }
-//        logger.info("配置已更新");
-//    }
-//
-//    /**
-//     * 设置超时时间
-//     */
-//    public void setTimeout(int timeout) {
-//        this.timeout = timeout;
-//        ModbusMaster master = masterRef.get();
-//        if (master != null) {
-//            master.setTimeout(timeout);
-//        }
-//    }
-//
-//    /**
-//     * 设置重试次数
-//     */
-//    public void setRetries(int retries) {
-//        this.retries = retries;
-//        ModbusMaster master = masterRef.get();
-//        if (master != null) {
-//            master.setRetries(retries);
-//        }
-//    }
-//
-//    /**
-//     * 获取从站ID
-//     */
-//    public int getSlaveId() {
-//        if (currentConfig != null && currentConfig.getDevice() != null) {
-//            return currentConfig.getDevice().getSlaveId();
-//        }
-//        return 1;
-//    }
-//
-//    /**
-//     * 获取连接信息
-//     */
-//    public Map<String, Object> getConnectionInfo() {
-//        Map<String, Object> info = new java.util.HashMap<>();
-//        info.put("connected", isConnected());
-//        info.put("connectionType", connectionType);
-//        info.put("host", host);
-//        info.put("port", port);
-//        info.put("slaveId", getSlaveId());
-//        info.put("timeout", timeout);
-//        info.put("retries", retries);
-//        if ("rtu".equals(connectionType)) {
-//            info.put("serialPort", serialPort);
-//            info.put("baudRate", baudRate);
-//        }
-//        return info;
-//    }
-//
-//    /**
-//     * 测试连接
-//     */
-//    public boolean testConnection() {
-//        try {
-//            ModbusMaster master = getMaster();
-//            int slaveId = getSlaveId();
-//            // 尝试读取一个寄存器测试连接
-//            // master.getHoldingRegisters(slaveId, 0, 1);
-//            return true;
-//        } catch (Exception e) {
-//            logger.warn("连接测试失败", e);
-//            return false;
-//        }
-//    }
-//
-//    /**
-//     * 设置RTU串口参数
-//     */
-//    public void setRtuParameters(String serialPort, int baudRate, int dataBits,
-//                                 int stopBits, int parity) {
-//        this.serialPort = serialPort;
-//        this.baudRate = baudRate;
-//        this.dataBits = dataBits;
-//        this.stopBits = stopBits;
-//        this.parity = parity;
-//        this.connectionType = "rtu";
-//    }
-//
-//    /**
-//     * 设置TCP参数
-//     */
-//    public void setTcpParameters(String host, int port) {
-//        this.host = host;
-//        this.port = port;
-//        this.connectionType = "tcp";
-//    }
-//
-//    /**
-//     * 关闭资源
-//     */
-//    public void destroy() {
-//        disconnect();
-//        logger.info("ModbusMasterManager已销毁");
-//    }
-//
-//    /**
-//     * 获取ModbusFactory实例
-//     */
-//    public ModbusFactory getModbusFactory() {
-//        return modbusFactory;
-//    }
-//
-//    @Override
-//    public String toString() {
-//        return String.format("ModbusMasterManager{connected=%s, host=%s, port=%d, slaveId=%d}",
-//                isConnected(), host, port, getSlaveId());
-//    }
-//}

+ 1 - 0
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/ITransmit.java

@@ -1,5 +1,6 @@
 package cn.oleauto.protocol.common;
 
+import cn.oleauto.protocol.common.event.AbstractEventArgs;
 import cn.oleauto.protocol.common.event.DefaultEventArgs;
 import cn.oleauto.protocol.common.event.TransmitMessageEventArgs;
 import cn.oleauto.protocol.common.transmit.TransmitState;

+ 0 - 3
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/channel/AbstractChannel.java

@@ -9,9 +9,6 @@ import cn.oleauto.config.domain.ConfigChannel;
 import cn.oleauto.protocol.common.IChannel;
 import cn.oleauto.protocol.common.IProtocol;
 import cn.oleauto.protocol.common.ITransmit;
-import cn.oleauto.protocol.common.dto.ReportMessageDto;
-import cn.oleauto.protocol.common.event.ProtocolMessageEventArgs;
-import cn.oleauto.protocol.common.mq.MQCenter;
 import lombok.extern.slf4j.Slf4j;
 
 @Slf4j

+ 7 - 0
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/event/ConnectEventArgs.java

@@ -0,0 +1,7 @@
+package cn.oleauto.protocol.common.event;
+
+public class ConnectEventArgs extends AbstractEventArgs{
+    public ConnectEventArgs(Object sender) {
+        super(sender, EventType.TRANSMIT_CONNETED);
+    }
+}

+ 7 - 0
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/event/DisconnectEventArgs.java

@@ -0,0 +1,7 @@
+package cn.oleauto.protocol.common.event;
+
+public class DisconnectEventArgs extends AbstractEventArgs{
+    public DisconnectEventArgs(Object sender) {
+        super(sender, EventType.TRANSMIT_DISCONNECTED);
+    }
+}

+ 4 - 0
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/event/EventCenter.java

@@ -4,6 +4,10 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.function.Consumer;
 
+/**
+ * 非线程安全类
+ * @param <T>
+ */
 public class EventCenter<T> {
     private final List<Consumer<T> > consumerList = new ArrayList<>();
 

+ 44 - 0
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/event/EventCenterTopic.java

@@ -0,0 +1,44 @@
+package cn.oleauto.protocol.common.event;
+
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.Consumer;
+
+/**
+ * 线程安全类
+ */
+public class EventCenterTopic {
+    private ConcurrentMap<EventType, List<Consumer<AbstractEventArgs>>> topicMap = new ConcurrentHashMap<>();
+
+    public EventCenterTopic(){
+        for(EventType eventType : EventType.values()){
+            topicMap.put(eventType, new CopyOnWriteArrayList<>());
+        }
+    }
+
+    public void subscribe(Consumer<AbstractEventArgs> consumer, EventType... eventTypes){
+        for(EventType eventType : eventTypes){
+            subscribe(eventType, consumer);
+        }
+    }
+
+    public void subscribe(EventType eventType, Consumer<AbstractEventArgs> consumer) {
+        List<Consumer<AbstractEventArgs>> orDefault = topicMap.getOrDefault(eventType, new CopyOnWriteArrayList<>());
+        orDefault.add(consumer);
+    }
+
+    public void unsubscribe(EventType eventType, Consumer<AbstractEventArgs> consumer) {
+        List<Consumer<AbstractEventArgs>> orDefault = topicMap.getOrDefault(eventType, new CopyOnWriteArrayList<>());
+        orDefault.remove(consumer);
+    }
+
+    public void clear(){
+        topicMap.clear();
+    }
+
+    public void publish(AbstractEventArgs eventArgs){
+        topicMap.getOrDefault(eventArgs.getEventType(), new CopyOnWriteArrayList<>()).forEach(consumer -> consumer.accept(eventArgs));
+    }
+}

+ 1 - 0
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/event/EventType.java

@@ -3,6 +3,7 @@ package cn.oleauto.protocol.common.event;
 public enum EventType {
     TRANSMIT_DISCONNECTED(0),
     TRANSMIT_CONNETED(1),
+
     TRANSMIT_SENT(2),
     TRANSMIT_RECEIVED(3),
 

+ 0 - 16
gateway/forecast-protocol-common/src/main/java/cn/oleauto/protocol/common/event/ProtocolMessageEventArgs.java

@@ -1,16 +0,0 @@
-package cn.oleauto.protocol.common.event;
-
-import lombok.Getter;
-
-public class ProtocolMessageEventArgs extends AbstractEventArgs{
-    @Getter
-    private long tmMs = System.currentTimeMillis();
-
-    @Getter
-    private byte[] data;
-
-    public ProtocolMessageEventArgs(Object sender, EventType eventType, byte[] data){
-        super(sender, eventType);
-        this.data = data;
-    }
-}