Перенаправление идентификатора mqtt_client и источника отключения none

#flutter #dart #mqtt

#трепетание #dart #mqtt

Вопрос:

Информация о флаттере:

 Flutter 1.22.6 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 9b2d32b605 (3 weeks ago) • 2021-01-22 14:36:39 -0800
Engine • revision 2f0af37152
Tools • Dart 2.10.5
 

Я пытаюсь использовать mqtt_client для подключения к брокеру (emqx), хотя я также пробовал hivemq и получаю ту же ошибку. Код, который я использую для подключения, является:

 import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

class MqttTest {

  Future<MqttServerClient> connect() async {
    MqttServerClient client = MqttServerClient.withPort('<ip redacted>', 'client-1', 1883);
    client.logging(on: true);
    client.onConnected = onConnected;
    client.onDisconnected = onDisconnected;
    client.onUnsubscribed = onUnsubscribed;
    client.onSubscribed = onSubscribed;
    client.onSubscribeFail = onSubscribeFail;
    client.pongCallback = pong;

    final connMessage = MqttConnectMessage()
      .keepAliveFor(60)
      .withWillTopic('willtopic')
      .withWillMessage('willMessage')
      .startClean()
      .withWillQos(MqttQos.atLeastOnce);

    client.connectionMessage = connMessage;

    try {
      await client.connect();
    } catch(e) {
      print('Exception: $e');
      client.disconnect();
    }

    client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final MqttPublishMessage message = c[0].payload;
      final payload = MqttPublishPayload.bytesToStringAsString(message.payload.message);

      print('Received message:$payload from topic: ${c[0].topic}>');
    });

    return client;
  }

  void onConnected() {
    print('Connected');
  }

  void onDisconnected() {
    print('Disconnected');
  }

  void onSubscribed(String topic) {
    print('Subscribed topic: $topic');
  }

  void onSubscribeFail(String topic) {
    print('Failed to subscribe $topic');
  }

  void onUnsubscribed(String topic) {
    print('Unsubscribed topic: $topic');
  }

  void pong() {
    print('Ping response client callback invoked');
  }
}
 

Вот журналы при попытке подключения:

 I/flutter ( 9784): 2-2021-02-12 20:25:05.602730 -- MqttConnectionHandlerBase::connect - server 192.168.0.34, port 1883
