package com.template.util;
import lombok.extern.log4j.Log4j2;
import org.eclipse.paho.client.mqttv3.*;
/**
 * @Author：liuxinyue
 * @Package：com.template.util
 * @Project：cloud-server
 * @name：Test
 * @Date：2024/9/27 11:55
 */
@Log4j2
public class Test {

    public static void main(String[] args) {
        String topic        = "vehicle";
        String content      = "Message from MqttPublishSample";
        int qos             = 2;
        String broker       = "tcp://47.101.53.251:1883";
        String clientId     = "Lxy";

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            //是否清空session
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: "+broker);
            //连接
            sampleClient.connect(connOpts);
            sampleClient.subscribe("vehicle",qos);
            sampleClient.setCallback(new MqttCallback() {

                //连接丢失(报错)
                @Override
                public void connectionLost(Throwable throwable) {
                  log.error("error:"+throwable.getMessage());
                }

                //消息已经接收到
                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    System.out.println(new String(mqttMessage.getPayload()));
                }

                //交付完成
                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
        } catch(MqttException me) {
            System.out.println("reason "+me.getReasonCode());
            System.out.println("msg "+me.getMessage());
            System.out.println("loc "+me.getLocalizedMessage());
            System.out.println("cause "+me.getCause());
            System.out.println("excep "+me);
            me.printStackTrace();
        }
    }
}
