}
public static ModbusRequest getReadRequest(String func, int ref, int quantity) {
if (func.equals( "05" ))// 功能码:05
return new WriteCoilRequest( ref, true );
else if (func.equals( "01" ))// 功能码:01
return new ReadCoilsRequest( ref, quantity );
else if (func.equals( "02" ))// 功能码:02
return new ReadInputDiscretesRequest( ref, quantity );
else if (func.equals( "04" ))// 功能码:04
return new ReadInputRegistersRequest( ref, quantity );
else if (func.equals( "03" ))// 功能码:03
return new ReadMultipleRegistersRequest( ref, quantity );
else if (func.equals( "06" )) {
Register r = ModbusCoupler.getReference().getProcessImageFactory().createRegister();
// r.setValue( 420 );
// 功能码:06
return new WriteSingleRegisterRequest( 0, r );
} else if (func.equals( "16" ))// 功能码:16 return new
{
Register rr = ModbusCoupler.getReference().getProcessImageFactory().createRegister();
rr.setValue( 420 );
return new WriteMultipleRegistersRequest( 0, new Register[] { rr } );
}
return null;
}
private static String getResponseString(ModbusResponse res) {
String data = null;
if (res == null) {
logger.info( "UDP请求无返回值" );
return null;
}
logger.info( "\nTransactionID=" + res.getTransactionID() + "\nProtocolID=" + res.getProtocolID() + "\nDataLength=" + res.getDataLength()
+ "\nUnitID=" + res.getUnitID() + "\nFunctionCode=" + res.getFunctionCode() + "\nHexMessage=" + res.getHexMessage() + "" );
if (res instanceof ReadCoilsResponse) {
ReadCoilsResponse t = (ReadCoilsResponse) res;
logger.info( "\ndata=" + t.getCoils().toString() );
data = t.getCoils().toString();
}
if (res instanceof ReadInputDiscretesResponse) {
ReadInputDiscretesResponse t = (ReadInputDiscretesResponse) res;
logger.info( "\ndata=" + t.getDiscretes().toString() );
data = t.getDiscretes().toString();
System.out.println( "t.getDiscretes():" + t.getDiscretes().toString() );
}
if (res instanceof ReadInputRegistersResponse) {
ReadInputRegistersResponse t = (ReadInputRegistersResponse) res;
InputRegister[] s = t.getRegisters();
List
for (InputRegister ss : s) {
// System.out.println( ss.getValue() );
valList.add( ss.getValue() );
}
data = "04-" + StringUtils.join( valList, "-" );
logger.info( "\ndata=" + data );
}
if (res instanceof ReadMultipleRegistersResponse) {
ReadMultipleRegistersResponse t = (ReadMultipleRegistersResponse) res;
// logger.info( "\ndata=" + t.getRegisters().toString() );
Register[] rlist = t.getRegisters();
List
for (Register r : rlist) {
valList.add( r.getValue() );
}
data = "03-" + StringUtils.join( valList, "-" );
logger.info( "\ndata=" + data );
}
return data;
}