MqttX.js
2.53 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
var mqttX = {
client:null,
mqttStatus:false,
options:{},
onConnect:function(){
mqttStatus = true;
if(options && options.success){
options.success();
}
},
onFailure:function(){
mqttStatus = false;
if(options && options.error){
options.error();
}
},
onConnectionLost:function(responseObject){
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
console.log("连接已断开");
mqttStatus = false;
if(options && options.connectLost){
options.connectLost(responseObject.errorMessage);
}
}
},
onMessageArrived:function(message){
//console.log(message);
if(options && options.onMessage){
options.onMessage(message);
}
},
sendMessage:function(topic,obj){
if(mqttStatus){
var message = new Paho.MQTT.Message(JSON.stringify(obj));
message.destinationName = topic;
if(mqttX.client && mqttStatus){
mqttX.client.send(message);
return true;
}
}
return false;
},
subscribe:function(topic,qos){
if(mqttX.client && mqttStatus){
mqttX.client.subscribe(topic,{qos:qos});
return true;
}
return false;
},
unsubscribe:function(topic){
if(mqttX.client && mqttStatus){
mqttX.client.unsubscribe(topic);//取消订阅主题
return true;
}
return false;
},
disconnect:function(){
if(mqttX.client && mqttStatus){
mqttX.client.disconnect();//取消订阅主题
return true;
}
return false;
},
reconnect:function(){
if(mqttX.client && options){
var useSSL = false;
if(options.useSSL){
useSSL = options.useSSL;
}
mqttX.client.connect({
onSuccess:this.onConnect,
onFailure: this.onFailure,
timeout: 10,
keepAliveInterval:100,
cleanSession:true,
useSSL:useSSL
});
return true;
}
return false;
},
isConnected:function(){
if(mqttX.client){
return mqttX.client.isConnected();
}
return false;
},
init:function(options1){
if(options1){
options = options1;
var useSSL = false;
if(options.useSSL){
useSSL = options.useSSL;
}
mqttX.client = new Paho.MQTT.Client(options.ip, Number(options.port), options.id);
mqttX.client.connect({
onSuccess:this.onConnect,
onFailure: this.onFailure,
timeout: 10,
keepAliveInterval:100,
cleanSession:true,
useSSL:useSSL
});
mqttX.client.onConnectionLost = this.onConnectionLost;//注册连接断开处理事件
mqttX.client.onMessageArrived = this.onMessageArrived;//注册消息接收处理事件
}
}
};