forked from arenaxr/arena-web-core
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mqtt-client.js
executable file
·146 lines (129 loc) · 5.2 KB
/
mqtt-client.js
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/**
* @fileoverview Paho mqtt client wrapper
*
*/
/* global Paho */
const nretries = 2;
/**
* Mqtt client wrapper class
*/
export default class MqttClient {
/**
* Create an mqtt client instance
* @param st an object with the client setting
*/
constructor(st) {
// handle default this.settings
st = st || {};
this.settings = {
uri: st.uri !== undefined ? st.uri : 'wss://arena.andrew.cmu.edu/mqtt/',
host: st.host !== undefined ? st.host : 'arena.andrew.cmu.edu',
port: st.port !== undefined ? st.port : 8083,
path: st.path !== undefined ? st.path : '/mqtt/',
clientid:
st.clientid !== undefined ? st.clientid : `this.mqttc-client-${Math.round(Math.random() * 10000)}`,
subscribeTopics: st.subscribeTopics,
onConnectCallback: st.onConnectCallback,
onConnectCallbackContext: st.onConnectCallbackContext,
onMessageCallback: st.onMessageCallback,
useSSL: st.useSSL !== undefined ? st.useSSL : true,
dbg: st.dbg !== undefined ? st.dbg : false,
mqtt_username: st.mqtt_username,
mqtt_token: st.mqtt_token,
};
// console.log(st.mqtt_username);
if (this.settings.dbg === true) console.log(this.settings);
}
async connect() {
if (this.settings.uri) {
if (this.settings.dbg === true) console.log('Connecting [uri]: ', this.settings.uri);
// init Paho client connection
this.mqttc = new Paho.Client(this.settings.uri, this.settings.clientid);
} else {
const wss = this.settings.useSSL === true ? 'wss://' : 'ws://';
console.log(
`Connecting [host,port,path]: ${wss}${this.settings.host}:${this.settings.port}${this.settings.path}`
);
// init Paho client connection
this.mqttc = new Paho.Client(
this.settings.host,
Number(this.settings.port),
this.settings.path,
this.settings.clientid
);
}
// callback handlers
this.mqttc.onConnectionLost = this.onConnectionLost.bind(this);
this.mqttc.onMessageArrived = this.onMessageArrived.bind(this);
this.retries = 0;
const _this = this;
return new Promise((resolve, reject) => {
// connect the client, if successful, call onConnect function
_this.mqttc.connect({
onSuccess: () => {
if (_this.settings.subscribeTopics !== undefined) {
// Subscribe to the requested topic
if (_this.settings.subscribeTopics.length > 0) {
if (_this.settings.dbg === true)
console.log(`Subscribing to: ${_this.settings.subscribeTopics}\n`);
_this.mqttc.subscribe(_this.settings.subscribeTopics);
}
}
if (_this.settings.onConnectCallback !== undefined)
_this.settings.onConnectCallback(_this.settings.onConnectCallbackContext);
resolve();
},
onFailure: () => {
throw new Error('Could not connect!');
},
useSSL: _this.settings.useSSL,
userName: _this.settings.mqtt_username,
password: _this.settings.mqtt_token,
});
});
}
// simulate message publication for testing purposes
simulatePublish(topic, payload) {
if (typeof payload !== 'string') payload = JSON.stringify(payload);
const msg = new Paho.Message(payload);
msg.destinationName = topic;
this.settings.onMessageCallback(msg);
}
disconnect() {
try {
this.mqttc.disconnect();
} catch (err) {
if (this.settings.dbg === true) console.error('MQTT Disconnected.');
}
}
/**
* Callback; Called when the client loses its connection
*/
onConnectionLost(responseObject) {
if (this.settings.dbg === true) console.log('Mqtt client disconnected...');
if (responseObject.errorCode !== 0) {
if (this.settings.dbg === true) console.error(`Mqtt ERROR: ${responseObject.errorMessage}\n`);
}
}
/**
* Callback; Called when a message arrives
*/
onMessageArrived(message) {
if (this.settings.dbg === true)
console.log(`Mqtt Msg [${message.destinationName}]: ${message.payloadString}\n`);
if (this.settings.onMessageCallback !== undefined) this.settings.onMessageCallback(message);
}
publish(topic, payload) {
if (typeof payload !== 'string') payload = JSON.stringify(payload);
if (this.settings.dbg === true) console.log(`Publishing (${topic}):${payload}`);
this.mqttc.send(topic, payload, 0, false);
}
subscribe(topic) {
if (this.settings.dbg === true) console.log(`Subscribing :${topic}`);
this.mqttc.subscribe(topic);
}
unsubscribe(topic) {
console.log(`Unsubscribing :${topic}`);
this.mqttc.unsubscribe(topic);
}
}