Git Product home page Git Product logo

mqtt5_client's Introduction

mqtt5_client

Build Status

A server and browser based MQTT Version 5 client for Dart.

The client is an MQTT Version 5 implementation supporting subscription/publishing at all QOS levels, authentication, keep alive and synchronous connection. The client is designed to take as much MQTT protocol work off the user as possible, connection protocol is handled automatically as are the message exchanges needed to support the different QOS levels and the keep alive mechanism. This allows the user to concentrate on publishing/subscribing and not the details of MQTT itself.

Examples of usage can be found in the examples directory.

The server client supports both normal and secure TCP connections and secure(wss) and non-secure(ws) websocket connections. The browser client supports only secure(wss) and non-secure(ws) websocket connections.

Please read the changelog for details related to specific versions.

This version of the client supports the full MQTT Version 5 message set including the setting and reception of user properties and authentication using the authenticate message. Some aspects of the MQTT version 5 protocol are not yet fully implemented and will be added in future versions. If some particular currently unsupported functionality is needed please raise an issue for it and this will be processed ahead of other functionality.

Omissions from the full MQTT Version 5 specification in this version are as follows :-

  • Parameters received in the connect acknowledge message are not fully acted upon, e.g receive maximum and topic alias maximum values for instance are not enforced.
  • Subscription identifiers and shared subscriptions are not fully supported.
  • Server redirection is not supported.
  • Reason codes are processed only in support of the protocol itself, other than this although received reason codes are made available to the user the client will not necessarily take any action itself.
  • Flow control is not fully supported.

mqtt5_client's People

Contributors

amarghosh avatar ashu-pietech avatar deepanchal avatar eldavoo avatar felixduelmer avatar irusher avatar levili-t avatar shamblett avatar skuggaedward avatar stijn1989 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mqtt5_client's Issues

App freezes after a while when number of topics are more

app freeze when the number of subscriptions are more. Pasted last trail logs here

I/flutter ( 3602): 2021-02-08 19:21:33.752252 -- MqttServerConnection::_onData - message available event fired I/flutter ( 3602): 2021-02-08 19:21:33.752355 -- MqttServerConnection::_onData - Message Received Ended <<< I/flutter ( 3602): 2021-02-08 19:21:33.753225 -- MqttConnectionHandlerBase::messageAvailable - message type is MqttMessageType.publish I/flutter ( 3602): 2021-02-08 19:21:33.754938 -- MqttPublishingManager::handlePublish - entered I/flutter ( 3602): 2021-02-08 19:21:33.759217 -- MqttConnectionHandlerBase::sendMessage - sending message started >>> -> MQTTMessage of type MqttMessageType.publishReceived I/flutter ( 3602): MessageType = MqttMessageType.publishReceived Duplicate = false Retain = false Qos = atMostOnce Size = 0 I/flutter ( 3602): Message Identifier = 1 I/flutter ( 3602): Reason Code = success I/flutter ( 3602): Properties = No properties set I/flutter ( 3602): I/flutter ( 3602): 2021-02-08 19:21:33.760230 -- MqttConnectionHandlerBase::sendMessage - sending message ended >>> I/flutter ( 3602): 2021-02-08 19:21:33.764121 -- MqttServerConnection::_onData - Message Received Started <<< I/flutter ( 3602): 2021-02-08 19:21:33.764245 -- MqttServerConnection::_ondata - adding incoming data, data length is 1168, message stream length is 0, message stream position is 0

AWS IOT Connection

Hello there,

I am wondaring if there any example for using the lib with AWS IoT.

Thanks.

Please help on why can not connect to broker

Hi, this is my code:

 _client =
        MqttServerClient.withPort(host, cid, 1883, maxConnectionAttempts: 3);
    kLog(
        '!!!! ------------> [conn] connect with $host, $port, $username, $password, ${_clientId} $_client');

    _client!.logging(on: true);
    // _client!.logging(on: false);
    _client!.onConnected = onConnected;
    _client!.onDisconnected = onDisconnected;
    _client!.onUnsubscribed = onUnsubscribed;
    _client!.onSubscribed = onSubscribed;
    _client!.onSubscribeFail = onSubscribeFail;
    _client!.onAutoReconnect = onAutoReconnect;
    _client!.pongCallback = pong;
    _client!.keepAlivePeriod = 60 * 3;
    _client!.autoReconnect = false;
    _client!.useWebSocket = useWebsocket;

    final connMessage = MqttConnectMessage()
        .authenticateAs(username, password)
        // .withWillTopic('lastwills')
        // .withWillMessage('Will message')
        .withClientIdentifier(cid);
    // .withProtocolName("MQTT")
    // .withProtocolVersion(4)
    // .withSessionExpiryInterval(interval)
    // .withWillQos(MqttQos.atLeastOnce);
    _client!.connectionMessage = connMessage;
    try {
      //_messagesController =  StreamController.broadcast();
      _broadcastConnectionState();
      await _client!.connect();
      _broadcastConnectionState();
      // only after connected?
      _subscribeToArchivesTopics();
      _listenAndFilter();

      return true;
    } catch (e) {
      kLog('Exception: $e');
      if (_client != null) _client!.disconnect();
      return false;
    }

Now, the connection ends up 3 maxium failure connection, then disconnected.

Every try tells my different reason:


