core/homeassistant/components/opengarage/__init__.py

82 lines
2.6 KiB
Python
Raw Normal View History

2021-09-29 15:43:51 +00:00
"""The OpenGarage integration."""
from __future__ import annotations
2021-10-17 17:48:45 +00:00
from datetime import timedelta
import logging
from typing import Any
2021-10-17 17:48:45 +00:00
2021-09-29 15:43:51 +00:00
import opengarage
from homeassistant.config_entries import ConfigEntry
2021-12-06 03:06:35 +00:00
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_VERIFY_SSL, Platform
2021-09-29 15:43:51 +00:00
from homeassistant.core import HomeAssistant
2021-10-17 17:48:45 +00:00
from homeassistant.helpers import update_coordinator
2021-09-29 15:43:51 +00:00
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
2021-09-29 15:43:51 +00:00
from .const import CONF_DEVICE_KEY, DOMAIN
2021-10-17 17:48:45 +00:00
_LOGGER = logging.getLogger(__name__)
2021-12-06 03:06:35 +00:00
PLATFORMS = [Platform.BINARY_SENSOR, Platform.COVER, Platform.SENSOR]
2021-09-29 15:43:51 +00:00
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up OpenGarage from a config entry."""
hass.data.setdefault(DOMAIN, {})
2021-10-17 17:48:45 +00:00
open_garage_connection = opengarage.OpenGarage(
2021-09-29 15:43:51 +00:00
f"{entry.data[CONF_HOST]}:{entry.data[CONF_PORT]}",
entry.data[CONF_DEVICE_KEY],
entry.data[CONF_VERIFY_SSL],
async_get_clientsession(hass),
)
2021-10-17 17:48:45 +00:00
open_garage_data_coordinator = OpenGarageDataUpdateCoordinator(
hass,
open_garage_connection=open_garage_connection,
)
await open_garage_data_coordinator.async_config_entry_first_refresh()
hass.data[DOMAIN][entry.entry_id] = open_garage_data_coordinator
2021-09-29 15:43:51 +00:00
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
2021-09-29 15:43:51 +00:00
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
2021-10-17 17:48:45 +00:00
class OpenGarageDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
2021-10-17 17:48:45 +00:00
"""Class to manage fetching Opengarage data."""
def __init__(
self,
hass: HomeAssistant,
*,
open_garage_connection: opengarage.OpenGarage,
) -> None:
"""Initialize global Opengarage data updater."""
self.open_garage_connection = open_garage_connection
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
update_interval=timedelta(seconds=5),
2021-10-17 17:48:45 +00:00
)
async def _async_update_data(self) -> dict[str, Any]:
2021-10-17 17:48:45 +00:00
"""Fetch data."""
data = await self.open_garage_connection.update_state()
if data is None:
raise update_coordinator.UpdateFailed(
"Unable to connect to OpenGarage device"
)
return data