package com.hwclouds.romalink;

import org.eclipse.paho.client.mqttv3.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DeviceConnectDemo
{
    public static void main(String[] args)
    {
        // 设备连接地址
        final String host = "";
        // 设备客户端ID
        final String clientId = "";
        // 设备认证的用户名
        final String userName = "";
        // 设备认证的密码
        final String password = "";
        // 设备Publish权限的Topic
        final String pubTopic = "";
        // 设备Subscribe权限的Topic
        final String subTopic = "";
        // 设备发送的消息内容
        final String payload = "hello world.";

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(userName);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setMqttVersion(3);

        try
        {
            final MqttClient client = new MqttClient(host, clientId);
            client.connect(mqttConnectOptions);
            System.out.println("Device connect success. client id is " + clientId + ", host is " + host);

            final MqttMessage message = new MqttMessage();
            message.setQos(1);
            message.setRetained(false);
            message.setPayload(payload.getBytes(StandardCharsets.UTF_8));

            Runnable pubTask = () -> {
                try
                {
                    client.publish(pubTopic, message);
                }
                catch (MqttException e)
                {
                    System.out.println(e.getMessage());
                }
            };

            client.subscribe(subTopic, (s, mqttMessage) -> {
                String recieveMsg = "Receive message from topic:" + s + "\n";
                System.out.println(recieveMsg + new String(mqttMessage.getPayload(), StandardCharsets.UTF_8));
            });

            ScheduledExecutorService service = Executors
                    .newSingleThreadScheduledExecutor();
            service.scheduleAtFixedRate(pubTask, 0, 10, TimeUnit.SECONDS);
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
