@burgrp/mqtt-mtl 1.0.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/mqtt-mtl.js +37 -5
- package/package.json +1 -1
package/mqtt-mtl.js
CHANGED
|
@@ -10,16 +10,34 @@ module.exports = brokerUrl => {
|
|
|
10
10
|
connection: mqtt.connect(brokerUrl),
|
|
11
11
|
|
|
12
12
|
listeners: [],
|
|
13
|
+
nextListenerId: 0,
|
|
14
|
+
subscriptions: {},
|
|
13
15
|
|
|
14
16
|
publish(topic, message) {
|
|
15
17
|
this.connection.publish(topic, message);
|
|
16
18
|
},
|
|
17
19
|
|
|
18
20
|
subscribe(topic, listener) {
|
|
19
|
-
this.connection.subscribe(topic);
|
|
20
21
|
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
if (!(topic instanceof Object)) {
|
|
23
|
+
topic = {
|
|
24
|
+
strict: topic,
|
|
25
|
+
loose: topic
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (!this.subscriptions[topic.loose]) {
|
|
30
|
+
this.connection.subscribe(topic.loose);
|
|
31
|
+
this.subscriptions[topic.loose] = 1;
|
|
32
|
+
} else {
|
|
33
|
+
this.subscriptions[topic.loose]++;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let parsedTopic = topic.strict.split("/");
|
|
37
|
+
|
|
38
|
+
let id = this.nextListenerId++;
|
|
39
|
+
|
|
40
|
+
this.listeners[id] = (actTopic, actMessage) => {
|
|
23
41
|
let parsedActTopic = actTopic.split("/");
|
|
24
42
|
let matches = true;
|
|
25
43
|
for (let i in parsedTopic) {
|
|
@@ -35,14 +53,28 @@ module.exports = brokerUrl => {
|
|
|
35
53
|
if (matches) {
|
|
36
54
|
listener(actTopic, actMessage);
|
|
37
55
|
}
|
|
38
|
-
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
return id;
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
unsubscribe(listenerId) {
|
|
62
|
+
//TODO: unsubscribe from MQTT if it's last subscription in this.subscriptions[]
|
|
63
|
+
//delete this.listeners[listenerId];
|
|
64
|
+
throw new Error("Not implemented yet");
|
|
39
65
|
}
|
|
40
66
|
}
|
|
41
67
|
|
|
42
68
|
brokers[brokerUrl] = broker;
|
|
43
69
|
|
|
44
70
|
broker.connection.on("message", (topic, message) => {
|
|
45
|
-
|
|
71
|
+
for (listener of Object.values(broker.listeners)) {
|
|
72
|
+
try {
|
|
73
|
+
listener(topic, message);
|
|
74
|
+
} catch(e) {
|
|
75
|
+
console.error("Unhandled MQTT listener exception:", e);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
46
78
|
});
|
|
47
79
|
}
|
|
48
80
|
|