hOn/custom_components/hon/__init__.py

74 lines
2.4 KiB
Python
Raw Normal View History

2023-02-19 02:58:21 +01:00
import logging
2023-06-25 17:33:30 +02:00
from pathlib import Path
2024-03-29 01:22:44 +01:00
from typing import Any
2023-02-19 02:58:21 +01:00
2023-11-20 15:56:24 +01:00
import voluptuous as vol # type: ignore[import-untyped]
2023-02-19 02:58:21 +01:00
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.helpers import config_validation as cv, aiohttp_client
from homeassistant.helpers.typing import HomeAssistantType
2024-03-29 01:22:44 +01:00
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
2023-06-25 17:33:30 +02:00
from pyhon import Hon
2023-03-03 18:23:30 +01:00
2024-02-10 01:02:26 +01:00
from .const import DOMAIN, PLATFORMS, MOBILE_ID, CONF_REFRESH_TOKEN
2023-02-19 02:58:21 +01:00
_LOGGER = logging.getLogger(__name__)
HON_SCHEMA = vol.Schema(
{
vol.Required(CONF_EMAIL): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
}
)
CONFIG_SCHEMA = vol.Schema(
{DOMAIN: vol.Schema(vol.All(cv.ensure_list, [HON_SCHEMA]))},
extra=vol.ALLOW_EXTRA,
)
2023-07-24 21:37:48 +02:00
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
2023-02-19 02:58:21 +01:00
session = aiohttp_client.async_get_clientsession(hass)
if (config_dir := hass.config.config_dir) is None:
raise ValueError("Missing Config Dir")
2024-03-29 01:22:44 +01:00
hon = await Hon(
email=entry.data[CONF_EMAIL],
password=entry.data[CONF_PASSWORD],
mobile_id=MOBILE_ID,
session=session,
2024-03-30 20:25:08 +01:00
test_data_path=Path(config_dir),
2024-03-29 01:22:44 +01:00
refresh_token=entry.data.get(CONF_REFRESH_TOKEN, ""),
).create()
2024-02-11 05:06:53 +01:00
2024-03-29 01:22:44 +01:00
# Save the new refresh token
2024-02-11 05:06:53 +01:00
hass.config_entries.async_update_entry(
entry, data={**entry.data, CONF_REFRESH_TOKEN: hon.api.auth.refresh_token}
)
2024-03-29 01:22:44 +01:00
coordinator: DataUpdateCoordinator[dict[str, Any]] = DataUpdateCoordinator(
hass, _LOGGER, name=DOMAIN
)
hon.subscribe_updates(coordinator.async_set_updated_data)
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.unique_id] = {"hon": hon, "coordinator": coordinator}
2023-02-19 02:58:21 +01:00
for platform in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, platform)
)
2023-07-24 21:37:48 +02:00
return True
2023-03-05 00:54:57 +01:00
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
2024-03-29 01:22:44 +01:00
refresh_token = hass.data[DOMAIN][entry.unique_id]["hon"].api.auth.refresh_token
2024-02-11 05:06:53 +01:00
hass.config_entries.async_update_entry(
entry, data={**entry.data, CONF_REFRESH_TOKEN: refresh_token}
)
2023-03-05 00:54:57 +01:00
unload = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload:
if not hass.data[DOMAIN]:
hass.data.pop(DOMAIN, None)
return unload