package com.ltgk.video.common;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

/**
 * @Author: zhouyaoyao
 * @Date 2025/3/28 17:26
 * Description: mqtt 服务端配置
 */
@Component
public class MQTTServerConfig {

    String broker = "tcp://inner.qdlimap.cn:16890";
    String topic = "thing/product/7CTXMC200B04XG/osd";
    String username = "admin";
    String password = "Litugaoke01!";
    String clientId = System.currentTimeMillis() + "";
    int qos = 1;

    public void readSubscribeTopicMessage(){
        try {
            MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());

            // 连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            //是否清除会话
            options.setCleanSession(true);
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            client.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable throwable) {
                    System.out.println("连接丢失");
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
//                    System.out.println("topic为: " + topic);
//                    System.out.println("qos为: " + mqttMessage.getQos());
//                    System.out.println("消息内容为: " + new String(mqttMessage.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    // 当消息被完全传送出去后调用
                    System.out.println("交付完成 ---Delivery complete!");
                    // 可以在这里处理一些发送完成后的清理工作
                }
            });

            client.connect(options);
            client.subscribe(topic, qos);
        } catch (MqttException e){
            System.out.println("MqttMsgSubscriber 连接启动异常："+e.getMessage());
        } catch (Exception e){
            System.out.println("MqttMsgSubscriber 读取消息异常："+e.getMessage());
        }
    }

//    @PostConstruct
    public void initd() {
        new Thread(() -> {
            MQTTServerConfig config = new MQTTServerConfig();
            config.readSubscribeTopicMessage();
        }).start();
    }

}