MessageType = MqttMessageType.connectAck Duplicate = false Retain = false Qos = atMostOnce Size = 6
I/flutter (20758): Session Present = true
I/flutter (20758): Connect Reason Code = success
I/flutter (20758): Session Expiry Interval = 0
I/flutter (20758): Receive Maximum = 1024
I/flutter (20758): Maximum QoS = 2
I/flutter (20758): Retain Available = false
I/flutter (20758): Maximum Packet Size = 0
I/flutter (20758): Assigned client Identifier = null
I/flutter (20758): Topic Alias Maximum = 0
I/flutter (20758): Reason String = null
I/flutter (20758): Wildcard Subscription Available = true
I/flutter (20758): Subscription Identifiers Available = true
I/flutter (20758): Shared Subscription Available = true
I/flutter (20758): broker Keep Alive = 0
I/flutter (20758): Response Information = null
I/flutter (20758): broker Reference = null
I/flutter (20758): Authentication Method = null
I/flutter (20758): Properties = Identifier : receiveMaximum, value : 1024
I/flutter (20758):
I/flutter (20758): 2023-11-20 22:38:01.838114 -- MqttServerConnection::_onData - Message Received Ended <<<
I/flutter (20758): 2023-11-20 22:38:01.838530 -- MqttServerConnection::_onData - Message Received Started <<<
I/flutter (20758): 2023-11-20 22:38:01.838665 -- MqttServerConnection::_ondata - adding incoming data, data length is 23, message stream length is 0, message stream position is 0
I/flutter (20758): 2023-11-20 22:38:01.838777 -- MqttServerConnection::_ondata - added incoming data message stream length is 23, message stream position is 0
I/flutter (20758): 2023-11-20 22:38:01.839262 -- MqttByteBuffer:isMessageAvailable - assumed valid header, value is 224
I/flutter (20758): 2023-11-20 22:38:01.840691 -- MqttServerConnection::_onData - MESSAGE RECEIVED -> MQTTMessage of type MqttMessageType.disconnect
I/flutter (20758): MessageType = MqttMessageType.disconnect Duplicate = false Retain = false Qos = atMostOnce Size = 21
I/flutter (20758):
I/flutter (20758): Reason Code  = sessionTakenOver
I/flutter (20758): Properties = Identifier : reasonString, value : session takeover
I/flutter (20758): 2023-11-20 22:38:01.841056 -- MqttServerConnection::_onData - Message Received Ended <<<
I/flutter (20758): 2023-11-20 22:38:01.843045 -- MqttConnectionBase::_onDone - calling disconnected callback
I/flutter (20758): 2023-11-20 22:38:01.843274 -- MqttClient::internalDisconnect - not invoking disconnect, no connection handler
I/flutter (20758): 2023-11-20 22:38:06.835011 -- MqttSynchronousServerConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of notSet and a disconnection origin of none
I/flutter (20758): 2023-11-20 22:38:06.835491 -- MqttSynchronousServerConnectionHandler::internalConnect failed
I/flutter (20758): [KLOG] 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?

Can anyone tell me why this happen?

Unsubscribe doesn't change value of subscriptionTopicStatus

Hello again,

When I unsubscribe from topics value of subscriptionTopicStatus stays pending before unsubAck and after unsubscribeAck message changes back to active. Am I doing something wrong or is this a bug?

I've reused test from issue #22 for it:

import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';
import 'package:typed_data/typed_buffers.dart';
import 'package:test/test.dart';

Future<int> main() async {
  resubscribeAfterUnsubscribe(String broker_url, int port, bool useWs, int delay) async {
    final client = MqttServerClient(broker_url, "");
    client.useWebSocket = useWs;
    client.port = port;
    client.logging(on: true);

    String topic = "iWantToBeUnsubscribed";
    var sendData = Uint8Buffer();

    await client.connect();

    client.subscribe(topic, MqttQos.exactlyOnce);

    print("Waiting for $delay seconds before unsubscribing");
    await MqttUtilities.asyncSleep(delay);


    client.unsubscribeStringTopic(topic);

    print("Waiting for $delay seconds after unsubscribing");
    await MqttUtilities.asyncSleep(delay);

    var subStatus = client.subscriptionsManager!.getSubscriptionTopicStatus(topic);
    print(subStatus);

    expect(subStatus, MqttSubscriptionStatus.doesNotExist);

    client.disconnect();


  }



  test("[broker.emqx.io] websocket unsubscribe", () => resubscribeAfterUnsubscribe("ws://broker.emqx.io/mqtt", 8083, true, 0));

  test("[broker.emqx.io] websocket unsubscribe after a delay", () => resubscribeAfterUnsubscribe("ws://broker.emqx.io/mqtt", 8083, true, 5));

  test("[broker.hivemq.com] websocket unsubscribe right after its published", () =>
      resubscribeAfterUnsubscribe("ws://broker.hivemq.com/mqtt", 8000, true, 0));

  test("[broker.hivemq.com] websocket unsubscribe after a delay", () => resubscribeAfterUnsubscribe("ws://broker.hivemq.com/mqtt", 8000, true, 5));

  return 0;
}

image

While using a persistent session and when client is offline and the messages published are not received

Use case

  • Flutter app - Subscriber
  • Node app - Publisher
  • QOS - 1 - Both Publisher and subscriber

