I try to communicate with a connected object via modbus. The problem is that just a few exchanges, the phone disconnects from the equipment due to an error. Also, the connected object does not provide internet access so by default, the android system also hesitates to maintain the wifi connection.
In my application, we will need a cyclic reading at 0.5s. Here is a small part of my code that reproduces the problem. When I only do a cyclic reading, it works, but it only takes one writing for everything to bug.
I can do more than 3000 successive reads without waiting, and 120 writes on average without waiting. Here are some statistics of what I can do.
Delay | Read | Write |
---|---|---|
0s | more than 3000 | 120 (average) |
0.5s delay | more than 3000 | 27 (max) |
import 'dart:async';
import './utilities/register_converter.dart';
import 'package:flutter/material.dart';
import 'package:modbus/modbus.dart' as modbus;
void main() {
runApp(const Home());
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
String _bottomLog = "No data to show";
int _test = 0, _success = 0;
@override
Widget build(BuildContext context) {
// overflow();
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Test app'),
),
body: Column(
children: [
const SizedBox(height: 12,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(onPressed: () => tryModbus(), child: const Text('Overflow')),
],
),
const SizedBox(height: 12,),
Text(_bottomLog),
]
),
),
);
}
void tryModbus() async {
setState(() {
_bottomLog = "Tentative de lecture\n";
});
modbus.ModbusClient modbusClient = modbus.createTcpClient('10.1.1.1');
try {
await modbusClient.connect();
overflow(modbusClient);
} catch (e){
setState(() {
_bottomLog += "Echec de connexion\n";
});
rethrow;
}
}
void overflow(modbus.ModbusClient modbusClient) async {
_test += 1;
if (_test % 100 == 0) {
await Future.delayed(const Duration(seconds: 3));
modbusClient.writeMultipleRegisters(40001, RegisterConverter.stringToRegisters("New name $_test", 10))
.then((value) => overflow(modbusClient))
.onError((error, stackTrace){
print("writing failure");
overflow(modbusClient);
});
} else {
await Future.delayed(const Duration(milliseconds: 500));
modbusClient.readHoldingRegisters(40001, 10)
.then((value){
_success += 1;
setState(() {
_bottomLog = "Test: $_test\n";
_bottomLog += "Success: $_success\n";
_bottomLog += "Failure: ${_test - _success}\n";
});
print(RegisterConverter.registersToString(value));
overflow(modbusClient);
}).onError((error, stackTrace){
print("Failure");
overflow(modbusClient);
});
}
}
}