Skip to content

Commit 8f045fd

Browse files
committed
feat(connection): Disconnect from IoT cloud as soon as no devices are configured
1 parent ad7b61d commit 8f045fd

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

connection.js

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ module.exports = function (RED) {
1111
this.mqttClient = undefined
1212
this.childNodes = {}
1313
this.isConnected = false
14+
this.isDisconnecting = false
1415
this.isSubscribed = false
1516
this.isError = false
1617
this.isKilled = false
@@ -28,10 +29,10 @@ module.exports = function (RED) {
2829
}
2930
}
3031

31-
this.registerChildNode = function (nodeId, callbacks) {
32+
this.registerChildNode = async function (nodeId, callbacks) {
3233
if (Object.keys(this.childNodes).length == 0) {
3334
//first child node is registering!
34-
this.connectAndSubscribe()
35+
await this.connectAndSubscribe()
3536
}
3637

3738
this.childNodes[nodeId] = callbacks
@@ -54,9 +55,13 @@ module.exports = function (RED) {
5455
this.execOrQueueJob(requestShadowJob)
5556
}
5657

57-
this.unregisterChildNode = function (nodeId) {
58-
console.log('UNREGISTERING CHILD NODE', nodeId)
58+
this.unregisterChildNode = async function (nodeId) {
5959
delete this.childNodes[nodeId]
60+
61+
if (Object.keys(this.childNodes).length == 0) {
62+
//last child node is unregistering!
63+
await this.disconnect()
64+
}
6065
}
6166

6267
this.execCallbackForAll = function (eventName, eventDetails) {
@@ -164,11 +169,13 @@ module.exports = function (RED) {
164169
this.discover(nodeId)
165170
}
166171

167-
this.connectAndSubscribe = function () {
172+
this.connectAndSubscribe = async function () {
168173
if (!this.credentials.server) {
169174
return
170175
}
171176

177+
this.isDisconnecting = false
178+
172179
const options = {
173180
host: this.credentials.server,
174181
port: config.port,
@@ -272,10 +279,16 @@ module.exports = function (RED) {
272279
`vsh/${this.credentials.thingId}/kill`
273280
]
274281

275-
this.mqttClient.subscribe(topicsToSubscribe)
282+
await this.mqttClient.subscribe(topicsToSubscribe)
276283
}
277284

278285
this.disconnect = async function () {
286+
if (this.isDisconnecting) {
287+
return
288+
}
289+
290+
this.isDisconnecting = true
291+
279292
await this.mqttClient.publish(`vsh/${this.credentials.thingId}/update`, {
280293
state: { reported: { connected: false } }
281294
})

virtual-device.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ module.exports = function (RED) {
8989

9090
node.on('close', function (removed, done) {
9191
if (connectionNode) {
92-
connectionNode.unregisterChildNode(node.id)
92+
connectionNode.unregisterChildNode(nodeId)
9393
}
9494
node.status({})
9595
done()

0 commit comments

Comments
 (0)