package com.tuoheng.admin.mqtt.consumer;


import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.entity.third.LingXiuDataResponse;
import com.tuoheng.admin.mqtt.MqttProviderConfig;
import com.tuoheng.admin.service.airData.IAirDataService;
import com.tuoheng.common.core.utils.SpringUtils;
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 MqttConsumerCallBack implements MqttCallback {

    private IAirDataService airDataService = SpringUtils.getBean(com.tuoheng.admin.service.airData.IAirDataService.class);

    /**
     * 客户端断开连接的回调
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.info("与服务器断开连接，可重连, throwable={}", throwable);
        MqttProviderConfig client = SpringUtils.getBean(MqttProviderConfig.class);
        if (!client.isconnect()) {
            client.connect();
            System.out.println("重连成功！");
        }
    }

    /**
     * 消息到达的回调
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        log.info("接收灵嗅消息 : topic={}, message={}", topic, message);
        LingXiuDataResponse response = JSONObject.parseObject(message.getPayload(), LingXiuDataResponse.class);
        airDataService.syncData(response);
    }

    /**
     * 消息发布成功的回调
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }

}

