package com.zy.acs.manager.core.service;
|
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.ghgande.j2mod.modbus.facade.ModbusTCPMaster;
|
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<String, ModbusTCPMaster> CHARGE_CACHE = new ConcurrentHashMap<>();
|
|
private final Map<String, Object> deviceLocks = new ConcurrentHashMap<>();
|
|
@PostConstruct
|
public void init() {
|
List<FuncSta> list = funcStaService.list(new LambdaQueryWrapper<FuncSta>()
|
.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) {
|
ModbusTCPMaster modbusTcp = new ModbusTCPMaster(funcSta.getIp(), funcSta.getPort(), true);
|
try {
|
modbusTcp.connect();
|
} catch (Exception e) {
|
log.info("连接失败");
|
}
|
CHARGE_CACHE.put(funcSta.getUuid(), modbusTcp);
|
}
|
|
public void remove(String chargePointId) {
|
ModbusTCPMaster master = CHARGE_CACHE.remove(chargePointId);
|
if (master != null && master.isConnected()) {
|
master.disconnect();
|
}
|
}
|
|
public ModbusTCPMaster get(String chargePointId) {
|
// 获取或创建设备锁
|
Object lock = deviceLocks.computeIfAbsent(chargePointId, k -> new Object());
|
synchronized (lock) {
|
ModbusTCPMaster modbusTcp = CHARGE_CACHE.get(chargePointId);
|
if (modbusTcp != null) {
|
return modbusTcp;
|
}
|
FuncSta funcSta = funcStaService.getOne(new LambdaQueryWrapper<FuncSta>().eq(FuncSta::getUuid, chargePointId));
|
modbusTcp = new ModbusTCPMaster(funcSta.getIp(), funcSta.getPort(),true);
|
try {
|
modbusTcp.connect();
|
} catch (Exception e) {
|
log.info("连接失败");
|
return null;
|
}
|
CHARGE_CACHE.put(chargePointId, modbusTcp);
|
return modbusTcp;
|
}
|
|
}
|
|
|
}
|