using flutter read data from azure iot hub

119 Views Asked by At

Currently working on interfacing flutter and azure iot hub to read data and display in flutter widget. I used the following code

//handler part

class MqttHandler with ChangeNotifier {
  final ValueNotifier<String> data = ValueNotifier<String>("");
  late MqttBrowserClient client;

  Future<Object> connect() async {
    client = MqttBrowserClient(
        'ws://iothub.azure-devices.net', '');
    client.port = 443;
    client.logging(on: true);
    client.onConnected = onConnected;
    client.onDisconnected = onDisconnected;
    client.onUnsubscribed = onUnsubscribed;
    client.onSubscribed = onSubscribed;
    client.onSubscribeFail = onSubscribeFail;
    client.pongCallback = pong;
    client.keepAlivePeriod = 60;
    client.logging(on: true);
    client.websocketProtocols = ['mqtts'];
  

    /// Set the correct MQTT protocol for mosquito
    client.setProtocolV311();
    
    final MqttConnectMessage connectMessage = MqttConnectMessage()
      .authenticateAs('iothub.azure-devices.net/DEVICE01', 'SharedAccessSignature')
      .withClientIdentifier('DEVICE01')
      .keepAliveFor(60)
      .startClean();

    client.connectionMessage = connectMessage;
    try {
      await client.connect();
    } catch (e) {
      print('Exception: $e');
      client.disconnect();
    }

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

    print('MQTT_LOGS::Subscribing to the test/lol topic');
    const topic = 'devices/EZTRDEVICE01/messages/events/';
    client.subscribe(topic, MqttQos.atMostOnce);

    client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
      final recMess = c![0].payload as MqttPublishMessage;
      final pt =
          MqttPublishPayload.bytesToStringAsString(recMess.payload.message);

      data.value = pt;
      notifyListeners();
      print(
          'MQTT_LOGS:: New data arrived: topic is <${c[0].topic}>, payload is $pt');
      print('');
    });

    return client;
  }

  void onConnected() {
    print('MQTT_LOGS:: Connected');
  }

  void onDisconnected() {
    print('MQTT_LOGS:: Disconnected');
  }

  void onSubscribed(String topic) {
    print('MQTT_LOGS:: Subscribed topic: $topic');
  }

  void onSubscribeFail(String topic) {
    print('MQTT_LOGS:: Failed to subscribe $topic');
  }

  void onUnsubscribed(String? topic) {
    print('MQTT_LOGS:: Unsubscribed topic: $topic');
  }

  void pong() {
    print('MQTT_LOGS:: Ping response client callback invoked');
  }

  void publishMessage(String message) {
    const pubTopic = 'test/sample';
    final builder = MqttClientPayloadBuilder();
    builder.addString(message);

    if (client.connectionStatus?.state == MqttConnectionState.connected) {
      client.publishMessage(pubTopic, MqttQos.atMostOnce, builder.payload!);
    }
  }
}

but the error I'm getting is

-2024-02-02 17:42:43.068 -- SynchronousMqttBrowserConnectionHandler::internalConnect - pre sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none 1-2024-02-02 17:42:48.121 -- SynchronousMqttBrowserConnectionHandler::internalConnect - post sleep, state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none 1-2024-02-02 17:42:48.122 -- SynchronousMqttBrowserConnectionHandler::internalConnect failed 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? 1-2024-02-02 17:42:48.124 -- MqttConnectionHandlerBase::disconnect - entered 1-2024-02-02 17:42:48.124 -- MqttConnectionHandlerBase::_performConnectionDisconnect entered 1-2024-02-02 17:42:48.125 -- MqttConnectionKeepAlive::stop - stopping keep alive MQTT_LOGS:: Disconnected MQTT_LOGS::ERROR Azure client connection failed - disconnecting, status is Connection status is disconnected with return code of noneSpecified and a disconnection origin of solicited MQTT_LOGS:: Disconnected

I used mqtt_browser_client.dart because running this app in chrome. I changed port to 443 same response received. What would be the problem?

1

There are 1 best solutions below

0
Sampath On

The error you're encountering is related to the connection to the Azure IoT Hub using MQTT. The error message indicates that the maximum allowed connection attempts were exceeded, and the broker is not responding to the connection request message. It occurs due to invalid MQTT details. The code below demonstrates how to connect to MQTT.

enter image description here


// MQTT client configurations
  const String mqttServer = 'broker-cn.emqx.io'; // MQTT server address
  const int mqttPort = 8883; // MQTT port for secure connection
  const String username = 'sampath'; // Username of MQTT
  const String password = 'Ra@80muravi'; // Password of MQTT

  // Initialize MQTT client
  final client = MqttServerClient(mqttServer, '');

  // Set MQTT client options
  client.port = mqttPort;
  client.secure = true;
  client.logging(on: false);

  // Set up connection message
  final connMess = MqttConnectMessage()
      .withClientIdentifier(deviceId)
      .startClean() // Start with a clean session
      .withWillTopic('willtopic')
      .withWillMessage('willmessage')
      .withWillQos(MqttQos.atLeastOnce);
  client.connectionMessage = connMess;

  // Connect to the MQTT server
  try {
    await client.connect(username, password);
    print('MQTT client connected to Azure IoT Hub');

    // Publish a message
    final builder = MqttClientPayloadBuilder();
    builder.addString('Hello from Dart!');
    client.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
    print('Message published to topic: $topic');

    // Subscribe to the topic to receive messages (optional)
    client.subscribe(topic, MqttQos.atLeastOnce);
    client.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final recMess = c[0].payload as MqttPublishMessage;
      final pt =
          MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
      print('Received message: $pt');
    });
  } on Exception catch (e) {
    print('MQTT client exception - $e');
    client.disconnect();
    exit(-1);
  }

  // Wait for a while before disconnecting
  await Future.delayed(Duration(seconds: 10));

  // Disconnect from the MQTT server
  client.disconnect();
  print('MQTT client disconnected from Azure IoT Hub');

  return 0;
}

Output: enter image description here