package com.ruoyi.framework.config.mqtt;

import com.ruoyi.framework.utils.SSLUtils;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

/**
 * MQTT 生产端
 * Create By Spring-2022/10/29
 */
@Configuration
public class MqttOutboundConfiguration {
    @Autowired
    private MqttConfiguration mqttProperties;

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

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

    /**
     * 建立MQTT连接，配置连接的参数选项
     *
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttOutClient() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        String[] mqttServerUrls = mqttProperties.getUrl().split(",");
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setServerURIs(mqttServerUrls);
        mqttConnectOptions.setUserName(mqttProperties.getUsername());
        mqttConnectOptions.setPassword(mqttProperties.getPassword().toCharArray());
        // 接收离线消息
        mqttConnectOptions.setCleanSession(false); //告诉代理客户端是否要建立持久会话   false为建立持久会话
        // 单向ssl/tls
//        try {
//            String caCrtFile = getClass().getResource("/emqxsl-ca.crt").getPath();
//            mqttConnectOptions.setSocketFactory(SSLUtils.getSingleSocketFactory(caCrtFile));
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        factory.setConnectionOptions(mqttConnectOptions);
        return factory;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannelIOT")
    public MessageHandler mqttOutboundIOT() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperties.getClientId() + "_outbound_iot",
                mqttOutClient());
        messageHandler.setDefaultTopic("iot/deviceId/+/sensorTag/+/#");  // 支持主题表达式
        messageHandler.setAsync(true);
        return messageHandler;
    }


}