I/flutter ( 9784): 2-2021-02-12 20:25:05.603044 -- SynchronousMqttServerConnectionHandler::internalConnect entered
I/flutter ( 9784): 2-2021-02-12 20:25:05.603131 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0, auto reconnect in progress false
I/flutter ( 9784): 2-2021-02-12 20:25:05.603230 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
I/flutter ( 9784): 2-2021-02-12 20:25:05.603668 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect
I/flutter ( 9784): 2-2021-02-12 20:25:05.603767 -- MqttNormalConnection::connect - entered
I/flutter ( 9784): 2-2021-02-12 20:25:05.662356 -- MqttServerConnection::_startListening
I/flutter ( 9784): 2-2021-02-12 20:25:05.662832 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
I/flutter ( 9784): 2-2021-02-12 20:25:05.663126 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
I/flutter ( 9784): 2-2021-02-12 20:25:05.663404 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
I/flutter ( 9784): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 0
I/flutter ( 9784): Connect Variable Header: ProtocolName=MQIsdp, ProtocolVersion=3, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=true, WillQos=MqttQos.atLeastOnce, WillRetain=false, PasswordFlag=false, UserNameFlag=false, KeepAlive=60
I/flutter ( 9784): MqttConnectPayload - client identifier is : 
I/flutter ( 9784): 2-2021-02-12 20:25:05.666395 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
I/flutter ( 9784): 2-2021-02-12 20:25:05.670081 -- MqttConnection::_onData
I/flutter ( 9784): 2-2021-02-12 20:25:05.670414 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.connectAck
I/flutter ( 9784): Header: MessageType = MqttMessageType.connectAck, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 2
I/flutter ( 9784): Connect Variable Header: TopicNameCompressionResponse={0}, ReturnCode={MqttConnectReturnCode.identifierRejected}
I/flutter ( 9784): 2-2021-02-12 20:25:05.670585 -- MqttServerConnection::_onData - message available event fired
I/flutter ( 9784): 2-2021-02-12 20:25:05.671317 -- MqttConnectionHandlerBase::_connectAckProcessor
I/flutter ( 9784): 2-2021-02-12 20:25:05.671420 -- MqttConnectionHandlerBase::_connectAckProcessor connection rejected
I/flutter ( 9784): 2-2021-02-12 20:25:05.671510 -- MqttConnectionHandlerBase::_performConnectionDisconnect entered
I/flutter ( 9784): 2-2021-02-12 20:25:05.671632 -- MqttConnectionHandlerBase:: cancelling connect timer
I/flutter ( 9784): 2-2021-02-12 20:25:05.672389 -- MqttConnectionBase::_onDone - calling disconnected callback
I/flutter ( 9784): 2-2021-02-12 20:25:05.672538 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is disconnected with return code of identifierRejected and a disconnection origin of none
I/flutter ( 9784): 2-2021-02-12 20:25:05.672625 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 1, auto reconnect in progress false
I/flutter ( 9784): 2-2021-02-12 20:25:05.672687 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
I/flutter ( 9784): 2-2021-02-12 20:25:05.672755 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect
I/flutter ( 9784): 2-2021-02-12 20:25:05.672805 -- MqttNormalConnection::connect - entered
I/flutter ( 9784): 2-2021-02-12 20:25:05.689565 -- MqttServerConnection::_startListening
I/flutter ( 9784): 2-2021-02-12 20:25:05.690119 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
I/flutter ( 9784): 2-2021-02-12 20:25:05.690352 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
I/flutter ( 9784): 2-2021-02-12 20:25:05.690550 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
I/flutter ( 9784): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 38
I/flutter ( 9784): Connect Variable Header: ProtocolName=MQIsdp, ProtocolVersion=3, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=true, WillQos=MqttQos.atLeastOnce, WillRetain=false, PasswordFlag=false, UserNameFlag=false, KeepAlive=60
I/flutter ( 9784): MqttConnectPayload - client identifier is : 
I/flutter ( 9784): 2-2021-02-12 20:25:05.692258 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
I/flutter ( 9784): 2-2021-02-12 20:25:05.695322 -- MqttConnection::_onData
I/flutter ( 9784): 2-2021-02-12 20:25:05.695474 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.connectAck
I/flutter ( 9784): Header: MessageType = MqttMessageType.connectAck, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 2
I/flutter ( 9784): Connect Variable Header: TopicNameCompressionResponse={0}, ReturnCode={MqttConnectReturnCode.identifierRejected}
I/flutter ( 9784): 2-2021-02-12 20:25:05.695566 -- MqttServerConnection::_onData - message available event fired
I/flutter ( 9784): 2-2021-02-12 20:25:05.695650 -- MqttConnectionHandlerBase::_connectAckProcessor
I/flutter ( 9784): 2-2021-02-12 20:25:05.695708 -- MqttConnectionHandlerBase::_connectAckProcessor connection rejected
I/flutter ( 9784): 2-2021-02-12 20:25:05.695777 -- MqttConnectionHandlerBase::_performConnectionDisconnect entered
I/flutter ( 9784): 2-2021-02-12 20:25:05.695836 -- MqttConnectionHandlerBase:: cancelling connect timer
I/flutter ( 9784): 2-2021-02-12 20:25:05.696047 -- MqttConnectionBase::_onDone - calling disconnected callback
I/flutter ( 9784): 2-2021-02-12 20:25:05.696120 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is disconnected with return code of identifierRejected and a disconnection origin of none
I/flutter ( 9784): 2-2021-02-12 20:25:05.696170 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 2, auto reconnect in progress false
I/flutter ( 9784): 2-2021-02-12 20:25:05.696574 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
I/flutter ( 9784): 2-2021-02-12 20:25:05.696646 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect
I/flutter ( 9784): 2-2021-02-12 20:25:05.696697 -- MqttNormalConnection::connect - entered
I/flutter ( 9784): 2-2021-02-12 20:25:05.708657 -- MqttServerConnection::_startListening
I/flutter ( 9784): 2-2021-02-12 20:25:05.708823 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
I/flutter ( 9784): 2-2021-02-12 20:25:05.708878 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
I/flutter ( 9784): 2-2021-02-12 20:25:05.708960 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
I/flutter ( 9784): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 38
I/flutter ( 9784): Connect Variable Header: ProtocolName=MQIsdp, ProtocolVersion=3, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=true, WillQos=MqttQos.atLeastOnce, WillRetain=false, PasswordFlag=false, UserNameFlag=false, KeepAlive=60
I/flutter ( 9784): MqttConnectPayload - client identifier is : 
I/flutter ( 9784): 2-2021-02-12 20:25:05.709719 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
I/flutter ( 9784): 2-2021-02-12 20:25:05.713511 -- MqttConnection::_onData
I/flutter ( 9784): 2-2021-02-12 20:25:05.713653 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.connectAck
I/flutter ( 9784): Header: MessageType = MqttMessageType.connectAck, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 2
I/flutter ( 9784): Connect Variable Header: TopicNameCompressionResponse={0}, ReturnCode={MqttConnectReturnCode.identifierRejected}
I/flutter ( 9784): 2-2021-02-12 20:25:05.713730 -- MqttServerConnection::_onData - message available event fired
I/flutter ( 9784): 2-2021-02-12 20:25:05.713811 -- MqttConnectionHandlerBase::_connectAckProcessor
I/flutter ( 9784): 2-2021-02-12 20:25:05.713867 -- MqttConnectionHandlerBase::_connectAckProcessor connection rejected
I/flutter ( 9784): 2-2021-02-12 20:25:05.713920 -- MqttConnectionHandlerBase::_performConnectionDisconnect entered
I/flutter ( 9784): 2-2021-02-12 20:25:05.713973 -- MqttConnectionHandlerBase:: cancelling connect timer
I/flutter ( 9784): 2-2021-02-12 20:25:05.716320 -- MqttConnectionBase::_onDone - calling disconnected callback
I/flutter ( 9784): 2-2021-02-12 20:25:05.716455 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is disconnected with return code of identifierRejected and a disconnection origin of none
I/flutter ( 9784): 2-2021-02-12 20:25:05.716550 -- SynchronousMqttServerConnectionHandler::internalConnect failed
I/flutter ( 9784): Exception: mqtt-client::NoConnectionException: The maximum allowed connection attempts ({3}) were exceeded. The broker is not responding to the connection request message correctly The return code is MqttConnectReturnCode.identifierRejected
I/flutter ( 9784): 2-2021-02-12 20:25:05.716842 -- MqttConnectionHandlerBase::disconnect - entered
I/flutter ( 9784): 2-2021-02-12 20:25:05.716915 -- MqttConnectionHandlerBase::_performConnectionDisconnect entered
I/flutter ( 9784): Disconnected
 

Ответ №1:

Как оказалось, проблема заключалась в том, что при создании MqttConnectMessage идентификатор клиента в конструкторе игнорируется. Мне пришлось добавить withClientIdentifier("client-1") к моему MqttConnectMessage .

Комментарии:

1. Наконец-то! ваш ответ спас меня от тонны часов разочарования.

Ответ №2:

Я столкнулся с той же проблемой и решил ее. Раньше я использовал Hivemqtt в своем приложении flutter и столкнулся с той же проблемой, поэтому позже я использую MQTTx.

Ниже я упомянул шаги по решению проблемы.

  1. Используйте последнюю зависимость от MQTT flutter
  2. Скачать MQTTX.Setup.1.7.2.exe , Ссылка
  3. Откройте MQTTX.exe затем подключитесь к серверу, указав любое случайное имя
  4. Используйте MqttServerClient.С помощью порта (‘broker.emqx.io ‘, ‘flutter_client’, 1883); и остальная часть кода будет такой же
  5. Затем запустите свое приложение. Это будет работать

N: P: перед подключением к мобильному устройству обязательно перезапустите сервер MQTT