Future<String?> sendAndReceiveCommand(String value) async {
try {
final ipParts =
'192.168.4.1'.split('.').map((part) => int.parse(part)).toList();
final ipAddress =
InternetAddress.fromRawAddress(Uint8List.fromList(ipParts));
final socket = await Socket.connect(ipAddress, 80,
timeout: const Duration(seconds: 10));
socket.setOption(SocketOption.tcpNoDelay, true);
final completer = Completer<String>();
String answer = '';
socket.listen((data) {
answer = ascii.decode(data);
print(answer);
if (!completer.isCompleted) {
completer.complete(answer);
}
}, onDone: () {
socket?.destroy();
}, onError: (e) {
if (!completer.isCompleted) {
completer.complete('Error');
}
socket?.destroy();
});
await Future.delayed(Duration(milliseconds: 200));
final command = 'Value:02d11d61d03d*';
socket.add(ascii.encode(command));
await socket.flush();
final response = await completer.future.timeout(
const Duration(seconds: 5),
onTimeout: () {
return 'Timeout';
},
);
return response;
} catch (e) {
return null;
}
}
In this code, I have successfully received data from the device, but unfortunately, I am struggling with returning data. I got a "Future already completed" error. How can I return data received from the device?
The output:
DATA : 02d15d55d1,0,0,0,0,0,00,0,01,00,90,0900,9999,9999,9999,9999,9999,9999,00,00,V208,03d
Timeout