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('MqttWsConnection::connectAuto - entered');
  // Add the port if present
  Uri uri;
  try {
    uri = Uri.parse(server);
  } on Exception {
    final message =
        'MqttWsConnection::connectAuto - The URI supplied for the WS '
        'connection is not valid - $server';
    throw NoConnectionException(message);
  }
  if (uri.scheme != 'ws' && uri.scheme != 'wss') {
    final message =
        'MqttWsConnection::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(
      'MqttWsConnection::connectAuto - WS URL is $uriString, protocols are $protocols');
  try {
    // Connect and save the socket.
    WebSocket.connect(uriString,
            protocols: protocols.isNotEmpty ? protocols : null,
            headers: headers)
        .then((socket) {
      client = socket;
      _startListening();
      completer.complete();
    }).catchError((e) {
      onError(e);
      completer.completeError(e);
    });
  } on Exception {
    final message =
        'MqttWsConnection::connectAuto - The connection to the message broker '
        '{$uriString} could not be made.';
    throw NoConnectionException(message);
  }
  return completer.future;
}