package com.usky.ai.service.mqtt;

import lombok.Data;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.stereotype.Component;

@ConditionalOnProperty(prefix = "mqtt", value = {"enabled"}, havingValue = "true")
@Data
@Component
@ConfigurationProperties(prefix = "mqtt")
public class MqttBaseConfig {

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.url}")
    private String hostUrl;

    @Value("${mqtt.sub-topics}")
    private String msgTopic;

    @Value("${mqtt.keep-alive-interval}")
    //心跳间隔
    private int keepAliveInterval;
    @Value("${mqtt.completionTimeout}")
    //心跳间隔
    private int completionTimeout;


    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{this.getHostUrl()});
        options.setUserName(this.getUsername());
        options.setPassword(this.getPassword().toCharArray());
        factory.setConnectionOptions(options);
        return factory;
    }

}