package com.ruoyi.system.core.mqtt;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 项目启动 监听主题
 */
@Component
public class MqttClientListener implements ApplicationListener<ContextRefreshedEvent> {

    private volatile AtomicBoolean isInit = new AtomicBoolean(false);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            if (!isInit.compareAndSet(false, true)) {
                return;
            }
//            deviceService.findByType("MQTT").flatMap(x -> {
//                MqttClientConnect mqttClientConnect = new MqttClientConnect();
//                mqttClientConnect.setMqttClientId(x.getDeviceNo());
//                String host = "tcp://" + x.getIp() + ":" + x.getPort();
//                try {
//                    mqttClientConnect.setMqttClient(host, x.getDeviceNo(), "admin", "admin", true, new MqttClientCallback(x.getDeviceNo()));
//                    MqttClientConnect.mqttClients.put(x.getDeviceNo(), mqttClientConnect);
//                    mqttClientConnect.sub(StringUtils.commaDelimitedListToStringArray(x.getTopic()));
//                    log.info("{}--连接成功！！订阅主题--{}", x.getDeviceNo(), x.getTopic());
//                    return Flux.just(x);
//                } catch (MqttException e) {
//                    return Flux.error(new RuntimeException(e));
//                }
//            }).subscribe();
        } catch (Exception e) {
        }
    }

}