-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
345 lines (307 loc) · 10.6 KB
/
index.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
'use strict';
const mqttBroker = require('mosca');
// ugly but only way of doing this (looks like)
var that;
/**
* This class represents the Hub Manager MQTT module connection
* This module will handle the remote connections between the MQTT broker on the server and the MQTT clients (hubs)
*
* Minimum setup exemple:
*
* // Init the module
* var hm = new HubManager(1883, 27017);
*
* // Set some control callbacks
* // Here we only allow 'truc' client with a predefined password
* hm.authorizeClientConnection(function (client, username, password) {
* if (username == 'truc' && password == 'wtl en pls') return true
* else return false;
* });
*
* // Setup the server
* hm.setup();
*
* // Done!
*
* @class HubManager
* @version 0.0001b
* @author Francois Leparoux (francois.leparoux@gmail.com)
* @copyright GiveMeSomeMoney Corporation (c)
*/
class HubManager {
/**
* Creates the Hub Manager instance
* @param mqttPort The MQTT port that the broker will listen on
* @param mongodbPort The mongoDB port that will be used for the connection with the local database
* @memberof HubManager
*/
constructor(mqttPort, mongodbPort) {
// thx Time
that = this;
// module settings
this.mqttPort = mqttPort;
this.mongodbPort = mongodbPort;
// server not configured yet
this.mqttServer = null;
// default callback values
this.authConnCallback = null;
this.authPubCallback = null;
this.authSubCallback = null;
this.connCallback = null;
this.subCallback = null;
this.unsubCallback = null;
this.pubCallback = null;
this.discCallback = null;
this.readyCallback = null;
// default settings values
this.ttlSub = 3600 * 2 * 1000; // 2 hours in ms
this.ttlPacket = 3600 * 2 * 1000; // 2 hours in ms
this.mongoPersistanceName = "hub_manager_broker_persistance";
this.logName = "hub_manager_log";
this.logLevel = 40;;
}
/**
* Sets the authorize callback that wil be called when a client tries to authenticate
* @param callback the callback function
*/
authorizeClientConnection(callback) {
this.authConnCallback = callback;
}
/**
* Sets the authorize callback that wil be called when a client tries to publish to a topic
* @param callback the callback function
*/
authorizeClientPublish(callback) {
this.authPubCallback = callback;
}
/**
* Sets the authorize callback that wil be called when a client tries to subscribe to a topic
* @param callback the callback function
*/
authorizeClientSubscription(callback) {
this.authSubCallback = callback;
}
/**
* Sets the callback that wil be called when a client is connected to the broker
* @param callback the callback function
*/
onClientConnected(callback) {
this.connCallback = callback;
}
/**
* Sets the callback that wil be called when a client has subscribed to a topic
* @param callback the callback function
*/
onClientSubscribed(callback) {
this.subCallback = callback;
}
/**
* Sets the callback that wil be called when a client has unsubscribed to a topic
* @param callback the callback function
*/
onClientUnsubscribed(callback) {
this.unsubCallback = callback;
}
/**
* Sets the callback that wil be called when a client has published data to a topic
* @param callback the callback function
*/
onClientPublished(callback) {
this.pubCallback = callback;
}
/**
* Sets the callback that wil be called when a client has disconnected from the borker
* @param callback the callback function
*/
onClientDisconnected(callback) {
this.discCallback = callback;
}
/**
* Sets the callback that wil be called when the MQTT broker has been setup
* @param callback the callback function
*/
onServerReady(callback) {
this.readyCallback = callback;
}
/**
* Returns the list of the broker's connected clients
* @readonly
* @memberof HubManager
*/
get clients() {
return this.mqttServer == null ? null : this.mqttServer.clients;
}
/**
* Publish some data (a packet) to clients subscribed to a defined topic
*
* @param {any} data
* @param {string} topic
* @memberof HubManager
*/
publishSimplePacket(data, topic) {
this.publishComplexPacket(data, topic, 0, false);
}
/**
* Publish some data (a packet) to clients subscribed to a defined topic
* Same as publishSimplePacket but with QoS and retin flag management
*
* @param {any} data
* @param {string} topic
* @memberof HubManager
*/
publishComplexPacket(data, topic, qos, retain) {
var message = {
topic: topic,
payload: data, // or a Buffer
qos: qos, // 0, 1, or 2
retain: retain // true or false
};
this.mqttServer.publish(message, /*client,*/ function () {
console.log('[HubManager MQTT] Publish done (to ' + topic + ')');
});
}
/**
* Setup the Hub Manager module, must be called after the constructor and the callback setters
*/
setup() {
// create the settings object
var settings = {
port: this.mqttPort,
backend: {
type: 'mongo',
url: 'mongodb://localhost:' + this.mongodbPort + '/mqtt',
pubsubCollection: this.mongoPersistanceName,
mongo: {}
},
logger: {
name: this.logName,
level: this.logLevel,
}
};
// create the instance
this.mqttServer = new mqttBroker.Server(settings);
var self = this;
var moscaPersistenceDB = new mqttBroker.persistence.Mongo({
url: 'mongodb://localhost:' + this.mongodbPort + '/moscaPersistence',
ttl: {
subscriptions: this.ttlSub,
packets: this.ttlPacket
}
},
function () {
console.log('[HubManager] server persistence is ready on port ' + self.mongodbPort)
}
);
moscaPersistenceDB.wire(this.mqttServer);
this.mqttServer.on('ready', function(){
// TODO fix this because it's ugly
// but cheers Time Kadel (time.kadel@sfr.fr) <-- this guy is world class! grab him whilst you can
self.__broker_setup(self)
}); // engage the broker setup procedure
}
/**
* Private function, fired when the mqtt server is ready
*/
__broker_setup() {
this.mqttServer.authenticate = this.__broker_auth;
this.mqttServer.authorizePublish = this.__broker_allow_pub;
this.mqttServer.authorizeSubscribe = this.__broker_allow_sub;
this.mqttServer.on('clientConnected', this.__broker_connected);
this.mqttServer.on('published', this.__broker_published);
this.mqttServer.on('subscribed', this.__broker_subscribed);
this.mqttServer.on('unsubscribed', this.__broker_unsubscribed);
this.mqttServer.on('clientDisconnecting', this.__broker_disconnecting);
this.mqttServer.on('clientDisconnected', this.__broker_disconnected);
if (this.readyCallback != null) {
this.readyCallback(); // indicates that we are ready
}
console.log('[MQTT] Mosca server is up and running on port ' + this.mqttPort);
}
/**
* Private function, Auth function
*/
__broker_auth(client, username, password, callback) {
console.log('[HubManager MQTT] AUTH : ' + client.id + ' using ' + username + ':' + password);
if (that.authConnCallback != null) {
callback(null, that.authConnCallback(client, username, password));
} else {
callback(null, false); // block every auth if no callback defined
}
}
/**
* Private function, used to allow client subscription
*/
__broker_allow_sub(client, topic, callback) {
if (that.authSubCallback != null) {
callback(null, that.authSubCallback(client, topic));
} else {
callback(null, false); // block subscribe if no callback define
}
}
/**
* Private function, used to allow client publish action
*/
__broker_allow_pub(client, topic, payload, callback) {
if (that.authPubCallback != null) {
callback(null, that.authPubCallback(client, topic, payload));
} else {
callback(null, false); // block every publish if no callback defined
}
}
/**
* Private function, fired when a client is connected
*/
__broker_connected(client) {
console.log('[HubManager MQTT] ' + client.id + ' is now connected');
if (that.connCallback != null) {
that.connCallback(client);
}
};
/**
* Private function, fired when a message is received
*/
__broker_published(packet, client) {
// quick fix moche comme MJ
if (client != undefined) {
console.log('[HubManager MQTT] ' + client.id + ' published "' + JSON.stringify(packet.payload) + '" to ' + packet.topic);
if (that.pubCallback != null) {
that.pubCallback(client, packet.topic, packet.payload);
}
}
};
/**
* Private function, fired when a client subscribes to a topic
*/
__broker_subscribed(topic, client) {
console.log('[HubManager MQTT] ' + client.id + ' has subscribed to ' + topic);
if (that.subCallback != null) {
that.subCallback(client, topic);
}
};
/**
* Private function, fired when a client unsubscribes from a topic
*/
__broker_unsubscribed(topic, client) {
console.log('[HubManager MQTT] ' + client.id + ' has unsubscribed from ' + topic);
if (that.unsubCallback != null) {
that.unsubCallback(client, topic);
}
};
/**
* Private function, fired when a client is disconnecting
*/
__broker_disconnecting(client) {
console.log('[HubManager MQTT] clientDisconnecting : ', client.id);
// callback needed?... TODO
};
/**
* Private function, fired when a client is disconnected
*/
__broker_disconnected(client) {
console.log('[HubManager MQTT] ' + client.id + ' is now disconnected');
if (that.discCallback != null) {
that.discCallback(client);
}
};
}
module.exports = HubManager;