package com.yeejoin.equipmanage.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @author keyong
 * @title: EquipmentIotProduceConfig
 * <pre>
 * @description: MQTT订阅模式生产类
 * </pre>
 * @date 2020/10/30 14:13
 */
@Configuration
@IntegrationComponentScan
public class EquipmentIotMqttProduceConfig {


    @Value("${emqx.client-user-name}")
    private String userName;

    @Value("${emqx.client-password}")
    private String password;

    @Value("${emqx.broker}")
    private String hostUrl;
    
    @Value("${mqtt.client.product.id}")
    private String clientId;

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


    @Bean
    public MqttConnectOptions getMqttConnectOption(){
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(userName);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(10);
        mqttConnectOptions.setMaxInflight(1000);
        mqttConnectOptions.setAutomaticReconnect(true);
//        mqttConnectOptions.setConnectionTimeout(0);
        return mqttConnectOptions;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOption());
        return factory;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientId + "_outbound", mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(defaultTopic);
        return messageHandler;
    }

    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

}
