diff --git a/src/integrations/home-assistant/home-assistant.service.spec.ts b/src/integrations/home-assistant/home-assistant.service.spec.ts index 8fbcfa87..78d2932b 100644 --- a/src/integrations/home-assistant/home-assistant.service.spec.ts +++ b/src/integrations/home-assistant/home-assistant.service.spec.ts @@ -558,6 +558,19 @@ describe('HomeAssistantService', () => { } ); + it('should clear old retained status messages from pre-2.18.x', async () => { + await service.onModuleInit(); + service.handleNewEntity(new Sensor('test', 'Test')); + + expect(mockMqttClient.publish).toHaveBeenCalledWith( + 'room-assistant/sensor/test-instance-test/status', + '', + { + retain: true, + } + ); + }); + it('should send an instance status message as heartbeat', async () => { await service.onModuleInit(); mockMqttClient.publish.mockClear(); diff --git a/src/integrations/home-assistant/home-assistant.service.ts b/src/integrations/home-assistant/home-assistant.service.ts index 7baec07e..ebbeaa8a 100644 --- a/src/integrations/home-assistant/home-assistant.service.ts +++ b/src/integrations/home-assistant/home-assistant.service.ts @@ -171,7 +171,11 @@ export class HomeAssistantService this.entityConfigs.set(combinedId, config); this.sendDiscoveryMessage(config); - this.sendEntityStatus(config); + + if (config.availability.length > 0) { + this.clearRetained(config.availability[0].topic); // for upgrades from < 2.18.x + this.sendEntityStatus(config); + } } /** @@ -434,6 +438,15 @@ export class HomeAssistantService }); } + /** + * Clear any retained message from the given MQTT topic. + * + * @param topic - Topic to clear ("delete") + */ + private async clearRetained(topic: string): Promise { + await this.mqttClient.publish(topic, '', { retain: true }); + } + /** * Publish entity status to its availability topic with MQTT. *