From c12bedb3e5e755b88aca4171c5f312903b0ff3cd Mon Sep 17 00:00:00 2001 From: Sean Kelly Date: Wed, 7 Jun 2023 00:16:11 -0700 Subject: [PATCH] fix: Fix HA entities unavailable after broker restart when broker does not persist retained messages (#17891) * Fix race condition with bridge status message cancelling reinitialize after a reconnect to mqtt * Fix tests --- lib/mqtt.ts | 5 +++-- test/controller.test.js | 5 ++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/mqtt.ts b/lib/mqtt.ts index 6b21cdc43..4ca606bb4 100644 --- a/lib/mqtt.ts +++ b/lib/mqtt.ts @@ -101,9 +101,10 @@ export default class MQTT { }, utils.seconds(10)); logger.info('Connected to MQTT server'); - await this.publishStateOnline(); - if (!this.initialConnect) { + if (this.initialConnect) { + await this.publishStateOnline(); + } else { this.republishRetainedTimer = setTimeout(() => { // Republish retained messages in case MQTT broker does not persist them. // https://github.com/Koenkk/zigbee2mqtt/issues/9629 diff --git a/test/controller.test.js b/test/controller.test.js index ee889e661..d616eff2c 100644 --- a/test/controller.test.js +++ b/test/controller.test.js @@ -651,7 +651,7 @@ describe('Controller', () => { MQTT.events['connect'](); await flushPromises(); jest.runOnlyPendingTimers(); - expect(MQTT.publish).toHaveBeenCalledTimes(13); + expect(MQTT.publish).toHaveBeenCalledTimes(12); expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/info', expect.any(String), { retain: true, qos: 0 }, expect.any(Function)); }); @@ -662,8 +662,7 @@ describe('Controller', () => { await flushPromises(); await MQTT.events.message('zigbee2mqtt/bridge/state', 'online'); jest.runOnlyPendingTimers(); - expect(MQTT.publish).toHaveBeenCalledTimes(1); - expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/state', expect.any(String), { retain: true, qos: 0 }, expect.any(Function)); + expect(MQTT.publish).toHaveBeenCalledTimes(0); }); it('Should prevent any message being published with retain flag when force_disable_retain is set', async () => {