package com.template.service.impl;

import com.template.service.MqttService;
import lombok.extern.log4j.Log4j2;
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.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author：liuxinyue
 * @Package：com.template.service.impl
 * @Project：cloud-server
 * @name：MqttServiceImpl
 * @Date：2024/9/26 15:58
 */
@Log4j2
@Service
public class MqttServiceImpl implements MqttService{

    String topic = "vehicle";
    String content = "Message from MqttPublishSample";
    int qos = 2;
    String broker = "tcp://47.101.53.251:1883";
    String clientId = "javaLxy";

    @Override
    public void connectionMqtt(String message) throws MqttException {

        MqttClient mqttClient = new MqttClient(broker, clientId);
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        //清理缓存
        connectOptions.setCleanSession(true);
        //连接
        mqttClient.connect(connectOptions);

        MqttMessage mqttMessage = new MqttMessage(message.getBytes());

        mqttMessage.setQos(qos);

        mqttClient.publish(topic, mqttMessage);

        log.info("发送成功");


    }
}
