package im.zksy.yjmqserver.system.mqtt;

import im.zksy.yjmqserver.common.util.CommonUtil;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyMqttRecieveMessage {
    private static int QoS = 2;
    private static MemoryPersistence memoryPersistence = null;
    private static MqttConnectOptions mqttConnectOptions = null;//配置参数信息
    private static MqttClient mqttClient  = null;
    private static  String host="tcp://39.99.206.175:1883";
    private static  String clientId="";
    private static  String topic="video/edge/topic";
    private static Logger logger = LoggerFactory.getLogger(MyMqttRecieveMessage.class);

    public static void init() {
        System.out.println("第一步");
        mqttConnectOptions = new MqttConnectOptions();
        memoryPersistence = new MemoryPersistence();
//        String clientId=obj.getString("clientId");
//        String Host = obj.getString("host");
//        System.out.println("clientId==>"+clientId);
        clientId= CommonUtil.getUUID();
        System.out.println("clientId:"+clientId);
        if(null != memoryPersistence && null != clientId && null != host) {
            try {
                mqttClient = new MqttClient(host, clientId, memoryPersistence);
            } catch (MqttException e) {
                // TODO Auto-generated catch block
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }else {
            logger.error("memoryPersistence clientId Host 有空值");
        }
        System.out.println("第二步");
        if(null != mqttConnectOptions) {
            mqttConnectOptions.setCleanSession(true);
            mqttConnectOptions.setConnectionTimeout(30);//设置超时时间
            mqttConnectOptions.setKeepAliveInterval(45);//设置会话心跳时间，单位为秒
            mqttConnectOptions.setUserName("admin");//设置用户名
            mqttConnectOptions.setPassword("admin".toCharArray());//设置密码
            if(null != mqttClient && !mqttClient.isConnected()) {
                mqttClient.setCallback(new MqttRecieveCallback());//设置回调
                try {
                    mqttClient.connect(mqttConnectOptions);//连接
                    mqttClient.subscribe(topic);//订阅
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
            }else {
                logger.error("mqttClient is error");
            }
        }else {
            logger.error("mqttConnectOptions is null");
        }
        System.out.println("第三步");
    }
}
