JLChen
2020-09-24 e91af284643d5e370b0d18c384fe8de65f59d9b3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.hdl.sdk.hdl_core.HDLDeviceManger.Core;
 
import android.util.Log;
 
 
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 
import com.hdl.sdk.hdl_core.HDLDeviceManger.Callback.PushCallback;
import com.hdl.sdk.hdl_core.Util.LogUtil.HDLLog;
 
 
public class HDLZigbeeMqtt {
 
    private static final String clientid = "HDLZigbeeDriver";
    private static MqttClient client;
    private static boolean isCancel = false;
 
    public static void setIsCancel(boolean isCancel) {
        HDLZigbeeMqtt.isCancel = isCancel;
    }
 
 
    /**
     * 连接mqtt
     */
    public static void connect1(String host) {
        try {
            client = new MqttClient("tcp://" + host + ":1883", clientid, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(false);
            options.setUserName("admin");
            options.setPassword("password".toCharArray());
            //设置自动重连
            options.setAutomaticReconnect(true);
            // 设置超时时间
            options.setConnectionTimeout(10);
            // 设置会话心跳时间
            options.setKeepAliveInterval(20);
            PushCallback pushCallback = new PushCallback();
            pushCallback.setHost(host);
            client.setCallback(pushCallback);
            client.connect(options);
            if (isCancel) {
                client.close();
                isCancel = false;
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 发送mqtt信息
     */
    public static void sendMqttData1(String topic, String json) {
        HDLLog.info("send Mqtt to gateway:" + json);
        Log.d("111133", "sendMqttData1: " + json);
        try {
            MqttMessage message = new MqttMessage();
            message.setQos(2);
            message.setRetained(false);
            message.setPayload(json.getBytes());
            MqttDeliveryToken token = client.getTopic(topic).publish(message);
            token.waitForCompletion();
            Log.d("111133", "已经发送");
            HDLLog.info("message is published completely!");
        } catch (MqttException e) {
            Log.d("111133", "sendMqttData1: " + e.getMessage());
            HDLLog.info("发送mqtt信息出错");
            e.printStackTrace();
        }
    }
}