Flutter MQTT disconnect immediately after connecting

2.3k views Asked by At

I am using the mqtt_client package for my project (this is my first project in MQTT). my code is below.

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

enum MQTTAppConnectionState { connected, disconnected, connecting }

class MQTTManager {
  // Private instance of client
  MQTTAppConnectionState _currentState = MQTTAppConnectionState.disconnected;
  MqttServerClient? _client;
  final String _identifier = 'test';
  final String _host = 'test.mosquitto.org';
  final String _topic = 'TTestTopic';

  void initializeMQTTClient() {
    _client = MqttServerClient(_host, _identifier);
    _client!.setProtocolV311();
    _client!.port = 1883;
    _client!.keepAlivePeriod = 60;
    _client!.onDisconnected = onDisconnected;
    _client!.logging(on: true);
    _client!.onConnected = onConnected;
    _client!.onSubscribed = onSubscribed;

    final MqttConnectMessage connMess = MqttConnectMessage()
        .withClientIdentifier(_identifier)
        .withWillTopic('willTopic')
        .withWillMessage('My Will message')
        .startClean()
        .withWillQos(MqttQos.atLeastOnce);
    _client!.connectionMessage = connMess;
    print('Initialize::Mosquitto client connecting....');
  }

  void connect() async {
    try {
      await _client!.connect();
    } on NoConnectionException catch (e) {
      print('Connect::client exception - $e');
      disconnect();
    } on SocketException catch (e) {
      print('Connect::socket exception - $e');
      disconnect();
    }

    if (_client!.connectionStatus!.state == MqttConnectionState.connected) {
      print('Connect::Mosquitto client connected');
    } else {
      print(
          'Connect::ERROR Mosquitto client connection failed - disconnecting, status is ${_client!.connectionStatus}');
      disconnect();
    }
  }

  void disconnect() {
    print('Disconnect::Mosquitto client Disconnecting...');
    _client!.disconnect();
  }

  void publish(String message) {
    final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
    builder.addString(message);
    _client!.publishMessage(_topic, MqttQos.exactlyOnce, builder.payload!);
    print('Publish::The Message published');
  }

  void onSubscribed(String topic) {
    print('onSubscribed::Subscription confirmed for topic $topic');
  }

  void onDisconnected() {
    print(
        'onDisconnected::OnDisconnected client callback - Client disconnection');
    if (_client!.connectionStatus!.disconnectionOrigin ==
        MqttDisconnectionOrigin.solicited) {
      print(
          'onDisconnected::OnDisconnected callback is solicited, this is correct');
    } else {
      print(
          'onDisconnected::OnDisconnected callback is unsolicited or none, this is incorrect - exiting');
      print(_client!.connectionStatus!.disconnectionOrigin);
    }
  }

  void onConnected() {
    print('onConnected::Mosquitto client connected');
    publish('test-message');
  }
}

On the main page, I am calling the initializeMQTTClient function, and after that, I am calling the connect function. it is supposed to connect to the MQTT broker. but it is disconnecting automatically right after the connection is established

the log is below