** Issue **
Once the subscriber turns online from offline after initial connections are established, subscriber doesn't get all the published messages while it was offline.

Here is the code


init() async {
client = MqttServerClient.withPort(hostName, 'test2', 1883);
    client.port = 1883;
    client.secure = false;
    client.logging(on: false);
    client.autoReconnect = true;
    client.resubscribeOnAutoReconnect = false;
    client.keepAlivePeriod = 3600;
    client.onAutoReconnected = onAutoReconnected;
    client.onDisconnected = onDisconnected;
    client.onSubscribed = onSubscribed;
    client.onUnsubscribed = onUnSubscribed;

    final connMess = MqttConnectMessage()
        .withClientIdentifier('test2');
    print('EXAMPLE::Mosquitto client connecting....');
    client.connectionMessage = connMess;

    try {
      await client.connect();

    } on Exception catch (e) {
      print('EXAMPLE::client exception - $e');
      client.disconnect();
    }


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

    }


    print('EXAMPLE:: <<<< SUBCRIBE 1 >>>>');
    const topic1 = 'demo/'; 

    client.subscribe(topic1, MqttQos.atLeastOnce);
    

    client.updates.listen((dynamic c) {
      final MqttPublishMessage recMess = c[0].payload;
      final pt = MqttUtilities.bytesToStringAsString(recMess.payload.message!);
      print(
          'EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');
      print('');
    });

  
    client.published!.listen((MqttPublishMessage message) {
      print(
          'EXAMPLE::Published notification:: topic is ${message.variableHeader!.topicName}, with Qos ${message.header!.qos}');
      if (message.variableHeader!.topicName == topic1) {
        print(
            'EXAMPLE::Published notification:: Non subscribed topic publication received');
      }
    });

    final builder1 = MqttPayloadBuilder();
    builder1.addString('Hello from mqtt_client flutter');
    print('EXAMPLE:: <<<< PUBLISH 1 >>>>');
    client.publishMessage(topic1, MqttQos.atLeastOnce, builder1.payload!);
  }

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


  void onUnSubscribed(MqttSubscription topic) {
    print('EXAMPLE::UnSubscribed for topic $topic');
  }

  void onAutoReconnected() {
    print('EXAMPLE::OnAutoReconnected');
    client.resubscribe();
  }

  void onDisconnected() {
    print('EXAMPLE::OnDisconnected client callback - Client disconnection');

  }

InvalidHeaderException (Header must be at least 2 bytes long)

Hello,

I am getting the following error seemingly random - but on connection.

mqtt-client::InvalidHeaderException: The supplied header is invalid. Header must be at least 2 bytes long.

It does not stop the code from working - but obviously leaves one worried to the underlying issue.

Call Stack:
MqttHeader.readFrom (package:mqtt5_client/src/messages/mqtt_header.dart:69:7)
#1 new MqttHeader.fromByteBuffer (package:mqtt5_client/src/messages/mqtt_header.dart:19:5)
#2 MqttByteBuffer.isMessageAvailable (package:mqtt5_client/src/utility/mqtt_byte_buffer.dart:66:29)
#3 MqttServerConnection._onData (package:mqtt5_client/src/connectionhandling/server/mqtt_server_connection.dart:60:26)
#4 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
#5 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
#6 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
#7 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
#8 _StreamController._add (dart:async/stream_controller.dart:648:7)
#9 _StreamController.add (dart:async/stream_controller.dart:596:5)
#10 _Socket._onData (dart:io-patch/socket_patch.dart:2324:41)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
#12 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
#13 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
#14 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
#15 _StreamController._add (dart:async/stream_controller.dart:648:7)
#16 _StreamController.add (dart:async/stream_controller.dart:596:5)
#17 new _RawSocket. (dart:io-patch/socket_patch.dart:1849:33)
#18 _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1322:14)
#19 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
#20 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
#21 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:122:13)
#22 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:193:5)

Fix linter errors from Pub

Found 16 issues. Showing the first 2:

INFO: An uninitialized variable should have an explicit type annotation.
lib/src/connectionhandling/browser/mqtt_browser_ws_connection.dart:53:11


53 │ var closeEvents;
│ ^^^^^^^^^^^

To reproduce make sure you are using the lints_core and run dart analyze lib/src/connectionhandling/browser/mqtt_browser_ws_connection.dart

INFO: An uninitialized variable should have an explicit type annotation.
lib/src/connectionhandling/browser/mqtt_browser_ws_connection.dart:54:11


54 │ var errorEvents;
│ ^^^^^^^^^^^

To reproduce make sure you are using the lints_core and run dart analyze lib/src/connectionhandling/browser/mqtt_browser_ws_connection.dart

Bad bytes error

Hello, I encountered an error, please tell me how to get around it? Now I have a constant connect-disconnect going on in my application. Apparently due to the fact that garbage got into one of the topics, this message does not reach the user code, your library immediately calls disconnect. I used MQTTExplorer for windows, it connected successfully and there I saw that the message was some kind of garbage. I still don’t understand how it ended up there, but still, I was hoping that your library would give my code the ability to process it, and not automatically call disconnect.
If I remove this message, your library will connect and work as expected. However, if garbage gets there once, it can get there again, completely disrupting the operation of my application.
Please tell me how to get around this problem?

image

logs.txt

Use will() cannot CONNECT

