Unable to connect to localhost using mqtt_client

2.3k views Asked by At

I have a local mosquito broker. an app on a phone( not an emulator). I am trying to connect to the local broker with no success via WebSockets.

I found some examples in the documentation but when I change URL and switch to WebSockets then I am unable to connect.

A hand is appreciated.

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

final client = MqttServerClient('ws://192.168.137.231', '');

Future<int> main() async {
  /// Set logging on if needed, defaults to off
  client.logging(on: false);
  client.keepAlivePeriod = 20;
  client.port = 8080;
  client.useWebSocket = true;
  client.onDisconnected = onDisconnected;
  client.onConnected = onConnected;
  client.onSubscribed = onSubscribed;

  client.pongCallback = pong;
  final connMess = MqttConnectMessage()
      .withClientIdentifier('client_id')
      .keepAliveFor(60) // Must agree with the keep alive set above or not set
      // .withWillTopic('/busline/201') // 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;

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

  /// Check we are connected
  if (client.connectionStatus.state == MqttConnectionState.connected) {
    print('EXAMPLE::Mosquitto client connected');
  } else {
    /// Use status here rather than state if you also want the broker return code.
    print(
        'EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, status is ${client.connectionStatus}');
    client.disconnect();
    return -1;
  }

  /// Ok, lets try a subscription
  print('EXAMPLE::Subscribing to the test/lol topic');
  const topic = '/busline/201'; // Not a wildcard topic
  client.subscribe(topic, MqttQos.atMostOnce);

  client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
    final MqttPublishMessage recMess = c[0].payload;
    final pt =
    MqttPublishPayload.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}');
  });

}

What I am doing wrong here

the error I get back

I/flutter ( 5031): EXAMPLE::Mosquitto client connecting...
I/flutter ( 5031): EXAMPLE::OnDisconnected client callback - Client disconnection
I/flutter ( 5031): EXAMPLE::client exception - SocketException: OS Error: Connection refused, errno = 111, address = 192.168.43.56, port = 49839
I/flutter ( 5031): EXAMPLE::OnDisconnected client callback - Client disconnection
I/flutter ( 5031): EXAMPLE::OnDisconnected callback is solicited, this is correct
I/flutter ( 5031): EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, status is Connection status is disconnected with return code of noneSpecified and a disconnection origin of solicited
I/flutter ( 5031): EXAMPLE::OnDisconnected client callback - Client disconnection
I/flutter ( 5031): EXAMPLE::OnDisconnected callback is solicited, this is correct

1

There are 1 answers

0
MaxC On

I bet it is because you have not specified a client name and a protocol prefix ws:// in the line

final client = MqttServerClient('ws://192.168.137.231', '');

Try it instead with

final client = MqttServerClient('192.168.137.231', 'client01');

I think that is what the part of the error message with return code of noneSpecified is supposed to tell you.