IpParameters params = new IpParameters()
params.setHost("localhost")//地址
params.setPort(502)//端口
ModbusFactory factory = new ModbusFactory()
ModbusMaster master = factory.createTcpMaster(params, true)
// 初始化
try {
master.init()
readHoldingRegistersTest(master,1,0,3)
} catch (ModbusInitException e) {
e.printStackTrace()
} finally {
master.destroy()
}
}
public static void main(String[] args) {
try {
TestModbus()
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace()
}
}
private static void readHoldingRegistersTest(ModbusMaster master,
int slaveId, int start, int len) {
try {
//ReadInputRegistersRequest request = new ReadInputRegistersRequest(
//slaveId, start, len)
//ReadInputRegistersResponse response = (ReadInputRegistersResponse) master
//.send(request)
ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(
slaveId, start, len)
ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master
.send(request)
if (response.isException()) {
System.out.println("Exception response: message="
+ response.getExceptionMessage())
} else {
ByteQueue byteQueue= new ByteQueue(12)
response.write(byteQueue)
System.out.println(byteQueue)
System.out.println(Arrays.toString(response.getShortData()))
short[] list = response.getShortData()
for(int i = 0i <list.lengthi++){
System.out.print(list[i] + " ")
}
}
} catch (ModbusTransportException e) {
e.printStackTrace()
}
}
其实任何数制都是一回事,大多协议相关资料在解释协议的时候,多采用十六进制表达MODBUS协议码,但这只是一种习惯而已,十进制表达也没有错的,只是大家不这样表达而已。无论什么协议数据,在进行信道上进行传输时都是以二进制码串的方式进行的。欢迎分享,转载请注明来源:内存溢出
评论列表(0条)