Skip to content

Commit

Permalink
Prevent stale forecast subscriptions from resubscribing
Browse files Browse the repository at this point in the history
  • Loading branch information
Patrick Kissling committed Dec 12, 2023
1 parent d20c858 commit 74f86b1
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/clock-weather-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export class ClockWeatherCard extends LitElement {
@state() private forecastSubscriber?: () => Promise<void>
@state() private forecasts?: WeatherForecast[]
@state() private error?: TemplateResult
forecastSubscriberLock = false

constructor () {
super()
Expand Down Expand Up @@ -186,7 +187,7 @@ export class ClockWeatherCard extends LitElement {

public connectedCallback (): void {
super.connectedCallback()
if (this.hasUpdated) {
if (this.hasUpdated && !this.forecastSubscriber) {
this.subscribeForecastEvents()
}
}
Expand Down Expand Up @@ -587,38 +588,47 @@ export class ClockWeatherCard extends LitElement {
}

private subscribeForecastEvents (): void {
if (this.forecastSubscriberLock) {
return
}
this.forecastSubscriberLock = true
this.unsubscribeForecastEvents()
if (this.isLegacyWeather()) {
this.forecastSubscriber = async () => {}
this.forecastSubscriberLock = false
return
}

if (!this.isConnected || !this.config || !this.hass) {
this.forecastSubscriberLock = false
return
}

const forecastType = this.determineForecastType()
if (forecastType === 'hourly_not_supported') {
this.forecastSubscriber = async () => {}
this.forecastSubscriberLock = false
throw this.createError(`Weather entity [${this.config.entity}] does not support hourly forecast.`)
}
const callback = (event: WeatherForecastEvent): void => {
this.forecasts = event.forecast
}
this.hass.connection.subscribeMessage<WeatherForecastEvent>(callback, {
const options = { resubscribe: false }
const subscribeMessage = {
type: 'weather/subscribe_forecast',
forecast_type: forecastType,
entity_id: this.config.entity
})
}
this.hass.connection.subscribeMessage<WeatherForecastEvent>(callback, subscribeMessage, options)
.then(forecastSubscriber => { this.forecastSubscriber = forecastSubscriber })
.catch(e => { console.error('clock-weather-card - Error when subscribing to weather forecast: ', e) })
.catch(e => { console.error('clock-weather-card - Error when subscribing to weather forecast: ', JSON.stringify(e)) })
.finally(() => { this.forecastSubscriberLock = false })
}

private unsubscribeForecastEvents (): void {
if (this.forecastSubscriber) {
this.forecastSubscriber()
.then(() => { this.forecastSubscriber = undefined })
.catch(e => { console.error('clock-weather-card - Error when unsubscribing weather forecast: ', e) })
void this.forecastSubscriber()
.finally(() => { this.forecasts = undefined })
}
}

Expand Down

0 comments on commit 74f86b1

Please sign in to comment.