This is a Modbus library for Android.
compile files('libs/modbus4Android-1.0.jar')
Copy the jar to the lib directory of your project and add the config to build.gradle.
ModbusReq.getInstance().setParam(new ModbusParam()
.setHost("192.168.0.105")
.setPort(502)
.setEncapsulated(false)
.setKeepAlive(true)
.setTimeout(2000)
.setRetries(0))
.init(new OnRequestBack<String>() {
@Override
public void onSuccess(String s) {
Log.d(TAG, "onSuccess " + s);
}
@Override
public void onFailed(String msg) {
Log.d(TAG, "onFailed " + msg);
}
});
Init ModbusReq instance through setting the modbus param.
ModbusReq.getInstance().readCoil(new OnRequestBack<boolean[]>() {
@Override
public void onSuccess(boolean[] booleen) {
Log.d(TAG, "readCoil onSuccess " + Arrays.toString(booleen));
}
@Override
public void onFailed(String msg) {
Log.e(TAG, "readCoil onFailed " + msg);
}
}, 1, 1, 2);
ModbusReq.getInstance().readDiscreteInput(new OnRequestBack<boolean[]>() {
@Override
public void onSuccess(boolean[] booleen) {
Log.d(TAG, "readDiscreteInput onSuccess " + Arrays.toString(booleen));
}
@Override
public void onFailed(String msg) {
Log.e(TAG, "readDiscreteInput onFailed " + msg);
}
},1,1,5);
ModbusReq.getInstance().readHoldingRegisters(new OnRequestBack<short[]>() {
@Override
public void onSuccess(short[] data) {
Log.d(TAG, "readHoldingRegisters onSuccess " + Arrays.toString(data));
}
@Override
public void onFailed(String msg) {
Log.e(TAG, "readHoldingRegisters onFailed " + msg);
}
}, 1, 2, 8);
ModbusReq.getInstance().readInputRegisters(new OnRequestBack<short[]>() {
@Override
public void onSuccess(short[] data) {
Log.d(TAG, "readInputRegisters onSuccess " + Arrays.toString(data));
}
@Override
public void onFailed(String msg) {
Log.e(TAG, "readInputRegisters onFailed " + msg);
}
}, 1, 2, 8);
ModbusReq.getInstance().writeCoil(new OnRequestBack<String>() {
@Override
public void onSuccess(String s) {
Log.e(TAG, "writeCoil onSuccess " + s);
}
@Override
public void onFailed(String msg) {
Log.e(TAG, "writeCoil onFailed " + msg);
}
},1,1,true);
ModbusReq.getInstance().writeRegister(new OnRequestBack<String>() {
@Override
public void onSuccess(String s) {
Log.e(TAG, "writeRegister onSuccess " + s);
}
@Override
public void onFailed(String msg) {
Log.e(TAG, "writeRegister onFailed " + msg);
}
},1,1,234);
ModbusReq.getInstance().writeRegisters(new OnRequestBack<String>() {
@Override
public void onSuccess(String s) {
Log.e(TAG, "writeRegisters onSuccess " + s);
}
@Override
public void onFailed(String msg) {
Log.e(TAG, "writeRegisters onFailed " + msg);
}
},1,2,new short[]{211,52,34});
ModbusReq.getInstance().destroy();
if you use RTU Mode with SerialPort,you should do :
-
- Create a class to implement SerialPortWrapper interface.
-
- Create a ModbusMaster instance with createRtuMaster mothod of ModbusFactory class.
You have any questions to send email to me.Thanks.
- e-mail : zgkxzx@163.com
- gmail : my.own.diy@gmail.com