package com.zehong.system.modbus.util;

import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.zehong.system.domain.TEquipmentInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @author lenovo
 * @date 2025/6/9
 * @description 读取数据多线程封装
 */
public class ModbusTcpTask implements Callable<Map<Integer, Object>> {

    private final TEquipmentInfo equipmentInfo;
    private final List<Integer> registerOffsets;

    public ModbusTcpTask(TEquipmentInfo equipmentInfo, List<Integer> registerOffset) {
        this.equipmentInfo = equipmentInfo;
        this.registerOffsets = registerOffset;
    }

    @Override
    public Map<Integer, Object> call(){
        ModbusMaster master = null;
        try {
            master = Modbus4jUtils.createModbusMaster(equipmentInfo.getfIp(), equipmentInfo.getfPort());
            return Modbus4jUtils.batchReadAgingCabinetStatus(master,registerOffsets);
        } catch (ModbusInitException e) {
            Map<Integer, Object> errorMap = new HashMap<>();
            errorMap.put(1,-1);
            return errorMap;
        } catch (Exception e) {
            Map<Integer, Object> errorMap = new HashMap<>();
            registerOffsets.forEach(offset -> errorMap.put(offset, "ERROR: " + e.getMessage()));
            return errorMap;
        } finally {
            if (master != null) {
                master.destroy();
            }
        }
    }
}
