shamblett / mqtt_client

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

How to process messages indefinitely? #445

Closed CordMemescape closed 1 year ago

CordMemescape commented 1 year ago

Thanks for a really great MQTT package. I've been using it for a couple of months now and am happily publishing messages to Mosquitto (from Flutter) and processing the messages in a Dart app.

One problem I have not yet solved is making my Dart application persistent. I need to run it as a server to process messages from Mosquitto and pass them through to my backend. All of the examples provided show Dart apps that start up, connect to an MQTT broker, subscribe to a topic, maybe publish a message or two and then terminate after a few seconds.

How do I expand one of the example Dart apps to continue listening for and processing messages indefinitely?

shamblett commented 1 year ago

The examples are written to terminate normally, to stop this just remove the code from the asyncSleep downwards to the return, the client will then listen indefinitely, you can see this in the ping responses, i.e. from the mqtt_server_client example remove -

print('EXAMPLE::Sleeping....');
  await MqttUtilities.asyncSleep(60);

  /// Finally, unsubscribe and exit gracefully
  print('EXAMPLE::Unsubscribing');
  client.unsubscribe(topic);

  /// Wait for the unsubscribe message from the broker if you wish.
  await MqttUtilities.asyncSleep(2);
  print('EXAMPLE::Disconnecting');
  client.disconnect();
  print('EXAMPLE::Exiting normally');

you should be good to go. Note you can also set the asyncSleep value to an extremely large value if you want a forced exit after a certain amount of time.

CordMemescape commented 1 year ago

Thank you for your prompt reply Steve, much appreciated!

You are absolutely spot on. I incorrectly assumed that Dart would run to the end and terminate automatically after the last line of code. However, thanks to your comment, I can see that the call to exit() has to be explicit for it to terminate. I can remove all the unnecessary loops and asyncSleep() now and leave it to run in the background.

All that's left now is to figure out why my callbacks aren't being called. That's a separate thing though.