package cn.iocoder.yudao.module.product.emqx;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class DeviceMqttService {
    private final MqttProperties mqttProperties;
    private DeviceMqttClient deviceMqttClient;

    public DeviceMqttService(MqttProperties mqttProperties) {
        this.mqttProperties = mqttProperties;
    }

    /**
     * 定时器检查连接是否有效(断线会自动重连不需要定时器)
     */
    public void checkAndAutoConnectMqttServer(){
        if(mqttProperties.getIsOpen()) {
            boolean isConnected = this.deviceMqttClient().isConnected();
            log.info("检查MQTT服务连接状态：isConnected={}", isConnected);
            if (!isConnected) {
                try {
                    this.deviceMqttClient().connect();
                } catch (Exception ex) {
                    log.error("检查并自动连接MQTT服务时出错， error={}", ex.getMessage());
                }
            }
        } else {
            log.info("**********************根据配置，mqtt将不随服务启动*************************");
        }
    }

    public void sendMessage(String receiver, String msg) throws Exception {
        deviceMqttClient().sendMessage(receiver, msg);
    }

    public void sendMessage(String receiver, byte[] msg) throws Exception {
        deviceMqttClient().sendMessage(receiver, msg);
    }

    private DeviceMqttClient deviceMqttClient() {
        if (deviceMqttClient == null) {
            deviceMqttClient = createDeviceMqttClient();
        }
        return deviceMqttClient;
    }

    private DeviceMqttClient createDeviceMqttClient() {
        try {
            return new DeviceMqttClient(mqttProperties);
        } catch (Exception ex) {
            throw new RuntimeException("初始化deviceMqttClient失败， " + ex.getMessage(), ex);
        }
    }

}
