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

class MqttClient {

  Future<MqttServerClient> connect() async {
    MqttServerClient client =
        // MqttServerClient.withPort('emqtt.hdmedicine.naiterui.com', '180.76.145.155', 61630);
        MqttServerClient.withPort('broker.emqx.io', 'flutter_client', 1883);
    client.logging(on: true);
    client.onConnected = onConnected;
    client.onDisconnected = onDisconnected;
    client.onUnsubscribed = onUnsubscribed;
    client.onSubscribed = onSubscribed;
    client.onSubscribeFail = onSubscribeFail;
    client.pongCallback = pong;



    final connMessage = MqttConnectMessage()
        .authenticateAs('androiduser', 'Cf3Jf3tM06200G+Up0')
        .keepAliveFor(60)
        .withWillTopic('clientWillDead')
        .withWillMessage('{"i":"dr_133","c":0,"t":3}')
        .startClean()
        .withWillQos(MqttQos.atLeastOnce);
    client.connectionMessage = connMessage;
    try {
      await client.connect();
    } catch (e) {
      print('Exception: $e');
      client.disconnect();
    }

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

      print('收到消息  Received message:$payload from topic: ${c[0].topic}>');
      Fluttertoast.showToast(msg: "flutter  收到MQtt消息  $payload");
    });

    client.subscribe("topic/test", MqttQos.atLeastOnce);

    return client;
  }

  // 连接成功
  void onConnected() {
    print('连接 --- Connected');
  }

// 连接断开
  void onDisconnected() {
    print('连接 --- Disconnected');
  }

// 订阅主题成功
  void onSubscribed(String topic) {
    print('连接 --- Subscribed topic: $topic');
  }

// 订阅主题失败
  void onSubscribeFail(String topic) {
    print('连接 --- Failed to subscribe $topic');
  }

// 成功取消订阅
  void onUnsubscribed(String topic) {
    print('连接 --- Unsubscribed topic: $topic');
  }

// 收到 PING 响应
  void pong() {
    print('连接 --- Ping response client callback invoked');
  }

  MqttClient();
}
