Modbus是一个工业通信系统,由带智能终端的可编程序控制器和计算机通过公用线路或局部专用线路连接而成。其系统结构既包括硬件、亦包括软件。它可应用于各种数据采集和过程监控。
由于android系统的开源性,可定制性,功能强大,网络应用成熟,很多工业设备开始逐渐使用android设备来定制工业设备系统,那么modbus在android系统上面的应用应运而生。在笔者工作期间,就主导过两个比较大的基于modbus的android项目,某大型国企的大型消防系统,某大型国企电气公司的大型充电栓系统…
这是Android版的Modbus TCP 例子,例子里面只写了对保持寄存器的读写功能,其中要注意的是对modbus的初始化、读、写等等操作都要在子线程里面进行,不然会引起网络操作在主线程的异常。
下载地址:https://github.com/zgkxzx/Modbus4Android
对于modbus 的线圈,离散寄存器,输入寄存器等等的操作,程序思路基本一致,不另作例子;对于modbus RTU/ASCII模式的通信,手机上面不带串口功能,用不了此功能,暂时没有上传。
ModbusFactory factory = new ModbusFactory();
IpParameters params = new IpParameters();
//设置IP地址以及端口号
params.setHost("192.168.0.101");
params.setPort(502);
params.setEncapsulated(false);
//创建ModbusMaster以及设置超时时间
ModbusMaster master = factory.createTcpMaster(params, true);
// master.setRetries(4);
master.setTimeout(2000);
master.setRetries(0);
master.init();
ModbusReq.readCoil(mModbusMaster, new OnRequestBack() {
@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.readDiscreteInput(mModbusMaster, new OnRequestBack() {
@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.readHoldingRegisters(mModbusMaster, new OnRequestBack() {
@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.readInputRegisters(mModbusMaster, new OnRequestBack() {
@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.writeCoil(mModbusMaster, new OnRequestBack() {
@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.writeRegister(mModbusMaster, new OnRequestBack() {
@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.writeRegisters(mModbusMaster, new OnRequestBack() {
@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});
master.destroy();
由于本人精力有限,仅封装了modbus的tcp/ip模式的协议。如有任何问题,请直接留言;如有后续要求,将更新版本仓库。
下载地址:https://github.com/zgkxzx/Modbus4Android