Performing hot restart...                                               
Restarted application in 2,774ms.
D/ViewRootImpl@7dfadf8[MainActivity]( 3522): ViewPostIme pointer 0
D/ViewRootImpl@7dfadf8[MainActivity]( 3522): ViewPostIme pointer 1
I/flutter ( 3522): Initialize::Mosquitto client connecting....
D/ViewRootImpl@7dfadf8[MainActivity]( 3522): ViewPostIme pointer 0
D/ViewRootImpl@7dfadf8[MainActivity]( 3522): ViewPostIme pointer 1
I/flutter ( 3522): 1-2022-07-20 12:49:24.073836 -- MqttClient::connect - keep alive is enabled with a value of 60 seconds
I/flutter ( 3522): 1-2022-07-20 12:49:24.086424 -- MqttConnectionKeepAlive:: Initialised with a keep alive value of 60 seconds
I/flutter ( 3522): 1-2022-07-20 12:49:24.086761 -- MqttConnectionKeepAlive:: Disconnect on no ping response is disabled
I/flutter ( 3522): 1-2022-07-20 12:49:24.091955 -- MqttConnectionHandlerBase::connect - server test.mosquitto.org, port 1883
I/flutter ( 3522): 1-2022-07-20 12:49:24.098246 -- SynchronousMqttServerConnectionHandler::internalConnect entered
I/flutter ( 3522): 1-2022-07-20 12:49:24.099240 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0, auto reconnect in progress false
I/flutter ( 3522): 1-2022-07-20 12:49:24.101517 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
I/flutter ( 3522): 1-2022-07-20 12:49:24.103563 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect
I/flutter ( 3522): 1-2022-07-20 12:49:24.106087 -- MqttNormalConnection::connect - entered
I/flutter ( 3522): 1-2022-07-20 12:49:26.946207 -- MqttServerConnection::_startListening
I/flutter ( 3522): 1-2022-07-20 12:49:26.957122 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
I/flutter ( 3522): 1-2022-07-20 12:49:26.957554 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
I/flutter ( 3522): 1-2022-07-20 12:49:26.958760 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
I/flutter ( 3522): Header: MessageType = MqttMessageType.connect, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 0
I/flutter ( 3522): Connect Variable Header: ProtocolName=MQTT, ProtocolVersion=4, ConnectFlags=Connect Flags: Reserved1=false, CleanStart=true, WillFlag=true, WillQos=MqttQos.atLeastOnce, WillRetain=false, PasswordFlag=false, UserNameFlag=false, KeepAlive=60
I/flutter ( 3522): MqttConnectPayload - client identifier is : test
I/flutter ( 3522): 1-2022-07-20 12:49:27.006966 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
I/flutter ( 3522): 1-2022-07-20 12:49:27.594101 -- MqttConnection::_onData
I/flutter ( 3522): 1-2022-07-20 12:49:27.612564 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.connectAck
I/flutter ( 3522): Header: MessageType = MqttMessageType.connectAck, Duplicate = false, Retain = false, Qos = MqttQos.atMostOnce, Size = 2
I/flutter ( 3522): Connect Variable Header: TopicNameCompressionResponse={0}, ReturnCode={MqttConnectReturnCode.connectionAccepted}
I/flutter ( 3522): 1-2022-07-20 12:49:27.617457 -- MqttServerConnection::_onData - message available event fired
I/flutter ( 3522): 1-2022-07-20 12:49:27.625087 -- MqttConnectionHandlerBase::_connectAckProcessor
I/flutter ( 3522): 1-2022-07-20 12:49:27.625838 -- MqttConnectionHandlerBase:_connectAckProcessor - state = connected
I/flutter ( 3522): onConnected::Mosquitto client connected
I/flutter ( 3522): 1-2022-07-20 12:49:27.635989 -- PublishingManager::publish - entered with topic TTestTopic
I/flutter ( 3522): 1-2022-07-20 12:49:27.641728 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.publish
I/flutter ( 3522): Header: MessageType = MqttMessageType.publish, Duplicate = false, Retain = false, Qos = MqttQos.exactlyOnce, Size = 0
I/flutter ( 3522): Publish Variable Header: TopicName={TTestTopic}, MessageIdentifier={1}, VH Length={0}
I/flutter ( 3522): Payload: {12 bytes={<116><101><115><116><45><109><101><115><115><97><103><101>
I/flutter ( 3522): Publish::The Message published
I/flutter ( 3522): 1-2022-07-20 12:49:27.648302 -- MqttConnectionHandlerBase:: cancelling connect timer
I/flutter ( 3522): 1-2022-07-20 12:49:27.649860 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is connected with return code of connectionAccepted and a disconnection origin of none
I/flutter ( 3522): 1-2022-07-20 12:49:27.650373 -- SynchronousMqttServerConnectionHandler::internalConnect exited with state Connection status is connected with return code of connectionAccepted and a 
disconnection origin of none
I/flutter ( 3522): Connect::Mosquitto client connected
I/flutter ( 3522): 1-2022-07-20 12:49:27.837663 -- MqttConnectionBase::_onDone - calling disconnected callback
I/flutter ( 3522): 1-2022-07-20 12:49:27.846350 -- MqttConnectionKeepAlive::stop - stopping keep alive
I/flutter ( 3522): onDisconnected::OnDisconnected client callback - Client disconnection
I/flutter ( 3522): onDisconnected::OnDisconnected callback is unsolicited or none, this is incorrect - exiting
I/flutter ( 3522): MqttDisconnectionOrigin.unsolicited

sometimes it gives the following error instead of 'MqttDisconnectionOrigin.unsolicited'

Unhandled Exception: SocketException: Connection reset by peer (OS Error: Connection reset by peer, errno = 104), address = test.mosquitto.org, port = 40274

I have tried flutter clean, flutter pub cache repair on the terminal. no use. I have also tried changing the ISP, no use. can some one help me solve this problem.

1

There are 1 answers

2
MrDark On

thank you for your comment Brits, it worked.

Answer: Change _identifier to a random string. You are using a public test broker; another user connecting with the same client id will cause the broker to drop your connection (and test is probably a popular ID!) – Brits