连接成功后,设备显示在线。

ea82bf72b7ba8dedfe4ca2b705e300b0.png

注:如果连接失败,在onFailure函数中已实现退避重连,代码样例如下:

@Override

public void onFailure(IMqttToken iMqttToken, Throwable throwable) {

System.out.println("Mqtt connect fail.");

//退避重连

int lowBound = (int) (defaultBackoff * 0.8);

int highBound = (int) (defaultBackoff * 1.2);

long randomBackOff = random.nextInt(highBound - lowBound);

long backOffWithJitter = (int) (Math.pow(2.0, (double) retryTimes)) * (randomBackOff + lowBound);

long waitTImeUntilNextRetry = (int) (minBackoff + backOffWithJitter) > maxBackoff ? maxBackoff : (minBackoff + backOffWithJitter);

System.out.println("---- " + waitTImeUntilNextRetry);

try {

Thread.sleep(waitTImeUntilNextRetry);

} catch (InterruptedException e) {

System.out.println("sleep failed, the reason is" + e.getMessage().toString());

}

retryTimes++;

MqttDemo.this.connect(true);

}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