package cn.iocoder.yudao.module.iot.framework.mqtt.config;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
@EnableConfigurationProperties(DefaultEmqProperties.class)
public class DefaultMqttStarter implements ApplicationListener<ApplicationReadyEvent> {
    @Resource
    private MqttConnectOptions options;

    @Resource
    private MqttClient mqttClient;
    @Resource
    private DefaultEmqProperties defaultEmqProperties;

    @SneakyThrows
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        // catch异常，不然连不上emqx项目就跑不起来
        try {
            if(defaultEmqProperties.getIsEnable())
                mqttClient.connect(options);
        } catch (MqttException e) {
            e.getMessage();
            e.printStackTrace();
        }
    }
}
