簡體   English   中英

我無法連接到 flutter 中的 mqtt?

[英]I'm having trouble connecting to mqtt in flutter?

我無法連接到 flutter 中的 mqtt。我無法連接。 我使用的代碼如下。

import 'package:mqtt_client/mqtt_server_client.dart';

late MqttServerClient client;

// ignore: camel_case_types
class mqttconnect {
  Future<MqttServerClient> connect() async {
    try {
      client =
          MqttServerClient.withPort('broker.emqx.io', 'flutter_client', 1883);
      client.logging(on: true);
      client.onConnected = onConnected;
      client.onDisconnected = onDisconnected;
    } catch (e) {
      print(e.toString());
    }

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

    return client;
  }

  void onConnected() {
    print('object');
  }

  void onDisconnected() {}
}

在此處輸入圖像描述

在嘗試連接到 mqtt 時,我在控制台中收到如上所示的錯誤。 我該如何解決。

import 'dart:convert';
import 'dart:developer';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

late MqttServerClient client;

mqttSubscribe() async {
  client = MqttServerClient.withPort("broker.emqx.io", "daly", 1883);
  client.keepAlivePeriod = 30;
  client.autoReconnect = true;
  await client.connect().onError((error, stackTrace) {
    log("error -> " + error.toString());
  });

  client.onConnected = () {
    log('MQTT connected');
  };

  client.onDisconnected = () {
    log('MQTT disconnected');
  };

  client.onSubscribed = (String topic) {
    log('MQTT subscribed to $topic');
  };

  if (client.connectionStatus!.state == MqttConnectionState.connected) {
    client.subscribe("battery", MqttQos.atMostOnce);

    client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
      final recMess = c![0].payload as MqttPublishMessage;
      final pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
      log("message payload => " + pt);
    });
  }
}
import 'dart:async';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';



class MqttService{
   MqttService._();


  /// Our mqtt client object.
  static late MqttClient client;
  
  // for listen from other pages.
  // and can close listen mqtt.
  static StreamSubscription? mqttListen; 


  static void initMqtt(){
     
    /// Initialize Mqtt and connect.
    client = MqttServerClient(/* Your mqtt host address */)
        ..logging(on: false)
        ..port = MqttConstants.mqttPort
        ..keepAlivePeriod = 20
        ..onDisconnected = _onDisconnected
        ..onSubscribed = _onSubscribed
        ..onConnected = _onConnected
        ..onUnsubscribed = _onUnsubscribed
        ..onSubscribeFail = _onSubscribeFail;

     /// If the mqtt connection lost
     /// MqttBroker publish this message on this topic.
     final mqttMsg = MqttConnectMessage()
        .withWillMessage('connection-failed')
        .withWillTopic('willTopic')
        .startClean()
        .withWillQos(MqttQos.atLeastOnce)
        .withWillTopic('failed');
    client.connectionMessage = mqttMsg;
    await _connectMqtt();
  }


   /// Mqtt server connected.
  void _onConnected() {
    log('Connected');
    _listenMqtt();
  }

  /// Mqtt server disconnected
  void _onDisconnected() {
    log('Disconnected');
  }

  /// Mqtt server subscribed
  void _onSubscribed(String? topic) {
    log('Subscribed topic is : $topic');
  }

  void _onUnsubscribed(String? topic) {
    log('Unsubscribed topic is : $topic');
  }

  void _onSubscribeFail(String? topic) {
    log('Failed subscribe topic : $topic');
  }


  /// Connection MQTT Server.
  Future<void> _connectMqtt() async {
    if (client.connectionStatus!.state != MqttConnectionState.connected) {
      try {
        await client.connect();
      } catch (e) {
        log('Connection failed' + e.toString());
      }
    } else {
      log('MQTT Server already connected ');
    }
  }

  /// Diconnection MQTT Server.
  static Future<void> disconnectMqtt() async {
    if (client.connectionStatus!.state == MqttConnectionState.connected) {
      try {
        client.disconnect();
      } catch (e) {
        log('Disconnection Failed ' + e.toString());
      }
    } else {
      log('MQTT Server already disconnected ');
    }
  }
  

  /// Subscribe a topic
  static void subscribeTopic(String topic) {
    final state = client.connectionStatus?.state;
    if (state != null) {
      if (state == MqttConnectionState.connected) {
        client.subscribe(topic + "/data", MqttQos.atLeastOnce);
      }
    }
  }

  /// Publish a message to topic 
  /// [reatain] means last message save the broker.
  static void publish(String topic, String message, {bool retain = true}) {
    final builder = MqttClientPayloadBuilder();
    builder.addString(message);
    client.publishMessage(
      topic,
      MqttQos.atLeastOnce,
      builder.payload!,
      retain: retain,
    );
    builder.clear();
  }


  static void unSubscribeTopic(String topic) {
    final state = client.connectionStatus?.state;
    if (state != null) {
      if (state == MqttConnectionState.connected) {
        client.unsubscribe(topic + "/data");
      }
    }
  }

 
  static void onClose(){
    mqttListen?.close();
    disconnectMqtt();
  }

  void _listenMqtt() {
    mqttListen = client.updates!.listen((dynamic t) {
      MqttPublishMessage recMessage = t[0].payload;
      final message =
          MqttPublishPayload.bytesToStringAsString(recMessage.payload.message);
      /*
        Listen subscribe topic.
      */
      log(message);
    });
  }


}

我為MQTT創建了一個很好的格式,我想通過這個問題與您分享。

Package: mqtt_client

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM