init method
override
Initializes the connection to the device.
Implementation
@override
Future<bool> init() async {
await runZonedGuarded<Future<void>>(
// This code cannot be a try/catch because the SocketException can be thrown at any time,
// even after this function has finished. It also cannot be caught by the caller of this function.
// Using [runZonedGuarded] ensures that the error is caught no matter when it is thrown.
() async { // Initialize the socket
_socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, _port ?? 0);
_subscription = _socket!.onlyData().listen(_controller.add);
if (!quiet) logger.info("Listening on port $port");
},
(Object error, StackTrace stack) async { // Catch errors and restart the socket
if (error is SocketException && allowedErrors.contains(error.osError!.errorCode)) {
if (!quiet) logger.warning("Socket error ${error.osError!.errorCode} on port $port. Restarting...");
await Future<void>.delayed(const Duration(seconds: 1));
await dispose();
await init();
} else {
Error.throwWithStackTrace(error, stack);
}
}
);
return true;
}