Home > Mobile >  Android, through the modbus protocol, reading and writing PLC register values, be urgent!!!!
Android, through the modbus protocol, reading and writing PLC register values, be urgent!!!!

Time:10-01

Which for example, or API, help, torture day, thank you,

CodePudding user response:

https://blog.csdn.net/MickeyTaKigin/article/details/77803736

CodePudding user response:

 private void write (final int data) {
New Thread (new Runnable () {
@ Override
Public void the run () {
If (master==null) {
if (! InitModbus ()) {
return;
}
GetActivity (). The runOnUiThread (new Runnable () {
@ Override
Public void the run () {
StatetextView. SetText (" order status: failure ");
}
});
}
WriteRegisterRequest WriteRegisterRequest=null;
Try {
SharedPreferences SharedPreferences=getActivity (). GetSharedPreferences (" System ", 0);
Int slaveId=sharedPreferences. Get int (" Slave ", 2);
Int address=sharedPreferences. Get int (" Register ", 1);
WriteRegisterRequest=new writeRegisterRequest (slaveId, address, data);
WriteRegisterResponse WriteRegisterResponse=(WriteRegisterResponse) master. Send (writeRegisterRequest);
If (writeRegisterResponse isException ()) {
GetActivity (). The runOnUiThread (new Runnable () {
@ Override
Public void the run () {
StatetextView. SetText (" order status: failure ");
}
});
The v (" exception ", writeRegisterResponse getExceptionMessage ());
} else {
GetActivity (). The runOnUiThread (new Runnable () {
@ Override
Public void the run () {
StatetextView. SetText (" order status: success ");
}
});
The v (" write ", "succeed");
}

} the catch (ModbusTransportException e) {
e.printStackTrace();
} the finally {
Master. Destroy ();
}
}

}). The start ();

}


Private Boolean initModbus () {
ModbusFactory factory=new ModbusFactory ();
IpParameters params=new IpParameters ();
//set the IP address and port number
SharedPreferences SharedPreferences=getActivity (). GetSharedPreferences (" System ", 0);
String IP=sharedPreferences. Get String (" IP ", "192.168.1.21");
If (IP==null) {
Toast. MakeText (getActivity (), "not set the IP, please set the IP, Toast. LENGTH_LONG), show ();
return false;
}
Params. SetHost (IP);
Params. SetPort (502);
//params. SetEncapsulated (false);
//create ModbusMaster and set the timeout
Master=factory. CreateTcpMaster (params, true);
Master. The setTimeout (2000);
Master. SetRetries (1);

Try {
Master. The init ();
return true;
} the catch (Exception e) {
The e (" modbus ", "exception:" + e. oString ());
return false;
}
}



https://download.csdn.net/download/qq_33813665/10024698