package com.imdroid.beidou_fwd.service;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MQTTClient {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private MqttClient client;
    private String brokerUrl;
    private String username;
    private String password;
    private String clientid;
    private String topic;
    int qos = 1;//0、1、2

    public MQTTClient(String brokerUrl, String username, String password,
                      String clientid, String topic){
        this.brokerUrl = brokerUrl;
        this.username = username;
        this.password = password;
        this.clientid = clientid;
        this.topic = topic;
    }

    public void connect() throws MqttException {
        // Create a new MQTT client.
        client = new MqttClient(brokerUrl, clientid, new MemoryPersistence());
        // Create a new MQTT connection options object.
        MqttConnectOptions options = new MqttConnectOptions();
        // Set the MQTT connection options.
        options.setCleanSession(true);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setAutomaticReconnect(true);
        //options.setKeepAliveInterval();default:30s
        // Connect to the MQTT broker.
        client.connect(options);
    }

    public boolean publish(String message) throws MqttException {
        if(!client.isConnected()){
            logger.info("mqtt disconnected");
            return false;
        }
        try { // Create a new MQTT message.
            MqttMessage mqttMessage = new MqttMessage(message.getBytes());
            mqttMessage.setQos(qos);
            // Publish the MQTT message to the topic.
            client.publish(topic, mqttMessage);
        } catch (Exception e) {
            logger.error("mqtt推送gnss数据异常:", e);
            return false;
        }
        return true;
    }

    public void disconnect() throws MqttException {
        // Disconnect from the MQTT broker.
        client.disconnect();
    }

}
