package com.muyu.mqtt;

import lombok.AllArgsConstructor;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Service;

/**
 * mqtt配置 MqttFactory
 *
 * @author Yangle
 * Date 2024/6/6 15:10
 */
@Service
@AllArgsConstructor
public class MqttFactory {

    private final MessageCallbackService messageCallbackService;

    public MqttClient creatClient(MqttProperties mqttProperties) {
        MqttClient client =null;
        try {
            client = new MqttClient(mqttProperties.getBroker(), mqttProperties.getClientid(), new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();

            // 连接参数
            if (mqttProperties.isLong())
            {
                options.setUserName(mqttProperties.getUsername());
                options.setPassword(mqttProperties.getPassword().toCharArray());
            }
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            client.connect(options);
            client.setCallback(messageCallbackService);
            client.subscribe(mqttProperties.getTopic(),0);

        } catch (MqttException e) {
            throw new RuntimeException(e);
        }

        return client;
    }
}
