@@ -49,6 +49,7 @@ import CBOR from 'cbor-js';
49
49
import ArduinoCloudError from './ArduinoCloudError' ;
50
50
51
51
let connection = null ;
52
+ let connectionOptions = null ;
52
53
const subscribedTopics = { } ;
53
54
const propertyCallback = { } ;
54
55
const arduinoCloudPort = 8443 ;
@@ -82,6 +83,8 @@ const connect = options => new Promise((resolve, reject) => {
82
83
onConnected : options . onConnected ,
83
84
} ;
84
85
86
+ connectionOptions = opts ;
87
+
85
88
if ( connection ) {
86
89
return reject ( new Error ( 'connection failed: connection already open' ) ) ;
87
90
}
@@ -222,6 +225,40 @@ const disconnect = () => new Promise((resolve, reject) => {
222
225
return resolve ( ) ;
223
226
} ) ;
224
227
228
+ const updateToken = token => new Promise ( ( resolve , reject ) => {
229
+ if ( ! connection ) {
230
+ return reject ( new Error ( 'disconnection failed: connection closed' ) ) ;
231
+ }
232
+
233
+ try {
234
+ // Disconnect to the connection using the old token
235
+ connection . disconnect ( ) ;
236
+ } catch ( error ) {
237
+ // Ignore disconnection errors that comes out when Paho is reconnecting
238
+ }
239
+
240
+ // Remove the connection
241
+ connection = null ;
242
+
243
+ return resolve ( ) ;
244
+ } )
245
+ . then ( ( ) => {
246
+ // Reconnect using the new token
247
+ const reconnectOptions = Object . assign ( { } , connectionOptions , { token } ) ;
248
+ return connect ( reconnectOptions ) ;
249
+ } )
250
+ . then ( ( ) => {
251
+ // Re-subscribe to all topics subscribed before the reconnection
252
+ Object . values ( subscribedTopics ) . forEach ( ( subscribeParams ) => {
253
+ subscribe ( subscribeParams . topic , subscribeParams . cb ) ;
254
+ } ) ;
255
+
256
+ if ( typeof connectionOptions . onConnected === 'function' ) {
257
+ // Call the connection callback (with the reconnection param set to true)
258
+ connectionOptions . onConnected ( true ) ;
259
+ }
260
+ } ) ;
261
+
225
262
const subscribe = ( topic , cb ) => new Promise ( ( resolve , reject ) => {
226
263
if ( ! connection ) {
227
264
return reject ( new Error ( 'subscription failed: connection closed' ) ) ;
@@ -399,6 +436,7 @@ const onPropertyValue = (thingId, name, cb) => {
399
436
export default {
400
437
connect,
401
438
disconnect,
439
+ updateToken,
402
440
subscribe,
403
441
unsubscribe,
404
442
sendMessage,
0 commit comments