0

I have to rewrite the following Java code using Flutter:

private fun checkMqttConnection(): Pair<Int, String> {

    try {
        val sampleClient = MqttClient(broker, clientId, MemoryPersistence())
        val factory = getTrustAllHostsSSLSocketFactory()

        if (factory == null) {
            return Pair(1, getString(R.string.wifi_ko_test_no_test))
        }

        val connOpts = MqttConnectOptions().apply {
            isCleanSession = true
            userName = username
            password = pwd.toCharArray()
            socketFactory = factory
            connectionTimeout = 5
        }

        sampleClient.connect(connOpts)
        Log.d(TAG, "Connected")
        sampleClient.disconnect()
        Log.d(TAG, "Disconnected")
    } catch (me: MqttException) {
        if (me.toString().contains("SocketTimeoutException"))
            return Pair(1, getString(R.string.wifi_ko_test_no_port))
        if (me.toString().contains("UnknownHostException"))
            return Pair(1, getString(R.string.wifi_ko_test_no_dns))
        return Pair(1, getString(R.string.wifi_ko_test_no_connection))
    }
    return Pair(0, "Ok")
}

The code that I have currently wrote in Flutter is

  Future<ApiResponse> checkMqttConnection() async {
    try {
      String clientID = "APP-${DateTime.now().millisecondsSinceEpoch}";
      String username = "USERNAME";
      String password = "PASSWORD";
      MqttServerClient client = MqttServerClient('XXXXXXXX', clientID);

      client.port = 8883;
      client.logging(on: true);

      await client.connect(username, password);
      print("CONNECTED");
      client.disconnect();
      print("DISCONEVTED");
      return ApiResponse.completed(null);
    } catch (e) {
      print(e);
      return ApiResponse.error(e.toString());
    }
  }

but does not work. This is the error i get:

I/flutter (19493): 1-2023-05-15 16:32:54.339294 -- Authenticating with username '{XXXXXXX}' and password '{XXXXXXX}'
I/flutter (19493): 1-2023-05-15 16:32:54.345251 -- MqttClient::connect - Connection timeout period is 5000 milliseconds
I/flutter (19493): 1-2023-05-15 16:32:54.350014 -- MqttClient::connect - keep alive is disabled
I/flutter (19493): 1-2023-05-15 16:32:54.355110 -- MqttConnectionHandlerBase::connect - server XXXXXXXX, port 8883
I/flutter (19493): 1-2023-05-15 16:32:54.357529 -- SynchronousMqttServerConnectionHandler::internalConnect entered
I/flutter (19493): 1-2023-05-15 16:32:54.357768 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0, auto reconnect in progress false
I/flutter (19493): 1-2023-05-15 16:32:54.358157 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
I/flutter (19493): 1-2023-05-15 16:32:54.358849 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect
I/flutter (19493): 1-2023-05-15 16:32:54.359608 -- MqttNormalConnection::connect - entered
I/flutter (19493): 1-2023-05-15 16:32:54.515812 -- MqttServerConnection::_startListening
I/flutter (19493): 1-2023-05-15 16:32:54.518787 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
I/flutter (19493): 1-2023-05-15 16:32:54.519274 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
I/flutter (19493): 1-2023-05-15 16:32:54.520494 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
I/flutter (19493): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 0
I/flutter (19493): Connect Variable Header: ProtocolName=MQIsdp, ProtocolVersion=3, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=false, WillQos=MqttQos.atMostOnce, WillRetain=false, PasswordFlag=true, UserNameFlag=true, KeepAlive=0
I/flutter (19493): MqttConnectPayload - client identifier is : APP-1684161174323
I/flutter (19493): 1-2023-05-15 16:32:54.551319 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
I/flutter (19493): 1-2023-05-15 16:32:54.586137 -- MqttConnectionBase::_onError - calling disconnected callback
E/flutter (19493): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: SocketException: Connection reset by peer (OS Error: Connection reset by peer, errno = 104), address = evlink-brk10.evco.services, port = 59406

What can be the problem? I'm quite sure the part of ConnectionOption is missing, but I don't know where I can configure it on Flutter library.

giordy16
  • 275
  • 1
  • 12
  • Possibly `client.secure = true;` (port 8883 will, most likely, require SSL). Please confirm which MQTT library you are using (I'd guess it will have examples showing how to set the security context). – Brits May 15 '23 at 19:52
  • @Brits I tried this, and now it gives the error **I/flutter (18104): 1-2023-05-16 09:25:09.237360 -- MqttSecureConnection::connect - entered I/flutter (18104): 1-2023-05-16 09:25:10.161870 -- MqttConnectionBase::_onError - calling disconnected callback I/flutter (18104): HandshakeException: Handshake error in client (OS Error: I/flutter (18104): UNSUPPORTED_PROTOCOL(handshake_client.cc:697))** – giordy16 May 16 '23 at 07:26
  • I am using https://pub.dev/packages/mqtt_client – giordy16 May 16 '23 at 07:29
  • So are you following [the example](https://github.com/shamblett/mqtt_client/blob/master/example/mqtt_server_client_secure.dart)? That error may be due to the [TLS version](https://stackoverflow.com/a/74373966/11810946) supported by your server (but that's another guess). Info on what you are connecting to may help. – Brits May 16 '23 at 09:56
  • @Brits Yeah I am following that example. I also read that question, but seems to be that the solution was on the server side, and I don't have access to that. That's my I am looking for a solution on client side, also because on native Android is working – giordy16 May 17 '23 at 13:16
  • Yep the solution in that case was on the server side; however we need to confirm if that is actually the problem before moving onto solutions (you have not provided any broker details so I'm guessing here). Try running `openssl s_client -connect XXXXXXXX.XXX:8883 -tls1_3` (if that fails try `tls_12`). I believe Dart requires 1.2 [by default](https://github.com/dart-lang/sdk/issues/46875) (but don't use this myself!). – Brits May 17 '23 at 20:32

0 Answers0