Modbus4j and Android application
-
I am using modbus4j in Android application. Before I tested it in java, and works fine. But in Android I have problems with the master.init(), it does not work. In the manifest I add permissions for Internet and Access network state. I have a code more or less like this:
// Perform action on click // Read IP from layout*** EditText edittext_IP = (EditText) findViewById(R.id.editText1); TextView MWReaded = (TextView) findViewById(R.id.textView4); // ********************** // String slaveIP; slaveIP = edittext_IP.getText().toString(); ModbusFactory factory = new ModbusFactory(); IpParameters params = new IpParameters(); params.setHost(slaveIP); params.setPort(502); params.setEncapsulated(false); ModbusMaster master = factory.createTcpMaster(params, true); master.setTimeout(500); master.setRetries(2); try { master.init(); } catch (ModbusInitException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(getApplication(), "Error: " + e.getMessage(), 10).show(); } ModbusLocator locator = new ModbusLocator(1, RegisterRange.HOLDING_REGISTER, 0, DataType.TWO_BYTE_INT_UNSIGNED); Object xx = null; try { xx = master.getValue(locator); } catch (ModbusTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ErrorResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int Register = 0; if (xx != null){ Register = Integer.parseInt(xx.toString()); } else{ Register = 6969; } MWReaded.setText(String.valueOf(Register)); TextView txttest_n = (TextView) findViewById(R.id.textView5); txttest_n.setText("n=" + n); n = n + 1; } });
But the master is never initialized. I can see a exception. "android.os.NetworkOnMainThreadException"
**
Do you know how can I solve this problem?** -
I would suppose it's pretty much what the exception says: you're running network operations on the main thread, which Android frowns upon. Try running init in a service thread or something.
-
Hello.
Thanks for the information.
I have created and asynctask and I use the master.ini() in this new thread. Works fine.Best regards.