@@ -11,6 +11,7 @@ module.exports = function (RED) {
11
11
this . mqttClient = undefined
12
12
this . childNodes = { }
13
13
this . isConnected = false
14
+ this . isDisconnecting = false
14
15
this . isSubscribed = false
15
16
this . isError = false
16
17
this . isKilled = false
@@ -28,10 +29,10 @@ module.exports = function (RED) {
28
29
}
29
30
}
30
31
31
- this . registerChildNode = function ( nodeId , callbacks ) {
32
+ this . registerChildNode = async function ( nodeId , callbacks ) {
32
33
if ( Object . keys ( this . childNodes ) . length == 0 ) {
33
34
//first child node is registering!
34
- this . connectAndSubscribe ( )
35
+ await this . connectAndSubscribe ( )
35
36
}
36
37
37
38
this . childNodes [ nodeId ] = callbacks
@@ -54,9 +55,13 @@ module.exports = function (RED) {
54
55
this . execOrQueueJob ( requestShadowJob )
55
56
}
56
57
57
- this . unregisterChildNode = function ( nodeId ) {
58
- console . log ( 'UNREGISTERING CHILD NODE' , nodeId )
58
+ this . unregisterChildNode = async function ( nodeId ) {
59
59
delete this . childNodes [ nodeId ]
60
+
61
+ if ( Object . keys ( this . childNodes ) . length == 0 ) {
62
+ //last child node is unregistering!
63
+ await this . disconnect ( )
64
+ }
60
65
}
61
66
62
67
this . execCallbackForAll = function ( eventName , eventDetails ) {
@@ -164,11 +169,13 @@ module.exports = function (RED) {
164
169
this . discover ( nodeId )
165
170
}
166
171
167
- this . connectAndSubscribe = function ( ) {
172
+ this . connectAndSubscribe = async function ( ) {
168
173
if ( ! this . credentials . server ) {
169
174
return
170
175
}
171
176
177
+ this . isDisconnecting = false
178
+
172
179
const options = {
173
180
host : this . credentials . server ,
174
181
port : config . port ,
@@ -272,10 +279,16 @@ module.exports = function (RED) {
272
279
`vsh/${ this . credentials . thingId } /kill`
273
280
]
274
281
275
- this . mqttClient . subscribe ( topicsToSubscribe )
282
+ await this . mqttClient . subscribe ( topicsToSubscribe )
276
283
}
277
284
278
285
this . disconnect = async function ( ) {
286
+ if ( this . isDisconnecting ) {
287
+ return
288
+ }
289
+
290
+ this . isDisconnecting = true
291
+
279
292
await this . mqttClient . publish ( `vsh/${ this . credentials . thingId } /update` , {
280
293
state : { reported : { connected : false } }
281
294
} )
0 commit comments