Fix timing issue in Withings (#105203)

This commit is contained in:
Joost Lekkerkerker 2023-12-13 16:48:46 +01:00 committed by Franck Nijhof
parent 8744b05468
commit 896ca8ce83
No known key found for this signature in database
GPG Key ID: D62583BA8AB11CA3

View File

@ -192,18 +192,30 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = withings_data
register_lock = asyncio.Lock()
webhooks_registered = False
async def unregister_webhook(
_: Any,
) -> None:
LOGGER.debug("Unregister Withings webhook (%s)", entry.data[CONF_WEBHOOK_ID])
nonlocal webhooks_registered
async with register_lock:
LOGGER.debug(
"Unregister Withings webhook (%s)", entry.data[CONF_WEBHOOK_ID]
)
webhook_unregister(hass, entry.data[CONF_WEBHOOK_ID])
await async_unsubscribe_webhooks(client)
for coordinator in withings_data.coordinators:
coordinator.webhook_subscription_listener(False)
webhooks_registered = False
async def register_webhook(
_: Any,
) -> None:
nonlocal webhooks_registered
async with register_lock:
if webhooks_registered:
return
if cloud.async_active_subscription(hass):
webhook_url = await _async_cloudhook_generate_url(hass, entry)
else:
@ -228,16 +240,19 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
get_webhook_handler(withings_data),
allowed_methods=[METH_POST],
)
LOGGER.debug("Registered Withings webhook at hass: %s", webhook_url)
await async_subscribe_webhooks(client, webhook_url)
for coordinator in withings_data.coordinators:
coordinator.webhook_subscription_listener(True)
LOGGER.debug("Register Withings webhook: %s", webhook_url)
LOGGER.debug("Registered Withings webhook at Withings: %s", webhook_url)
entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, unregister_webhook)
)
webhooks_registered = True
async def manage_cloudhook(state: cloud.CloudConnectionState) -> None:
LOGGER.debug("Cloudconnection state changed to %s", state)
if state is cloud.CloudConnectionState.CLOUD_CONNECTED:
await register_webhook(None)