|
|
|
@ -10,12 +10,14 @@ import com.ghgande.j2mod.modbus.procimg.InputRegister; |
|
|
|
import com.xujie.sys.modules.reader.dao.ModbusCommunicateMapper; |
|
|
|
import com.xujie.sys.modules.reader.entity.ModbusCommunicateEntity; |
|
|
|
import com.xujie.sys.modules.reader.service.ModbusCommunicateService; |
|
|
|
import lombok.extern.slf4j.Slf4j; |
|
|
|
import org.springframework.beans.factory.annotation.Autowired; |
|
|
|
import org.springframework.stereotype.Service; |
|
|
|
|
|
|
|
import java.net.InetAddress; |
|
|
|
|
|
|
|
@Service |
|
|
|
@Slf4j |
|
|
|
public class ModbusCommunicateServiceImpl extends ServiceImpl<ModbusCommunicateMapper,ModbusCommunicateEntity> implements ModbusCommunicateService { |
|
|
|
|
|
|
|
@Autowired |
|
|
|
@ -29,6 +31,7 @@ public class ModbusCommunicateServiceImpl extends ServiceImpl<ModbusCommunicateM |
|
|
|
int modbusPort = one.getModbusPort(); |
|
|
|
int registerAddress = one.getRegisterAddress(); |
|
|
|
int registerNum = one.getRegisterNum(); |
|
|
|
int unitId = one.getUnitId(); |
|
|
|
try { |
|
|
|
InetAddress ipAddress = InetAddress.getByName(modbusIp); |
|
|
|
// 连接到Modbus设备 |
|
|
|
@ -39,7 +42,7 @@ public class ModbusCommunicateServiceImpl extends ServiceImpl<ModbusCommunicateM |
|
|
|
// 创建一个Modbus TCP请求 |
|
|
|
//ReadInputRegistersRequest(寄存器起始地址值,寄存器个数) |
|
|
|
ReadInputRegistersRequest request = new ReadInputRegistersRequest(registerAddress, registerNum); |
|
|
|
request.setUnitID(1); // 设置Modbus设备的Unit ID |
|
|
|
request.setUnitID(unitId); // 设置Modbus设备的Unit ID |
|
|
|
|
|
|
|
// 创建一个Modbus TCP事务 |
|
|
|
ModbusTCPTransaction transaction = new ModbusTCPTransaction(connection); |
|
|
|
@ -55,9 +58,9 @@ public class ModbusCommunicateServiceImpl extends ServiceImpl<ModbusCommunicateM |
|
|
|
InputRegister[] registers1 = response.getRegisters(); |
|
|
|
for (InputRegister inputRegister : registers1) { |
|
|
|
int value = inputRegister.getValue(); |
|
|
|
log.info("获取到的modbus数据为: ",value); |
|
|
|
System.out.println("Register value: " + value); |
|
|
|
} |
|
|
|
|
|
|
|
} else { |
|
|
|
System.out.println("No response received."); |
|
|
|
} |
|
|
|
@ -66,6 +69,5 @@ public class ModbusCommunicateServiceImpl extends ServiceImpl<ModbusCommunicateM |
|
|
|
} catch (Exception e) { |
|
|
|
e.printStackTrace(); |
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
} |