| | |
| | | import com.serotonin.modbus4j.locator.BaseLocator; |
| | | import com.serotonin.modbus4j.msg.*; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import java.util.HashMap; |
| | | |
| | | /** |
| | | * @Desc: 工具类 |
| | |
| | | //从机默认值 |
| | | private static Integer slaveId = 1; |
| | | |
| | | private static HashMap<String, ModbusMaster> masterMap = new HashMap<>(); |
| | | |
| | | /** |
| | | * 工厂 |
| | | */ |
| | | static ModbusFactory modbusFactory; |
| | | //static ModbusMaster modbusMaster; |
| | | |
| | | static { |
| | | if (modbusFactory == null) { |
| | |
| | | * @return |
| | | */ |
| | | public static ModbusMaster getMaster(String ip, int port) throws ModbusInitException, InterruptedException { |
| | | String key = ip; |
| | | ModbusMaster modbusMaster = masterMap.get(key); |
| | | if (modbusMaster == null || !modbusMaster.isConnected()) { |
| | | IpParameters ipParameters = new IpParameters(); |
| | | ipParameters.setHost(ip); |
| | | ipParameters.setPort(port); |
| | | modbusMaster = modbusFactory.createTcpMaster(ipParameters, true); |
| | | modbusMaster.init(); |
| | | |
| | | //初始化之后等待,避免出现连接未创建 |
| | | Thread.sleep(2000); |
| | | IpParameters ipParameters = new IpParameters(); |
| | | ipParameters.setHost(ip); |
| | | ipParameters.setPort(port); |
| | | ModbusMaster modbusMaster = modbusFactory.createTcpMaster(ipParameters, false); |
| | | modbusMaster.init(); |
| | | |
| | | masterMap.put(key, modbusMaster); |
| | | //初始化之后等待,避免出现连接未创建 |
| | | Thread.sleep(3000); |
| | | |
| | | return modbusMaster; |
| | | } |
| | | return modbusMaster; |
| | | } |
| | | |
| | |
| | | WriteCoilResponse coilResponse = (WriteCoilResponse) getMaster(ip, port).send(coilRequest); |
| | | return !coilResponse.isException(); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 写线圈开关状态数据 0x05 |
| | | * |
| | | * @param offset |
| | | * @param status |
| | | * @return |
| | | * @throws ModbusTransportException |
| | | * @throws ModbusInitException |
| | | |
| | | public static Boolean writeCoilStatus(String ip, int port, int offset, boolean status) throws ModbusTransportException, ModbusInitException, InterruptedException { |
| | | // boolean coilValue = status; |
| | | // WriteCoilRequest coilRequest = new WriteCoilRequest(slaveId, offset, coilValue); |
| | | // WriteCoilResponse coilResponse = (WriteCoilResponse) getMaster(ip, port).send(coilRequest); |
| | | // return !coilResponse.isException(); |
| | | |
| | | WriteCoilRequest coilRequest = new WriteCoilRequest(slaveId, offset, status); |
| | | // Thread.sleep(3000); |
| | | WriteCoilResponse coilResponse = (WriteCoilResponse) getMaster(ip, port).send(coilRequest); |
| | | |
| | | //发送清除命令 |
| | | WriteCoilRequest coilRequest1 = new WriteCoilRequest(slaveId, offset, !status); |
| | | getMaster(ip, port).send(coilRequest1); |
| | | |
| | | return !coilResponse.isException(); |
| | | } |
| | | */ |
| | | |
| | | |
| | | /** |