shamblett / mqtt_client

A server and browser based MQTT client for dart
Other
552 stars 179 forks source link

[Help] Unhandled Exception: mqtt-client::NoConnectionException: The maximum allowed connection attempts ({3}) were exceeded. The broker is not responding to the connection request message (Missing Connection Acknowledgement? #513

Closed nimengbo closed 7 months ago

nimengbo commented 9 months ago

I/flutter (15013): 1-2024-02-05 00:36:44.691535 -- Authenticating with username '{username}' and password '{password}' I/flutter (15013): 1-2024-02-05 00:36:44.693278 -- MqttClient::connect - Connection timeout period is 5000 milliseconds I/flutter (15013): 1-2024-02-05 00:36:44.702589 -- MqttClient::connect - keep alive is enabled with a value of 60 seconds I/flutter (15013): 1-2024-02-05 00:36:44.706233 -- MqttConnectionKeepAlive:: Initialised with a keep alive value of 60 seconds I/flutter (15013): 1-2024-02-05 00:36:44.706706 -- MqttConnectionKeepAlive:: Disconnect on no ping response is disabled I/flutter (15013): 1-2024-02-05 00:36:44.716581 -- MqttConnectionHandlerBase::connect - server mqtt.example.com, port 8883 I/flutter (15013): 1-2024-02-05 00:36:44.722277 -- SynchronousMqttServerConnectionHandler::internalConnect entered I/flutter (15013): 1-2024-02-05 00:36:44.723009 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0, auto reconnect in progress false I/flutter (15013): 1-2024-02-05 00:36:44.723838 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected I/flutter (15013): 1-2024-02-05 00:36:44.725251 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect I/flutter (15013): 1-2024-02-05 00:36:44.726806 -- MqttNormalConnection::connect - entered I/flutter (15013): 1-2024-02-05 00:36:45.080243 -- MqttServerConnection::_startListening I/flutter (15013): 1-2024-02-05 00:36:45.083166 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete I/flutter (15013): 1-2024-02-05 00:36:45.083700 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message I/flutter (15013): 1-2024-02-05 00:36:45.085182 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect I/flutter (15013): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 0 I/flutter (15013): Connect Variable Header: ProtocolName=MQTT, ProtocolVersion=4, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=false, WillQos=MqttQos.atMostOnce, WillRetain=false, PasswordFlag=true, UserNameFlag=true, KeepAlive=60 I/flutter (15013): MqttConnectPayload - client identifier is : mqtt_1707064604505 I/flutter (15013): 1-2024-02-05 00:36:45.124863 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none

I/flutter (15013): 1-2024-02-05 00:36:45.472524 -- MqttConnection::onData I/flutter (15013): 1-2024-02-05 00:36:45.487794 -- MqttServerConnection::_ondata - message is not yet valid, waiting for more data ... I/flutter (15013): 1-2024-02-05 00:36:45.491569 -- MqttConnectionBase::_onDone - calling disconnected callback I/flutter (15013): 1-2024-02-05 00:36:50.132040 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none I/flutter (15013): 1-2024-02-05 00:36:50.133572 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 1, auto reconnect in progress false I/flutter (15013): 1-2024-02-05 00:36:50.134321 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected I/flutter (15013): 1-2024-02-05 00:36:50.135262 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect I/flutter (15013): 1-2024-02-05 00:36:50.136024 -- MqttNormalConnection::connect - entered I/flutter (15013): 1-2024-02-05 00:36:50.681767 -- MqttServerConnection::_startListening I/flutter (15013): 1-2024-02-05 00:36:50.683700 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete I/flutter (15013): 1-2024-02-05 00:36:50.684787 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message I/flutter (15013): 1-2024-02-05 00:36:50.685609 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect I/flutter (15013): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 48 I/flutter (15013): Connect Variable Header: ProtocolName=MQTT, ProtocolVersion=4, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=false, WillQos=MqttQos.atMostOnce, WillRetain=false, PasswordFlag=true, UserNameFlag=true, KeepAlive=60 I/flutter (15013): MqttConnectPayload - client identifier is : mqtt_1707064604505 I/flutter (15013): 1-2024-02-05 00:36:50.690587 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none I/flutter (15013): 1-2024-02-05 00:36:50.989468 -- MqttConnection::onData I/flutter (15013): 1-2024-02-05 00:36:50.992254 -- MqttServerConnection::_ondata - message is not yet valid, waiting for more data ... I/flutter (15013): 1-2024-02-05 00:36:50.994184 -- MqttConnectionBase::_onDone - calling disconnected callback I/flutter (15013): 1-2024-02-05 00:36:55.699826 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none I/flutter (15013): 1-2024-02-05 00:36:55.700956 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 2, auto reconnect in progress false I/flutter (15013): 1-2024-02-05 00:36:55.701679 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected I/flutter (15013): 1-2024-02-05 00:36:55.702441 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect I/flutter (15013): 1-2024-02-05 00:36:55.703496 -- MqttNormalConnection::connect - entered I/flutter (15013): 1-2024-02-05 00:36:56.012784 -- MqttServerConnection::_startListening I/flutter (15013): 1-2024-02-05 00:36:56.014858 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete I/flutter (15013): 1-2024-02-05 00:36:56.016021 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message I/flutter (15013): 1-2024-02-05 00:36:56.017024 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect I/flutter (15013): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 48 I/flutter (15013): Connect Variable Header: ProtocolName=MQTT, ProtocolVersion=4, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=false, WillQos=MqttQos.atMostOnce, WillRetain=false, PasswordFlag=true, UserNameFlag=true, KeepAlive=60 I/flutter (15013): MqttConnectPayload - client identifier is : mqtt_1707064604505 I/flutter (15013): 1-2024-02-05 00:36:56.021877 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none I/flutter (15013): 1-2024-02-05 00:36:56.320124 -- MqttConnection::onData I/flutter (15013): 1-2024-02-05 00:36:56.323147 -- MqttServerConnection::_ondata - message is not yet valid, waiting for more data ... I/flutter (15013): 1-2024-02-05 00:36:56.324923 -- MqttConnectionBase::_onDone - calling disconnected callback I/flutter (15013): 1-2024-02-05 00:37:01.028300 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none I/flutter (15013): 1-2024-02-05 00:37:01.029913 -- SynchronousMqttServerConnectionHandler::internalConnect failed E/flutter (15013): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: mqtt-client::NoConnectionException: The maximum allowed connection attempts ({3}) were exceeded. The broker is not responding to the connection request message (Missing Connection Acknowledgement?

Future<MqttClientConnectionStatus?> connectToServer() async {
    return connect('mqtt.example.com', 8883,
        'mqtt_${DateTime.now().millisecondsSinceEpoch}', 'username', 'password'
        isSsl: true);
  }

  Future<MqttClientConnectionStatus?> connect(String server, int port,
      String clientIdentifier, String username, String password,
      {bool isSsl = false,
      DisconnectCallback? onDisconnected,
      ConnectCallback? onConnected}) async {
    _subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      _log('_subscription result $result');
      _currentConnectivityResult = result;
    });

    _log("mqtt connect to $server:$port, clientId:$clientIdentifier");
    mqttClient = MqttServerClient.withPort(server, clientIdentifier, port);

    mqttClient.onSubscribed = _onSubscribed;

    mqttClient.onSubscribeFail = _onSubscribeFail;

    mqttClient.onUnsubscribed = _onUnSubscribed;
    mqttClient.onDisconnected = () {
      _log('断开连接');
      onDisconnected?.call();
    };
    mqttClient.onConnected = () {
      _log('连接成功');
      onConnected?.call();
    };
    // var connectMessage = MqttConnectMessage()
    //     .withClientIdentifier(clientIdentifier)
    // // Explicitly set the will flag
    // //     .withWillQos(MqttQos.atMostOnce)
    //     .authenticateAs(username, password)
    //     .startClean();
    // mqttClient.connectionMessage = connectMessage;
    mqttClient.setProtocolV311();
    mqttClient.logging(on: true);
    mqttClient.keepAlivePeriod = 60;
    if (isSsl) {
      mqttClient.secure = false;
      // mqttClient.onBadCertificate = (dynamic a) => true;
      /// Security context
      String ca = "lib/assets/ota/my_root_ca.pem"; //path to asset
      ByteData caBytes = await rootBundle.load(ca); //load sound from assets
      Uint8List caBytesList = caBytes.buffer.asUint8List();

      String key = "lib/assets/ota/emqx.key"; //path to asset
      ByteData keyBytes = await rootBundle.load(key); //load sound from assets
      Uint8List keyBytesList = keyBytes.buffer.asUint8List();
      String client = "lib/assets/ota/emqx.pem"; //path to asset
      ByteData clientBytes =
          await rootBundle.load(client); //load sound from assets
      Uint8List clientBytesList = clientBytes.buffer.asUint8List();

      SecurityContext context = SecurityContext()
        ..setTrustedCertificatesBytes(caBytesList)
        ..usePrivateKeyBytes(keyBytesList)
        ..useCertificateChainBytes(clientBytesList);
      mqttClient.securityContext = context;
    }

    _log("mqtt正在连接中...");
    MqttClientConnectionStatus? status = await mqttClient.connect(username, password);
    _log("mqtt 连接状态..${status?.toString()}.");
    return status;
  }

When i call the connectToServer() , will connect failed, please help me to find out the problem ? thanks

shamblett commented 9 months ago

You need to set secure to true for secure working you have it set to false

nimengbo commented 8 months ago

You need to set secure to true for secure working you have it set to false

When i use the [https://github.com/emqx/MQTTX](mqttx client) secure set false means client would not to verify the CA and server,how can i use mqtts when set secure false

shamblett commented 8 months ago

You can either use non secure working on the MQTT standard port 1883 or secure working on port 8883 as you are doing.

If you use 1883 set secure to false which is the default, if you use 8883 then set secure to true but your security credentials must be valid at the tls level.

Refer to the examples or read the API docs.

tvanhuu commented 8 months ago

You need to set secure to true for secure working you have it set to false

Thank for suggestion. It's working