I can't connect when I use will().
The broker is not responding to the connection request message (Missing Connection Acknowledgement?

pub.dartlang.org/mqtt5_client-3.1.3/lib/mqtt5_browser_client.dart:11:8: Error: Not found: 'dart:html' import 'dart:html';

I got this on Web version.

lib/mqtt_browser_client.dart: Warning: Interpreting this as package URI, 'package:mojifinal/mqtt_browser_client.dart'.
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/mqtt5_client-3.1.3/lib/mqtt5_browser_client.dart:11:8: Error: Not found: 'dart:html'
import 'dart:html';
^
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/mqtt5_client-3.1.3/lib/src/connectionhandling/browser/mqtt_browser_ws_connection.dart:51:16: Error: The method 'WebSocket' isn't defined for the class 'MqttBrowserWsConnection'.

  • 'MqttBrowserWsConnection' is from 'package:mqtt5_client/mqtt5_browser_client.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/mqtt5_client-3.1.3/lib/mqtt5_browser_client.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'WebSocket'.
    client = WebSocket(uriString, protocols);
    ^^^^^^^^^
    /C:/flutter/.pub-cache/hosted/pub.dartlang.org/mqtt5_client-3.1.3/lib/src/connectionhandling/browser/mqtt_browser_ws_connection.dart:114:16: Error: The method 'WebSocket' isn't defined for the class 'MqttBrowserWsConnection'.
  • 'MqttBrowserWsConnection' is from 'package:mqtt5_client/mqtt5_browser_client.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/mqtt5_client-3.1.3/lib/mqtt5_browser_client.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'WebSocket'.
    client = WebSocket(uriString, protocols);
    ^^^^^^^^^
    /C:/flutter/.pub-cache/hosted/pub.dartlang.org/mqtt5_client-3.1.3/lib/src/connectionhandling/browser/mqtt_browser_connection.dart:44:32: Error: 'MessageEvent' isn't a type.
    client.onMessage.listen((MessageEvent e) {
    ^^^^^^^^^^^^

Process finished with exit code 254

Unit testing broker based test updates

The unit test suite needs to be updated to remove the use of mock brokers, either we fully mock this using Mockito or maybe we use a containerised solution on Travis.

flutter_test resolve dependency fail

When I'm trying to get packages, an error appears

Because every version of flutter_test from SDK depends on typed_data 1.1.6 and app depends on typed_data ^1.2.0, flutter_test from SDK is forbidden.
So, because app depends on flutter_test any from SDK, version solving failed.
pub get failed (1; So, because app depends on flutter_test any from sdk, version solving failed.)

Looks like all latest stable Flutter releases depend on typed_data 1.1.6

NoConnectionException with Authentication example

I'm not sure what I doing wrong but when I'm using the example for authentication with my specific Broker, I always get the following exception:

mqtt-client::NoConnectionException:` The maximum allowed connection attempts ({3}) were exceeded. The broker is not responding to the connection request message

As you can see in the log, my Broker replies to the connection message but the Client does nothing with the authentication message. Instead, he tries to connect again, until he reached the maximum attempts.
So the part (client.authentication.listen((final authMessage) { ... }) where I should do the stuff and send back an authentication message, will never reached.

EXAMPLE::Mqtt5 client connecting....
2020-07-13 16:58:22.719785 -- SynchronousMqttServerConnectionHandler::internalConnect entered
2020-07-13 16:58:22.737769 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0
2020-07-13 16:58:22.738770 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
2020-07-13 16:58:22.987339 -- MqttServerConnection::_startListening
2020-07-13 16:58:23.001331 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
2020-07-13 16:58:23.001331 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
2020-07-13 16:58:23.021320 -- MqttConnectionHandlerBase::sendMessage - SENDING MESSAGE -> MQTTMessage of type MqttMessageType.connect
MessageType = MqttMessageType.connect Duplicate = false Retain = false Qos = atMostOnce Size = 0
ProtocolName = MQTT
ProtocolVersion = 5
ConnectFlags = CleanStart=true, WillFlag=false, WillQos=atMostOnce, WillRetain=false, PasswordFlag=false, UserNameFlag=false
KeepAlive = 0
Properties = Identifier : authenticationMethod, value : SMOKER
Identifier MqttPropertyIdentifier.authenticationData, value [97, 52, 101, 48, 97, 55, 51, 55, 98, 97, 57, 52, 52, 98, 49, 100, 101, 56, 99, 56, 54, 56, 97, 100, 51, 101, 49, 48, 50, 101, 49, 55, 51, 54, 55, 53, 99, 53, 52, 50, 57, 97, 97, 57, 50, 49, 56, 49, 53, 56, 97, 52, 57, 51, 50, 52, 50, 102, 100, 48, 50, 56, 52, 53]
Will topic = null
User name = not set
Password = not set

2020-07-13 16:58:23.063296 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of notSet and a disconnection origin of none
2020-07-13 16:58:23.076311 -- MqttServerConnection::_onData
2020-07-13 16:58:23.076311 -- MqttServerConnection::_ondata - adding incoming data, data length is 48, message stream length is 0, message stream position is 0
2020-07-13 16:58:23.116266 -- MqttServerConnection::_onData - MESSAGE RECEIVED -> MQTTMessage of type MqttMessageType.auth
MessageType = MqttMessageType.auth Duplicate = false Retain = false Qos = atMostOnce Size = 46

Reason Code  = continueAuthentication
Properties = Identifier : authenticationMethod, value : SMOKER
Identifier MqttPropertyIdentifier.authenticationData, value [36, 147, 111, 51, 59, 190, 190, 215, 60, 205, 131, 231, 229, 73, 70, 78, 174, 96, 40, 162, 180, 138, 222, 108, 70, 183, 193, 245, 31, 211, 221, 246]


2020-07-13 16:58:23.134256 -- MqttServerConnection::_onData - message processed
2020-07-13 16:58:23.139252 -- MqttAuthenticationManager::handleAuthentication - Authentication message received
2020-07-13 16:58:28.084758 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of notSet and a disconnection origin of none
2020-07-13 16:58:28.085734 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 1
2020-07-13 16:58:28.085734 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
2020-07-13 16:58:28.095972 -- MqttServerConnection::_startListening
2020-07-13 16:58:28.096937 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
2020-07-13 16:58:28.096937 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
2020-07-13 16:58:28.097936 -- MqttConnectionHandlerBase::sendMessage - SENDING MESSAGE -> MQTTMessage of type MqttMessageType.connect

...

2020-07-13 16:58:33.411130 -- MqttServerConnection::_onData - message processed
2020-07-13 16:58:33.411130 -- MqttAuthenticationManager::handleAuthentication - Authentication message received
2020-07-13 16:58:38.417570 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of notSet and a disconnection origin of none
2020-07-13 16:58:38.418475 -- SynchronousMqttServerConnectionHandler::internalConnect failed
EXAMPLE::client 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?
2020-07-13 16:58:38.430500 -- SynchronousMqttServerConnectionHandler::disconnect
EXAMPLE::OnDisconnected client callback - Client disconnection
EXAMPLE::OnDisconnected callback is solicited, this is correct

Did I forget something?

mqtt5_client 4.0.1 incompatible flutter_test

Flutter version 3.13.6 , mqtt5_client 4.0.1:
Because every version of flutter_test from sdk depends on meta 1.9.1 and mqtt5_client >=4.0.1 depends on meta ^1.10.0, flutter_test from sdk is incompatible with mqtt5_client >=4.0.1.

updated from version 2.1.0 to 3.3.3 and getting exception when parsing mqtt incoming messages

E/flutter (18370): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: MqttByteBuffer::clear - attempt to clear a byte buffer where postion is not zero, it is 12
E/flutter (18370): #0 MqttByteBuffer.clear (package:mqtt5_client/src/utility/mqtt_byte_buffer.dart:191:7)
E/flutter (18370): #1 MqttServerConnection._onData (package:mqtt5_client/src/connectionhandling/server/mqtt_server_connection.dart:78:23)
E/flutter (18370): #2 _rootRunUnary (dart:async/zone.dart:1399:47)
E/flutter (18370): #3 _CustomZone.runUnary (dart:async/zone.dart:1300:19)
E/flutter (18370): #4 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
E/flutter (18370): #5 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (18370): #6 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (18370): #7 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
E/flutter (18370): #8 _StreamController._add (dart:async/stream_controller.dart:648:7)
E/flutter (18370): #9 _StreamController.add (dart:async/stream_controller.dart:596:5)
E/flutter (18370): #10 new _WebSocketImpl._fromSocket. (

Error when clearing MqttByteBuffer

Hi, When I communicate with my broker and send a payload with my message, I sometimes get the following error.
Do you happen to know how I could resolve this one?

Caught error: - Error details: Bad state: MqttByteBuffer::clear - attempt to clear a byte buffer where postion is not zero, it is 2 - Stacktrace: #0 MqttByteBuffer.clear (package:mqtt5_client/src/utility/mqtt_byte_buffer.dart:191) #1 MqttServerConnection._onData (package:mqtt5_client/src/connectionhandling/server/mqtt_server_connection.dart:78) #2 _rootRunUnary (dart:async/zone.dart:1399) #3 _CustomZone.runUnary (dart:async/zone.dart:1300) #4 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209) #5 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339) #6 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271) #7 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774) #8 _StreamController._add (dart:async/stream_controller.dart:648) #9 _StreamController.add (dart:async/stream_controller.dart:596) #10 _Socket._onData (dart:io-patch/socket_patch.dart:2324) #11 _rootRunUnary (dart:async/zone.dart:1407) #12 _CustomZone.runUnary (dart:async/zone.dart:1300) #13 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1209) #14 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339) #15 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271) #16 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774) #17 _StreamController._add (dart:async/stream_controller.dart:648) #18 _StreamController.add (dart:async/stream_controller.dart:596) #19 new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1849) #20 _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1322) #21 _microtaskLoop (dart:async/schedule_microtask.dart:40) #22 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49)

Does this library supports Utf8 Chinese topic name?

HI~

I tried some Chinese topic names, but raises following exception on the bottom.
Everything goes normal when I change the topic name back to just English chars.
Does this library supports Utf8 Chinese topic names or did I just misused something?
Thanks.

I/flutter (15925): 2023-10-27 09:47:58.753472 -- MqttServerConnection::_onData - Message Received Started <<<
I/flutter (15925): 2023-10-27 09:47:58.753624 -- MqttServerConnection::_ondata - adding incoming data, data length is 1487, message stream length is 0, message stream position is 0
I/flutter (15925): 2023-10-27 09:47:58.753701 -- MqttServerConnection::_ondata - added incoming data message stream length is 1487, message stream position is 0
I/flutter (15925): 2023-10-27 09:47:58.753828 -- MqttByteBuffer:isMessageAvailable - assumed valid header, value is 48
I/flutter (15925): 2023-10-27 09:47:58.762594 -- MqttServerConnection::_ondata - exception raised is mqtt-client::InvalidMessageException: The data provided in the message stream was not a valid MQTT Message, exception is Exception: MqttByteBuffer::read: The buffer did not have enough bytes for the read operation length 1454, count 1458, position 0, buffer [123, 13, 10, 32, 32, 34, 115, 99, 101, 110, 97, 114, 105, 111, 115, 34, 58, 32, 91, 123, 34, 105, 110, 100, 101, 120, 34, 58, 49, 44, 34, 110, 97, 109, 101, 34, 58, 34, 230, 184, 172, 232, 169, 166, 230, 131, 133, 229, 162, 131, 233, 150, 139, 49, 34, 44, 34, 115, 99, 101, 110, 97, 114, 105, 111, 84, 121, 112, 101, 34, 58, 50, 44, 34, 105, 100, 34, 58, 50, 57, 125, 44, 123, 34, 105, 110, 100, 101, 120, 34, 58, 50, 44, 34, 110, 97, 109, 101, 34, 58, 34, 230, 184, 172, 232, 169, 166, 230, 131, 133, 229, 162, 131, 233, 151, 156, 34, 44, 34, 115, 99, 101, 110, 97, 114, 105, 111, 84, 121, 112, 101, 34, 58, 50, 44, 34, 105, 100, 34, 58, 51, 48, 125, 44, 123, 34, 105, 110, 100, 10
I/flutter (15925): 2023-10-27 09:47:58.762873 -- MqttServerConnection::_ondata - irrecoverable exception raised - sending disconnect mqtt-client::InvalidMessageException: The data provided in the message stream was not a valid MQTT Message, exception is Exception: MqttByteBuffer::read: The buffer did not have enough bytes for the read operation length 1454, count 1458, position 0, buffer [123, 13, 10, 32, 32, 34, 115, 99, 101, 110, 97, 114, 105, 111, 115, 34, 58, 32, 91, 123, 34, 105, 110, 100, 101, 120, 34, 58, 49, 44, 34, 110, 97, 109, 101, 34, 58, 34, 230, 184, 172, 232, 169, 166, 230, 131, 133, 229, 162, 131, 233, 150, 139, 49, 34, 44, 34, 115, 99, 101, 110, 97, 114, 105, 111, 84, 121, 112, 101, 34, 58, 50, 44, 34, 105, 100, 34, 58, 50, 57, 125, 44, 123, 34, 105, 110, 100, 101, 120, 34, 58, 50, 44, 34, 110, 97, 109, 101, 34, 58, 34, 230, 184, 172, 232, 169, 166, 230, 131, 133, 229, 162, 131, 233, 151, 156, 34, 44, 34, 115, 99, 101, 110, 97, 114, 105, 111, 84, 121, 112, 101, 34, 58, 50, 44, 34, 105, 100, 34, 58, 51, 48, 125
I/flutter (15925): 2023-10-27 09:47:58.764227 -- MqttServerConnection::_onData - Message Received Ended <<<

Retained messages not recieved upon subscribing

As far as I tried I cannot seem to get a message that was published before with a retain bit set.

Running dart client in Linux and Mosquitto broker with Rpi4. I tested my setup with a python paho client and I recieve retained messages fine. Anything I could be missing?

How to fast determine abnormal disconnect and fast restore connection?

I have two questions:
1.
If I shutdown my MQTT broker normally, the client will change it's connection state immediately, but if the MQTT broker (actually it's a Raspberry PI) shutdown by power failure, or network failure, it will take very long time (maybe few minutes or longer) to determine the connection state changed. How to make it faster?

If the client is trying connect before MQTT broker is ready or before network is ready , it will blocking a lot of time till it failed then retry next time, how to make it faster?

Thanks for help :)

Nice tool by the way.

InvalidHeaderException (Header must be at least 2 bytes long) on Processing of PublishAck / Publish Received

After publishing with QOS 1 or 2 from a flutter app, the library throws this exception.

Looking at the code, I get the feeling that there is an extra call to _onData which calls isMessageAvailable() and erroneously doesn't return false, causing it to try to read from an empty byte buffer.

I am using the library together with the bloc package, so, it is the case that the code which publishes the message is ran from a different "zone" than the code suscribing to the topic. This is the only difference I can think of from the examples provided. Also, I am not sleeping after publishing, but I tried that and nothing changed.

Log example for QOS1

II/flutter (18997): 2023-01-09 19:48:59.410625 -- MqttConnectionHandlerBase::sendMessage - sending message ended >>>
I/flutter (18997): 2023-01-09 19:48:59.552287 -- MqttServerConnection::_onData - Message Received Started <<<
I/flutter (18997): 2023-01-09 19:48:59.552645 -- MqttServerConnection::_ondata - adding incoming data, data length is 6, message stream length is 0, message stream position is 0
I/flutter (18997): 2023-01-09 19:48:59.557413 -- MqttServerConnection::_onData - MESSAGE RECEIVED -> MQTTMessage of type MqttMessageType.publishReceived
I/flutter (18997): MessageType = MqttMessageType.publishReceived Duplicate = false Retain = false Qos = atMostOnce Size = 4
I/flutter (18997): Message Identifier = 2
I/flutter (18997): Reason Code = success
I/flutter (18997): Properties = No properties set
I/flutter (18997):
I/flutter (18997): 2023-01-09 19:48:59.567799 -- MqttServerConnection::_onData - message available event fired
E/flutter (18997): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: mqtt-client::InvalidHeaderException: The supplied header is invalid. Header must be at least 2 bytes long.
I/flutter (18997): 2023-01-09 19:49:04.505405 -- MqttConnectionHandlerBase::messageAvailable - message type is MqttMessageType.publishReceived
I/flutter (18997): 2023-01-09 19:49:04.506545 -- MqttPublishingManager::handlePublishReceived - entered
I/flutter (18997): 2023-01-09 19:49:04.511134 -- MqttConnectionHandlerBase::sendMessage - sending message started >>> -> MQTTMessage of type MqttMessageType.publishRelease
I/flutter (18997): MessageType = MqttMessageType.publishRelease Duplicate = false Retain = false Qos = atLeastOnce Size = 0
I/flutter (18997): Message Identifier = 2
I/flutter (18997): Reason Code = success
I/flutter (18997): Properties = No properties set
I/flutter (18997):
I/flutter (18997): 2023-01-09 19:49:04.513729 -- MqttConnectionHandlerBase::sendMessage - sending message ended >>>
I/flutter (18997): 2023-01-09 19:49:04.520093 -- MqttServerConnection::_onData - Message Received Started <<<
I/flutter (18997): 2023-01-09 19:49:04.524466 -- MqttServerConnection::_ondata - adding incoming data, data length is 45, message stream length is 1, message stream position is 0
I/flutter (18997): 2023-01-09 19:49:04.525270 -- Available bytes(46) is less than the message size 52
I/flutter (18997): 2023-01-09 19:49:04.526407 -- MqttServerConnection::_onData - Message Received Ended <<<

Log example with QOS2:

I/flutter (18559): 2023-01-09 19:32:15.325602 -- MqttConnectionHandlerBase::sendMessage - sending message ended >>>
I/flutter (18559): 2023-01-09 19:32:15.513071 -- MqttServerConnection::_onData - Message Received Started <<<
I/flutter (18559): 2023-01-09 19:32:15.515605 -- MqttServerConnection::_ondata - adding incoming data, data length is 6, message stream length is 0, message stream position is 0
I/flutter (18559): 2023-01-09 19:32:15.521690 -- MqttServerConnection::_onData - MESSAGE RECEIVED -> MQTTMessage of type MqttMessageType.publishReceived
I/flutter (18559): MessageType = MqttMessageType.publishReceived Duplicate = false Retain = false Qos = atMostOnce Size = 4
I/flutter (18559): Message Identifier = 2
I/flutter (18559): Reason Code = success
I/flutter (18559): Properties = No properties set
I/flutter (18559):
I/flutter (18559): 2023-01-09 19:32:15.526831 -- MqttServerConnection::_onData - message available event fired
E/flutter (18559): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: mqtt-client::InvalidHeaderException: The supplied header is invalid. Header must be at least 2 bytes long.
I/flutter (18559): 2023-01-09 19:32:38.712619 -- MqttConnectionHandlerBase::sendMessage - sending message started >>> -> MQTTMessage of type MqttMessageType.publishRelease
I/flutter (18559): MessageType = MqttMessageType.publishRelease Duplicate = false Retain = false Qos = atLeastOnce Size = 0
I/flutter (18559): Message Identifier = 2
I/flutter (18559): Reason Code = success
I/flutter (18559): Properties = No properties set
I/flutter (18559):
I/flutter (18559): 2023-01-09 19:32:38.720054 -- MqttConnectionHandlerBase::sendMessage - sending message ended >>>
I/flutter (18559): 2023-01-09 19:32:38.723103 -- MqttConnectionHandlerBase::sendMessage - sending message started >>> -> MQTTMessage of type MqttMessageType.pingRequest
I/flutter (18559): MessageType = MqttMessageType.pingRequest Duplicate = false Retain = false Qos = atMostOnce Size = 0
I/flutter (18559): 2023-01-09 19:32:38.724901 -- MqttConnectionHandlerBase::sendMessage - sending message ended >>>
I/flutter (18559): 2023-01-09 19:32:38.727776 -- MqttServerConnection::_onData - Message Received Started <<<
I/flutter (18559): 2023-01-09 19:32:38.730001 -- MqttServerConnection::_ondata - adding incoming data, data length is 45, message stream length is 1, message stream position is 0
I/flutter (18559): 2023-01-09 19:32:38.730910 -- Available bytes(46) is less than the message size 52
I/flutter (18559): 2023-01-09 19:32:38.732243 -- MqttServerConnection::_onData - Message Received Ended <<<

Duplicate add of user properties on invocation of addUserProperty from stream-created auth message

Hello,

First, great projects and thank you for all the work you do. It's much appreciated.

I think perhaps this assignment of _userProperties was intended to be with a copy of _propertySet.userProperties? (BTW, can this assignment be moved out of the for loop?)

_userProperty = _propertySet.userProperties;

Otherwise, it looks like it will add the property twice when called from here -- but only if creating the message from a byte buffer

_variableHeader!.userProperty = [property];

The following is a test showing the issue

Future<int> main() async {
  final user1 = MqttUserProperty();
  user1.pairName = 'User 1 name';
  user1.pairValue = 'User 1 value';
  final user2 = MqttUserProperty();
  user2.pairName = 'User 2 name';
  user2.pairValue = 'User 2 value';

  final message = MqttAuthenticateMessage()
      .withReasonCode(MqttAuthenticateReasonCode.success)
      .withAuthenticationMethod('method')
      .withAuthenticationData(typed.Uint8Buffer()..addAll([1, 2, 3, 4]))
      .withUserProperties([user1])
      .withReasonString('Reason String');

  final buffer = typed.Uint8Buffer();
  final stream = MqttByteBuffer(buffer);
  message.writeTo(stream);
  stream.reset();
  final outputHeader = MqttHeader.fromByteBuffer(stream);
  final message2 = MqttAuthenticateMessage.fromByteBuffer(outputHeader, stream);

  print(message.userProperties.length);  // 1
  print(message2.userProperties.length); // 1

  message.addUserProperty(user2);
  message2.addUserProperty(user2);

  print(message.userProperties.length);  // 2
  print(message2.userProperties.length); // 3 <should be 2>

  return 0;
}

path and meta requirements not compatible with Flutter stable

hi @shamblett, in your latest version update we noticed that you require

path: '^1.8.3'
meta: '^1.9.0'

But the latest version of Flutter 3.7.4 stable. Is running with path 1.8.2. And meta 1.8.0

I've looked into the changes of path and the only change here was

Support up to 16 arguments in join function and up to 15 arguments in absolute function.

This seems not like something required for this package.

For the meta package 1.9.0:

Introduce @reopen to annotate class or mixin declarations that can safely extend classes marked base, final or interface. Introduce @MustBeOverridden to annotate class or mixin members which must be overridden in all subclasses. Deprecate @alwaysThrows, which can be replaced by using a return type of 'Never'.

I don't think these changes are critical for the package.

Could you make an update that lowers the path version back 1.8.2 and meta to 1.8.0 so developers that run Flutter stable can also use the library. we are now forced to use a override in our yaml file.

InvalidHeaderException

Hello. When connecting to a broker, such an error occurs randomly and the application refuses to work further, can you tell me why it could be or how to get around this problem so that the application does not freeze?

InvalidHeaderException: The header being processed contained an invalid size byte pattern. Message size must take a most 4 bytes, and the last byte must have bit 8 set to 0.

MqttHeader.readFrom (package:mqtt5_client/src/messages/mqtt_header.dart:89:7)
new MqttHeader.fromByteBuffer (package:mqtt5_client/src/messages/mqtt_header.dart:19:5)
MqttByteBuffer.isMessageAvailable (package:mqtt5_client/src/utility/mqtt_byte_buffer.dart:66:29)
MqttServerConnection._onData (package:mqtt5_client/src/connectionhandling/server/mqtt_server_connection.dart:60:26)
_rootRunUnary (dart:async/zone.dart:1399:47)
_CustomZone.runUnary (dart:async/zone.dart:1300:19)
_CustomZone.runUnaryGuarded (dart:async/zone.dart:1209:7)
_BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)

Browser WS Connection: auto reconnect is not handling null values

In the browser ws connection, the auto-reconnect function is not handling null values.

If the onOpen function of the Browser WS Connection Websocket receives the correct data the completer finishes with a null value. This threw an error as the return function was non-nullable.

In the Server WS Connection, this is handled correctly.
Pull request is open: #18

Exceeding password and username

Hello, im trying to connect to EMQX using JWT.

MQTT explorer app logs in no problem with tls on username email and password JWT

Authenticating with username '{email}' and password '{JWT}'
MqttClient::checkCredentials - Username length (23) exceeds the max recommended in the MQTT spec.
-- MqttClient::checkCredentials - Password length (1837) exceeds the max recommended in the MQTT spec.
-- MqttConnectionHandlerBase::connect - server mqtt://mqtt.mydomain.com, port 8883
-- MqttSynchronousServerConnectionHandler::internalConnect entered
-- MqttSynchronousServerConnectionHandler::internalConnect - initiating connection try 0, auto reconnect in progress false
-- MqttSynchronousServerConnectionHandler::internalConnect - insecure TCP selected
-- MqttSynchronousServerConnectionHandler::internalConnect - calling connect
-- MqttNormalConnection::connect- entered
-- MqttConnectionBase::_onError - calling disconnected callback
ERROR: SocketException: Connection refused (OS Error: Connection refused, errno = 61), address = mqtt://mqtt.mydomain.com, port = 56837

How to deal with this?

Could not make the mqtt5_client connect to a EMQX server with WS

I was only experimenting with this for fun (Ex IT developer who became a manager now retired and keeping my brain active with dart)

I tried initially to connect to a free EMQX cloud instance but no joy so I downloaded Mosquitto onto my PC and this worked. So now I downloaded EMQX and ran on my PC and again no Joy.

Just messing around and looking at the other language examples I modified the connection string to add /mqtt at the end i.e. 'ws://RJMC-Work/' becomes 'ws://RJMC-Work/mqtt' and bang this works.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.