Search code examples
fluttermqtt

Flutter MQTT - Publish to topic1 and Listen to topic2


I have a Flutter application publishing to 'topic1' and currently listening to 'topic1'.

   MQTTManager(
        {required String host,
        required String topic,
        required String identifier,
        required MQTTAppState state})
        :
          _identifier = 'id',
          _host = '48.38.96.88',
          _topic = 'topic1',
          _currentState = state;

I want to publish to 'topic1' and then listener to a reply on 'topic2'

Is this possible with mqtt_client?

 void onConnected() {
      _currentState.setAppConnectionState(MQTTAppConnectionState.connected);
      print('EXAMPLE::Mosquitto client connected....');
      _client!.subscribe(_topic, MqttQos.atLeastOnce);
      _client!.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
        // ignore: avoid_as
        final MqttPublishMessage recMess = c![0].payload as MqttPublishMessage;

        // final MqttPublishMessage recMess = c![0].payload;
        final String pt =
            MqttPublishPayload.bytesToStringAsString(recMess.payload.message!);
        _currentState.setReceivedText(pt);
        print(
            'EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');
        print('');
      });
      print(
          'EXAMPLE::OnConnected client callback - Client connection was sucessful');
    }
  }


Solution

  • The publish string

        void publish(String message) {
          final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
          builder.addString(message);
          _client!.publishMessage(_topic1, MqttQos.exactlyOnce, builder.payload!);
        }
    

    The subscribe string

    _client!.subscribe(_topic2, MqttQos.atLeastOnce);
    

    You can see the two different topics.

      import 'package:mqtt_client/mqtt_client.dart';
      import 'package:flutter_mqtt/mqtt/state/mqtt_app_state.dart';
      import 'package:mqtt_client/mqtt_server_client.dart';
    
      class MQTTManager {
        // Private instance of client
        final MQTTAppState _currentState;
        MqttServerClient? _client;
        final String _identifier;
        final String _host;
        final String _topic1;
        final String _topic2;
    
        // Constructor
        // ignore: sort_constructors_first
        MQTTManager(
            {required String host,
            required String topic,
            required String identifier,
            required MQTTAppState state})
            : //_identifier = identifier,
              _identifier = 'id',
              //_host = host,
              _host = '48.38.96.88',
              //_topic = topic,
              _topic1 = 'topic1',
              _topic2 = 'topic2',
              _currentState = state;
    
        void initializeMQTTClient() {
          _client = MqttServerClient(_host, _identifier);
          //_client = MqttServerClient('48.38.96.88', 'Where');
          _client!.port = 1883;
          _client!.keepAlivePeriod = 20;
          _client!.onDisconnected = onDisconnected;
          _client!.secure = false;
          _client!.logging(on: true);
    
          /// Add the successful connection callback
          _client!.onConnected = onConnected;
          _client!.onSubscribed = onSubscribed;
    
          final MqttConnectMessage connMess = MqttConnectMessage()
              .withClientIdentifier(_identifier)
              .withWillTopic(
                  'willtopic') // If you set this you must set a will message
              .withWillMessage('My Will message')
              .startClean() // Non persistent session for testing
              .withWillQos(MqttQos.atLeastOnce);
          print('EXAMPLE::Mosquitto client connecting....');
          _client!.connectionMessage = connMess;
        }
    
        // Connect to the host
        // ignore: avoid_void_async
        void connect() async {
          assert(_client != null);
          try {
            print('EXAMPLE::Mosquitto start client connecting....');
            _currentState.setAppConnectionState(MQTTAppConnectionState.connecting);
            await _client!.connect();
          } on Exception catch (e) {
            print('EXAMPLE::client exception - $e');
            disconnect();
          }
        }
    
        void disconnect() {
          print('Disconnected');
          _client!.disconnect();
        }
    
        void publish(String message) {
          final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
          builder.addString(message);
          _client!.publishMessage(_topic1, MqttQos.exactlyOnce, builder.payload!);
        }
    
        /// The subscribed callback
        void onSubscribed(String topic) {
          print('EXAMPLE::Subscription confirmed for topic $topic');
        }
    
        /// The unsolicited disconnect callback
        void onDisconnected() {
          print('EXAMPLE::OnDisconnected client callback - Client disconnection');
          if (_client!.connectionStatus!.returnCode ==
              MqttConnectReturnCode.noneSpecified) {
            print('EXAMPLE::OnDisconnected callback is solicited, this is correct');
          }
          _currentState.setAppConnectionState(MQTTAppConnectionState.disconnected);
        }
    
        /// The successful connect callback
        void onConnected() {
          _currentState.setAppConnectionState(MQTTAppConnectionState.connected);
          print('EXAMPLE::Mosquitto client connected....');
          _client!.subscribe(_topic2, MqttQos.atLeastOnce);
          _client!.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
            // ignore: avoid_as
            final MqttPublishMessage recMess = c![0].payload as MqttPublishMessage;
    
            // final MqttPublishMessage recMess = c![0].payload;
            final String pt =
                MqttPublishPayload.bytesToStringAsString(recMess.payload.message!);
            _currentState.setReceivedText(pt);
            print(
                'EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');
            print('');
          });
          print(
              'EXAMPLE::OnConnected client callback - Client connection was sucessful');
        }
      }