-
Notifications
You must be signed in to change notification settings - Fork 6
/
mqtt-connection.html
724 lines (639 loc) · 23.4 KB
/
mqtt-connection.html
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="mqttjs.html">
<!--
The `<mqtt-connection>` element exposes MQTT connection functionality to the web.
Use one `<mqtt-connection>` element per connection to a mqtt broker e.g.
[mosca](http://www.mosca.io)
Currently the element supports `ws` and `wss` connections.
<mqtt-connection
url="ws://127.0.0.1:8080"
options='{reconnectPeriod: 1000}'>
</mqtt-connection>
With `auto` set to `true`, the element performs a MQTT.Connect whenever
the element is ready or the connection gets disconnected.
<mqtt-connection auto></mqtt-connection>
Note: The `options` attribute must be double quoted JSON.
You can disconnect the mqtt-connection explicitly by calling `disconnect` on the
element. And manually connect if `auto` is set to `false` with `connect`
@demo demo/index.html
-->
<dom-module id="mqtt-connection">
<template>
<content id="mqttSubscriptions" select="mqtt-subscription"></content>
<content id="mqttPublications" select="mqtt-publish"></content>
<content id="content"></content>
</template>
</dom-module>
<script>
'use strict';
(function (scope) {
var MqttElements = scope.MqttElements = scope.MqttElements || {};
MqttElements.MqttConnection = Polymer({
is: 'mqtt-connection',
/**
* Fired when a connection is connected.
*
* @mqtt-subscription-unregister mqtt-connection-connected
*/
/**
* Fired when a connection is closed.
*
* @event mqtt-connection-close
*/
/**
* Fired when a connection is closed.
*
* @event mqtt-connection-offline
*/
/**
* Fired when a connection error occurs.
*
* @event mqtt-connection-error
*/
/**
* Fired when a mqtt message is received .
*
* @event mqtt-message
*/
properties: {
/**
* When injecting the client object into different `<mqtt-connection>` element, each element will register to
* listen for changes/ messages in the connection. To detect memory leaks the the `EventEmitter` raises an error
* when more than `EventEmitter.maxListeners` (default 10) are registering to the client.
*
*/
maxListeners: {
type: Number,
value: 10,
observer: "_maxListenersChanged"
},
/**
* Set the clean flag to `false` to receive QOS 1 and 2 messages while offline. The messages are delivered if the
* connection is re-establish with the broker.
*/
clean: {
type: Boolean,
readOnly: false,
value: true,
},
/**
* The actual MQTT.js client that will be created on the first connect or injected
* via `<mqtt-connection client="[[client]]">`
*/
client: {
type: Object,
readOnly: false,
notify: true,
observer: '_clientChanged',
},
/**
* The prefix of the option.clientId. If the option.clientId is not set a random ID will be generated prefixed
* with clientIdPrefix
*/
clientIdPrefix: {
type: String,
value: 'mqttjs_',
},
/**
* Indicates weather the mqtt client is connected to the mqtt broker or not
*/
connected: {
type: Boolean,
readOnly: true,
notify: true,
value: false,
observer: '_connectedChanged',
},
/**
* Indicates weather the mqtt client is currently disconnecting the mqtt connection or not
*/
disconnecting: {
type: Boolean,
readOnly: true,
notify: true,
value: false,
},
/**
* A reference to the MQEmitter that is used to route messages between the `mqtt-connection` element and the
* `mqtt-subscription` elements.
*
* @attribute mqEmitter
* @type MQEmitter
* @default `new MQEmitter`
*/
mqEmitter: {
type: Object,
notify: true,
readOnly: true,
value: function () {
return require("MQEmitter")();
},
},
/**
* The options are directly passed to MQTT.js
* For further documentation see https://github.com/mqttjs/MQTT.js/wiki/connection#mqttconnectionconnectoptions
* * options.protocolId :String The mqtt protocolId tha is send to the mqtt broker DEFAULT: "MQTT"
* * options.protocolVersion :number 4
* * options.keepalive :number 120
* * options.clientId :String
* * options.clean :boolean
* * options.username :String The username that is user to authenticate the connection with
* * options.password :String The password that will be used to authenticate the `user` at the mqtt broker
* * options.will :Object The clients will message that is published from the mqtt broker in behalf of the client
* if the connection is from the client to the mqtt broker is lost.
* * options.will.topic :String The topic of the will message of the client eg. "client/"
* * options.will.qos :number The QOS of the will message of the client
* * options.will.retain :boolean The retain flag of the will message of the client
*/
options: {
type: Object,
readOnly: false,
notify: true,
value: function () {
return {
//MQIsdp
protocolId: "MQTT",
protocolVersion: 4,
keepalive: 120,
reconnectPeriod: 1000,
clientId: "",
encoding: "string",
};
},
},
username: {
type: String,
readOnly: false,
notify: true,
observer: "_usernameChanged"
},
password: {
type: String,
readOnly: false,
notify: true,
observer: "_passwordChanged"
},
/**
* An array of all `<mqtt-publish>` elements that are placed within this `<mqtt-connection>` element.
*/
publishers: {
type: Array,
notify: true,
readOnly: true,
value: function () {
return [];
},
},
/**
* An array of all `<mqtt-subscription>` elements that are placed within this `<mqtt-connection>` element. Use
* this to iterate over all subscriptions.
*/
subscriptions: {
type: Array,
notify: true,
readOnly: true,
value: function () {
return [];
},
},
/**
* The url of the mqtt broker and can be on the following protocols: 'mqtt', 'mqtts', 'tcp', 'tls', 'ws', 'wss'.
* E.g ws://localhost:8080
*/
url: {
type: String,
value: '',
},
withCredentials: {
type: Boolean,
readOnly: false,
notify: true,
value: false,
},
/**
* Set to `true` to automatically create and connect the mqtt connection.
*/
auto: {
type: Boolean,
readOnly: false,
value: false,
},
packetQueue: {
type: Array,
value: function(){
return [];
}
}
},
observers: [
'_usernameOrPasswordChanged(username, options.username, password, options.password, withCredentials, auto)',
'_autoChanged(auto, withCredentials)'
],
listeners: {
'mqtt-subscription-register': '_subscriptionElementRegistered',
'mqtt-subscription-unregister': '_subscriptionElementUnregistered',
'mqtt-publish-register': '_publishElementRegistered',
'mqtt-publish-unregister': '_publishElementUnregistered',
},
attached: function () {
if(!this.client && this.auto && !this.withCredentials) {
this.connect();
}
},
_usernameChanged: function (username, old) {
this.set("options.username", username);
},
_passwordChanged: function (password, old) {
this.set("options.password", password);
},
_autoChanged: function(auto, withCredentials){
if (!this.client && auto && !withCredentials){
this.connect();
}
},
_usernameOrPasswordChanged: function (username, optUsername, password, optPassword, withCredentials, auto) {
if (!this.client && auto && ( !withCredentials || ( withCredentials && ( username || optUsername ) && (password || optPassword )))){
this.connect()
}
},
_maxListenersChanged: function (maxListeners, old) {
if(this.client && maxListeners) {
this.client.setMaxListeners(maxListeners);
}
},
/**
* connect - connect to an MQTT broker.
*/
connect: function () {
// creates the client and automatically connects
this._createClient();
},
/**
* diconnect - disconnect for the MQTT broker
*/
disconnect: function () {
// check if we already have a client before calling end/ disconnect
if(this.client) {
this.client.end(true);
}
},
/**
* Publish to an MQTT topic
* @param topic
* @param message
* @param opt_qos
* @param opt_retained
* @param opt_callback
*/
publish: function (topic, message, opt_qos, opt_retained, opt_callback) {
// the optional parameters to the publish
var opts = {
// default qos is `0`
qos: opt_qos || 0,
// default for retained is `false`
retain: opt_retained || false
};
if(this.client) {
// actually send the `publish` message to the MQTT broker
this.client.publish(topic, message, opts, opt_callback);
} else {
var nop = function () {};
var queuePacket = {
cb: opt_callback || nop,
packet: {
cmd: 'publish',
topic: topic,
payload: message,
qos: opt_qos || 0,
retain: opt_retained || false,
messageId: 1
}
};
this.push("packetQueue", queuePacket);
}
},
/**
* Subscribe to an MQTT topic
* @param topic that the subscription is made to
* @param opt_qos [0,1,2] with the subscription is made with
* @param opt_callback an callback that will be executed when the `suback` message is received
*/
subscribe: function (topic, opt_qos, opt_callback) {
var opts = {qos: opt_qos || 0};
if(this.client) {
this.client.subscribe(topic, opts, opt_callback);
}
},
/**
* Pushes an element onto an array. To notify the changes `Polymer.Base.push` is used to alter the array
* @private
* @param path to the array
* @param element that will be put into the array
*/
_addElementAndRegister: function (path, element) {
// adding the element to the array
this.push(path, element);
// setting this connection as the parent on the connection
this._setParentConnectionOnElement(element);
},
/**
* A change listener to register event listeners on the `mqtt.client`
* @private
* @param client an instance of `MQTT.js#MqttClient`
*/
_clientChanged: function (client) {
if(client) {
client
.on("close", this._handelClose.bind(this))
.on("connect", this._handelConnected.bind(this))
.on("error", this._handelError.bind(this))
.on("message", this._handelMessage.bind(this))
.on("offline", this._handelOffline.bind(this))
.on("reconnect", this._handelReconnect.bind(this));
}
},
/**
* A listener that is run each time the `client.connected` changes
* @private
* @param connected true if `client.connected` is connected
* @param old is true if connected is false
*/
_connectedChanged: function (connected, old) {
if(connected) {
// after the connection is established we need to subscribe/ resubscribe
this._subscribeAllSubscriptions();
} else if(old) {
this._setUnsubscribedForAllSubscriptions();
}
},
/**
* Creates a new instance of MQTT.js#MqttClient
* @private
*/
_createClient: function () {
// require mqtt from bundled browserified dependencies
var mqtt = require("mqtt");
if(mqtt) {
this._createClientDebounce(mqtt);
// return this.debounce('_createClient', this._createClientDebounce());
} else {
// failed to load mqtt.js
// TODO SKO tell the user about this and maybe log environment
this.fire("mqtt-connection-error", "<mqtt-connection> element could not load MQTT.js, pleas check your setup");
console.error("<mqtt-connection> element could not load MQTT.js, pleas check your setup");
}
},
_createClientDebounce: function(mqtt){
if (this.options.clientId && this.options.clientId.length == 0){
this.set("options.clientId", this._generateClientId());
}
this.options["queue"] = this.packetQueue;
this.client = mqtt.connect(this.url, this.options);
this.client.setMaxListeners(this.maxListeners);
},
/**
* Creates a subscription for a `<mqtt-subscription>` element
* @private
* @param sub the `<mqtt-subscription>` element for that the subscription should be created
*/
_createSubscription: function (sub) {
if(this.client) {
// subscribe the element at the mqtt-broker
this.subscribe(sub.topic, sub.qos, sub._handelSubscriptionSubscribedFunc);
// add the element to the mqEmitter to receive messages on the topic
this.mqEmitter.on(sub.topic, sub._handelMessageFunc);
}
},
/**
* Generates a random mqtt client ID
* @returns {string} the X digit mqtt client ID prefixed with 'mqttjs_'. Set `clientIdPrefix` prefix the clientID
* with something else
* @private
*/
_generateClientId: function () {
return this.clientIdPrefix + Math.random().toString(16).substr(2, 8);
},
/**
* Returns true if the MQTTClient is connected otherwise false.
* @private
* @param client to check the connection status on
* @return true if the client is connected otherwise false
*/
_getConnectionStatusOfConnection: function (client) {
return client ? client.connected : false
},
/**
* Event-Handler to handel the MQTTClient close event
* @private
*/
_handelClose: function () {
this._setMqttConnected(this._getConnectionStatusOfConnection(this.client));
this.fire("mqtt-connection-close");
},
/**
* Event-Handler to handel the MQTTClient connect event
* @private
*/
_handelConnected: function () {
this._setMqttConnected(this._getConnectionStatusOfConnection(this.client));
this.fire("mqtt-connection-connected", {value: this.connected});
},
/**
* Event-Handler to handel the MQTTClient error event
* @private
*/
_handelError: function () {
this.fire("mqtt-connection-error");
},
/**
* Event-Handler to handel the MQTTClient message event
* @private
* @param topic of the message
* @param message the actual message
* @param packet the MQTT-Packet
*/
_handelMessage: function (topic, message, packet) {
this.fire("mqtt-message", {'topic': topic, 'message': message, 'packet': packet});
this.mqEmitter.emit({topic: topic, message: packet})
},
/**
* Event-Handler to handel the MQTTClient offline event
* @private
*/
_handelOffline: function () {
this._setMqttConnected(this._getConnectionStatusOfConnection(this.client));
this.fire("mqtt-connection-offline", {value: this.connected});
},
/**
* Event-Handler to handel the MQTTClient reconnect event
* @private
*/
_handelReconnect: function () {
this.fire("mqtt-connection-reconnect");
},
/**
* Event-Handler that is called when a <mqtt-subscriptions> is changed, for example when it recieves a mqtt-message
* @private
* @param element the <mqtt-subscriptions> elemment that has changed
*/
_notifySubscriptionChanged: function (element) {
this._propagateElementChanged(element, "subscriptions");
},
/**
* Propagates the changes of any element e.g. <mqtt-subscriptions> to other observing elements e.g. <dom-repeat>
* @private
* @param element
* @param arrElementPath
*/
_propagateElementChanged: function (element, arrElementPath) {
// the array property that hold the element that changed
var arrName = arrElementPath;
// get the index of the element
var index = this[arrName].indexOf(element);
// if the element exists within the array
if(index >= 0) {
// get the polymer collection key see:
// https://github.com/Polymer/polymer/issues/2068
var polymerPathId = Polymer.Collection.get(this.get(arrName)).getKey(this[arrName][index]);
// check if the id is valid
if(polymerPathId >= 0) {
// get all defined properties of the custom element
var propertyNames = Object.getOwnPropertyNames(this[arrName][index].properties);
// iterate over all properties
for (var i = 0; i < propertyNames.length; i++) {
// build the path
var path = [arrName, polymerPathId, propertyNames[i]].join(".");
// check if the element is an array, then slice needs to get called to actually result in
// Polymer_propertySetter
// old !== value => true
if(Array.isArray(this[arrName][index][propertyNames[i]])) {
this.notifyPath(path, this[arrName][index][propertyNames[i]].slice());
}
// TOOD
// if the prop is an object each property has to be checked recursively
// for now use
// this.set($path, {$prop1: $prop1Old, $prop2: prop2Changed};
// to notify the path about changes
// else if(typeof this[arrName][index][propertyNames[i]] === "object") {
//
// }
else {
this.notifyPath(path, this[arrName][index][propertyNames[i]]);
}
}
}
}
},
/**
* Adds and registers and <mqtt-publish> element
* @private
* @param event that is fired from the <mqtt-publish> element on attach
*/
_publishElementRegistered: function (event) {
this._addElementAndRegister("publishers", event.target);
},
/**
* Removes and <mqtt-publish> element
* @private
* @param event that is fires from the <mqtt-publish> element on detached
*/
_publishElementUnregistered: function (event) {
this._unregisterElement("publishers", event.detail.target);
},
/**
* Removes an <mqtt-subscription> element from the MQEmitter
* @private
* @param sub the <mqtt-subscription> element that will be removed from the MQEmitter
*/
_removeSubFromEmmitter: function (sub) {
this.mqEmitter.removeListener(sub.topic, sub._handelMessageFunc);
},
/**
* Sets the current connection state
* @private
* @param state the actual connection state false == disconnedted ; true == connected
*/
_setMqttConnected: function (state) {
if(typeof state === "boolean") {
this._setConnected(state);
}
},
/**
* Sets this <mqtt-connection> elment as the parrent connection on the element
* @private
* @param element
*/
_setParentConnectionOnElement: function (element) {
element._parentConnection = this;
},
/**
* When the mqtt-connection is disconnected all subscriptions have to be marked as unsubscribed
* @private
*/
_setUnsubscribedForAllSubscriptions: function () {
for (var i = 0; i < this.subscriptions.length; i++) {
this._setUnsubscribedToSubscription(this.subscriptions[i]);
}
},
/**
* Actually sets the <mqtt-subscription> element ot unsubscribed
* @private
* @param sub the <mqtt-subscription> element
*/
_setUnsubscribedToSubscription: function (sub) {
this._removeSubFromEmmitter(sub);
sub._handelSubscriptionUnsubscribed();
},
/**
* Subscribes all subscriptions
* @private
*/
_subscribeAllSubscriptions: function () {
var sub;
for (var i = 0; i < this.subscriptions.length; i++) {
sub = this.subscriptions[i];
// subscribe if the subscription is not subscribed
if(!sub.subscribed) {
this._createSubscription(sub);
}
}
},
/**
* Adds and registers and <mqtt-subscription> element
* @private
* @param event that is fired from the <mqtt-subscription> on attach
*/
_subscriptionElementRegistered: function (event) {
var sub = event.target;
this._addElementAndRegister("subscriptions", sub);
if(this.client && this.client.connected) {
this._createSubscription(sub);
}
},
/**
* Removes a <mqtt-subscription> element
* @private
* @param event that is fired from the <mqtt-subscription> element on detached
*/
_subscriptionElementUnregistered: function (event) {
var sub = event.detail.target;
if(sub) {
if(sub.topic && this.client) {
this.client.unsubscribe(sub.topic, sub._handelSubscriptionUnsubscribed.bind(sub));
this._removeSubFromEmmitter(sub);
}
this._unregisterElement("subscriptions", sub);
}
},
/**
* Removes an element from the array at path
* @private
* @param path of the array
* @param element that should be removed from the array
*/
_unregisterElement: function (path, element) {
this.arrayDelete(path, element);
},
})
})(window);
</script>