package com.zy.acs.manager.core.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.github.xingshuangs.iot.protocol.modbus.service.ModbusRtuOverTcp; import com.github.xingshuangs.iot.protocol.modbus.service.ModbusTcp; import com.github.xingshuangs.iot.utils.HexUtil; import com.zy.acs.framework.common.Cools; import com.zy.acs.manager.manager.entity.FuncSta; import com.zy.acs.manager.manager.enums.FuncStaType; import com.zy.acs.manager.manager.enums.ProtocolType; import com.zy.acs.manager.manager.service.FuncStaService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Slf4j @Service public class ChargeService { @Autowired private FuncStaService funcStaService; private final Map CHARGE_CACHE = new ConcurrentHashMap<>(); @PostConstruct public void init() { List list = funcStaService.list(new LambdaQueryWrapper() .eq(FuncSta::getType, FuncStaType.CHARGE.toString())); for (FuncSta funcSta : list) { if (Cools.isEmpty(funcSta.getProtocol()) && funcSta.getProtocol().equalsIgnoreCase(ProtocolType.MODBUS.toString())) { if (!Cools.isEmpty(funcSta.getIp()) && !Cools.isEmpty(funcSta.getPort())) add(funcSta); } } } public void add(FuncSta funcSta) { ModbusRtuOverTcp modbusTcp = new ModbusRtuOverTcp(funcSta.getIp(), funcSta.getPort()); modbusTcp.setComCallback((tag, bytes) -> log.info("%s[%d] %s%n", tag, bytes.length, HexUtil.toHexString(bytes))); CHARGE_CACHE.put(funcSta.getUuid(), modbusTcp); } public void remove(String chargePointId) { CHARGE_CACHE.remove(chargePointId); } public ModbusRtuOverTcp get(String chargePointId) { ModbusRtuOverTcp modbusTcp = CHARGE_CACHE.get(chargePointId); if (modbusTcp != null) { return modbusTcp; } FuncSta funcSta = funcStaService.getOne(new LambdaQueryWrapper().eq(FuncSta::getUuid, chargePointId)); modbusTcp = new ModbusRtuOverTcp(funcSta.getIp(), funcSta.getPort()); modbusTcp.setComCallback((tag, bytes) -> log.info("%s[%d] %s%n", tag, bytes.length, HexUtil.toHexString(bytes))); CHARGE_CACHE.put(chargePointId, modbusTcp); return modbusTcp; } }