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


import cn.iocoder.yudao.module.product.framework.provider.ApplicationContextProvider;
import cn.iocoder.yudao.module.product.service.envdata.EnvDataService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;


@Slf4j
public class DeviceMqttCallback implements MqttCallback {

    private final DeviceMqttClient mqttClient;
    private final EnvDataService envDataService = ApplicationContextProvider.getBean(EnvDataService.class);

    public DeviceMqttCallback(DeviceMqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
//        log.info("MQTT连接断开，发起重连");
        while (true) {
            try {
                Thread.sleep(10000);
                mqttClient.connect();
//                log.info("MQTT重新连接成功。");
                break;
            } catch (Exception e) {
                log.error("连接MQTT服务器失败，{}", e.getMessage(), e);
            }
        }
    }

    /**
     * @param topic
     * @param message
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        EmqxStart.executorService.submit(() -> {
            try {
                String msg = new String(message.getPayload());
                log.info("接收到消息: msg = {}, topic = {}", msg, JSONObject.toJSONString(topic));
                envDataService.saveEnvDataByEmqx(topic, new String(message.getPayload()));
            } catch (Exception e) {
                e.printStackTrace();
                log.info("mqtt 数据解析异常");
                log.info("mqtt 异常=======》{} ",e.getLocalizedMessage());
            }
        });
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}
