package com.muyu.server.config;

import cn.hutool.json.JSONObject;
import com.muyu.server.service.TemplateService;
import lombok.extern.log4j.Log4j2;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 *
 * @author liuxinyue
 * @Package：com.muyu.mqtt.configure
 * @Project：cloud-server
 * @name：MqttConfigure
 * @Date：2024/9/28 16:10
 */
@Log4j2
@Component
public class MqttConfigure {

    @Autowired
    private TemplateService templateService;


    @PostConstruct
    public void MQTTMonitoring(){
        String topic        = "vehicle";
        int qos             = 2;
        String broker       = "tcp://47.101.53.251:1883";
        String clientId     = "测试mqtt";
        try {
            MqttClient sampleClient = new MqttClient(broker, clientId);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            //是否清空session
            connOpts.setCleanSession(true);
            log.info("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());
                }
                //消息已经接收到
                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    // 将MQTT消息转换为字符串
                    String messageContent = new String(mqttMessage.getPayload());
                    // 解析JSON字符串
                    JSONObject jsonObject = new JSONObject(messageContent);
                    // 从JSON对象中获取"msg"字段的值
                    String msgValue = jsonObject.getStr("msg");
                    templateService.messageParsing(msgValue);
                    log.info("接收到的值为:"+msgValue);
                }
                //交付完成
                @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();
        }
    }
}
