eclipse-paho / paho.mqtt.javascript

paho.mqtt.javascript
Other
1.16k stars 466 forks source link

Keep on attempting to connect the client until it's not connected? #209

Open vedant-dobby opened 4 years ago

vedant-dobby commented 4 years ago

Hi guys I'm using MQTT.

export function establishConnectionApplianceConfig (client, uniqueId, callback) {
  client.connect({
    onSuccess:onConnect,
    onFailure:doFail
  });

  function onConnect () {
    client.subscribe('/home/'+uniqueId+'/configuration/get/response')
    console.log('onConnectCalled')
    callback()
  }

  function doFail (e) {
    console.log(e)
    console.log('Do Fail Called')
    callback()
  }
}

establishConnection (callback) {
    console.log('wifi-id: '+this.state.uniqueId)
    establishConnectionApplianceConfig(global.applianceClient, this.state.uniqueId,() => {
      callback()

    })
  }

callback () {
    if (global.applianceClient.isConnected()) {
      getAppliances(global.applianceClient, this.state.uniqueId)
      receiveApplianceUpdate(global.applianceClient, this.state.uniqueId, update => {
        let status = JSON.parse(update)
        console.log(status)
        if (typeof status.power != 'undefined') {

        } else {
          getAppliances(global.applianceClient, this.state.uniqueId)
        }
      })
    } else {
      setTimeout(this.establishConnection(() => this.callback()), 5000)
    }
  }

networkScanning((searchObject, data) => {
      console.log(data)
      global.applianceClient = createClient(data)
      this.establishConnection(() => {
        console.log('Callback triggered')
        if (global.applianceClient.isConnected()) {
          getAppliances(global.applianceClient, this.state.uniqueId)
          receiveApplianceUpdate(global.applianceClient, this.state.uniqueId, update => {
            let status = JSON.parse(update)
            console.log(status)
            if (typeof status.power != 'undefined') {

            } else {
              getAppliances(global.applianceClient, this.state.uniqueId)
            }
          })
        } else {
          setTimeout(this.establishConnection(() => this.callback()), 5000)
        }
      })

The thing is Mqtt port 1883 starts first and it takes a while to start 9001. So I can detect detect MQTT but I can't connect to it so I was attempting to reconnect to it continuously until it's not connected. How to accomplish this? I'm open to any other alternatives as well.

woodz- commented 4 years ago

Have you had a look onto the utility project coming with this lib?