package com.xzzn.common.core.modbus;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Modbus重试
 *
 */
public class RetryableModbusOperation {
    private static final Logger logger = LoggerFactory.getLogger(RetryableModbusOperation.class);

    public interface ModbusOperation<T> {
        T execute() throws Exception;
    }

    public static <T> T executeWithRetry(ModbusOperation<T> operation, int maxRetries) {
        int retryCount = 0;
        Exception lastException = null;

        while (retryCount <= maxRetries) {
            try {
                return operation.execute();
            } catch (Exception e) {
                lastException = e;
                retryCount++;
                if (retryCount <= maxRetries) {
                    logger.info("Operation failed, retrying... (Attempt {})", retryCount);
                }
            }
        }

        logger.error("Max retries ({}) reached. Last error: {}", maxRetries,
                lastException != null ? lastException.getMessage() : "Unknown");
        throw new RuntimeException("Operation failed after " + maxRetries + " retries", lastException);
    }
}
