connectAuto method

  1. @override
Future<MqttClientConnectionStatus?> connectAuto(
  1. String server,
  2. int port
)
override

Connect Auto

Implementation

@override
Future<MqttClientConnectionStatus?> connectAuto(String server, int port) {
  final completer = Completer<MqttClientConnectionStatus?>();
  MqttLogger.log('MqttBrowserWsConnection::connectAuto - entered');
  // Add the port if present
  Uri uri;
  try {
    uri = Uri.parse(server);
  } on Exception catch (_, stack) {
    final message =
        'MqttBrowserWsConnection::connectAuto - The URI supplied for the WS '
        'connection is not valid - $server';
    Error.throwWithStackTrace(NoConnectionException(message), stack);
  }
  if (uri.scheme != 'ws' && uri.scheme != 'wss') {
    final message =
        'MqttBrowserWsConnection::connectAuto - The URI supplied for the WS has '
        'an incorrect scheme - $server';
    throw NoConnectionException(message);
  }

  uri = uri.replace(port: port);
  final uriString = uri.toString();
  MqttLogger.log(
    'MqttBrowserWsConnection::connectAuto -  WS URL is $uriString',
  );
  try {
    // Connect and save the socket.
    final client = WebSocket(
      uriString,
      protocols.map((e) => e.toJS).toList().toJS,
    );
    this.client = client;
    client.binaryType = 'arraybuffer';
    messageStream = MqttByteBuffer(typed.Uint8Buffer());

    StreamSubscription<Event>? openEvents;
    StreamSubscription<CloseEvent>? closeEvents;
    StreamSubscription<Event>? errorEvents;
    openEvents = client.onOpen.listen((event) {
      MqttLogger.log(
        'MqttBrowserWsConnection::connectAuto - websocket is open',
      );
      openEvents?.cancel();
      closeEvents?.cancel();
      errorEvents?.cancel();
      _startListening();
      return completer.complete();
    });

    closeEvents = client.onClose.listen((e) {
      MqttLogger.log(
        'MqttBrowserWsConnection::connectAuto - websocket is closed',
      );
      openEvents?.cancel();
      closeEvents?.cancel();
      errorEvents?.cancel();
      return completer.complete(MqttClientConnectionStatus());
    });

    errorEvents = client.onError.listen((e) {
      MqttLogger.log(
        'MqttBrowserWsConnection::connectAuto - websocket has errored',
      );
      openEvents?.cancel();
      closeEvents?.cancel();
      errorEvents?.cancel();
      return completer.complete(MqttClientConnectionStatus());
    });
  } on Exception catch (_, stack) {
    final message =
        'MqttBrowserWsConnection::connectAuto - The connection to the message broker '
        '{$uriString} could not be made.';
    Error.throwWithStackTrace(NoConnectionException(message), stack);
  }
  MqttLogger.log(
    'MqttBrowserWsConnection::connectAuto - connection is waiting',
  );
  return completer.future;
}