package com.muyu.parse.configure;

import com.muyu.parse.process.ProcessData;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @version 1.0
 * @Author xie ya ru
 * @Date 2024/9/26 15:31
 * @注释  MQTT监听者
 */


@Component
@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MqttConsumerConfig {

    String topic        = "yyy";
    String content      = "Message from MqttPublishSample";
    int qos             = 2;
    String broker       = "tcp://123.57.152.124:1883";
    String clientId     = "xyr123456789";

    @Resource
    private ProcessData processData;

    @PostConstruct
    public void connect() {
        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, new MemoryPersistence());
            MqttConnectOptions connOpts = new MqttConnectOptions();
            //是否清空session
            connOpts.setCleanSession(false);
            System.out.println("Connecting to broker: " + broker);
            //连接
            sampleClient.connect(connOpts);
            sampleClient.subscribe(topic, qos);
            sampleClient.setCallback(new MqttCallback() {
                //连接丢失(报错)
                @Override
                public void connectionLost(Throwable throwable) {
                    log.error("error:{}", throwable.getMessage(), throwable);
                }

                //消息已经接收到
                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    String s1 = new String(mqttMessage.getPayload());
                    System.out.println("接收到的主题是:" + s + "内容是:{}" + s1);
                    processData.DataConversion(s1);

                }

                //交付完成
                @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();
        }


    }
}
