Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use entry.runtime_data #51

Merged
merged 2 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions custom_components/victorsmartkill/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import dataclasses as dc
import datetime as dt
import logging
from math import e
from typing import Any, Callable

from homeassistant.config_entries import ConfigEntry
Expand All @@ -30,6 +31,8 @@

PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR]

type VictorSmartKillConfigEntry = ConfigEntry[IntegrationContext]


@dc.dataclass(frozen=True)
class IntegrationContext:
Expand All @@ -45,7 +48,9 @@ async def async_setup(hass: HomeAssistant, config: Config) -> bool:
return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_setup_entry(
hass: HomeAssistant, entry: VictorSmartKillConfigEntry
) -> bool:
"""Set up this integration using UI."""
_LOGGER.debug("async_setup_entry %s.", entry.title)

Expand All @@ -57,27 +62,25 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
raise ConfigEntryAuthFailed("Please re-authenticate")

coordinator = await _async_initialize_coordinator(hass, entry)
context = IntegrationContext(coordinator=coordinator)
hass.data[DOMAIN][entry.entry_id] = context
entry.runtime_data = IntegrationContext(coordinator=coordinator)

await hass.config_entries.async_forward_entry_setups(entry, coordinator.platforms)

_setup_reload(hass, entry, context)
_setup_reload(hass, entry)

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
async def async_unload_entry(hass: HomeAssistant, entry: VictorSmartKillConfigEntry):
"""Handle removal of an entry."""
_LOGGER.debug("async_unload_entry %s.", entry.title)

context: IntegrationContext = hass.data[DOMAIN][entry.entry_id]
context: IntegrationContext = entry.runtime_data
is_unloaded = await hass.config_entries.async_unload_platforms(
entry, context.coordinator.platforms
)

if is_unloaded:
hass.data[DOMAIN].pop(entry.entry_id)
await context.coordinator.async_close()
for unsubscribe in context.unsubscribe_list:
unsubscribe()
Expand Down Expand Up @@ -194,7 +197,7 @@ async def _get_traps(self) -> list[victor.Trap]:


async def _async_initialize_coordinator(
hass: HomeAssistant, entry: ConfigEntry
hass: HomeAssistant, entry: VictorSmartKillConfigEntry
) -> VictorSmartKillDataUpdateCoordinator:
username = entry.data.get(CONF_USERNAME)
password = entry.data.get(CONF_PASSWORD)
Expand Down Expand Up @@ -225,20 +228,22 @@ async def _async_initialize_coordinator(


@callback
async def _async_config_entry_changed(hass: HomeAssistant, entry: ConfigEntry):
async def _async_config_entry_changed(
hass: HomeAssistant, entry: VictorSmartKillConfigEntry
) -> None:
_LOGGER.info("Config entry has change. Reload integration.")
await hass.config_entries.async_reload(entry.entry_id)


def _setup_reload(hass: HomeAssistant, entry: ConfigEntry, context: IntegrationContext):
def _setup_reload(hass: HomeAssistant, entry: VictorSmartKillConfigEntry) -> None:
"""Set up listeners of reload triggers."""
# Listen for config entry changes and reload when changed.
context.unsubscribe_list.append(
entry.runtime_data.unsubscribe_list.append(
entry.add_update_listener(_async_config_entry_changed)
)

@callback
async def async_trap_list_changed(event: Event):
async def async_trap_list_changed(event: Event) -> None:
_LOGGER.info("Trap list hast changed (%s). Reload integration.", event.data)
await hass.config_entries.async_reload(entry.entry_id)

Expand Down
10 changes: 6 additions & 4 deletions custom_components/victorsmartkill/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.entity import Entity
from homeassistant.core import HomeAssistant
import victor_smart_kill as victor

from custom_components.victorsmartkill import IntegrationContext
from custom_components.victorsmartkill import (
IntegrationContext,
VictorSmartKillConfigEntry,
)
from custom_components.victorsmartkill.const import (
ATTR_LAST_KILL_DATE,
DOMAIN,
Expand All @@ -27,11 +29,11 @@

async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
entry: VictorSmartKillConfigEntry,
async_add_entities: Callable[[Iterable[Entity], bool | None], None],
) -> None:
"""Set up binary_sensor platform."""
context: IntegrationContext = hass.data[DOMAIN][entry.entry_id]
context: IntegrationContext = entry.runtime_data
traps: list[victor.Trap] = context.coordinator.data

entities = []
Expand Down
12 changes: 8 additions & 4 deletions custom_components/victorsmartkill/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""Adds config flow for Victor Smart-Kill."""

from __future__ import annotations

import logging

from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow
from homeassistant.config_entries import ConfigFlow, OptionsFlow
from homeassistant.const import (
CONF_PASSWORD,
CONF_SCAN_INTERVAL,
Expand All @@ -16,6 +17,8 @@
import victor_smart_kill as victor
import voluptuous as vol # type: ignore

from custom_components.victorsmartkill import VictorSmartKillConfigEntry

from custom_components.victorsmartkill.const import ( # pylint: disable=unused-import
DEFAULT_UPDATE_INTERVAL_MINUTES,
DOMAIN,
Expand Down Expand Up @@ -121,7 +124,7 @@ async def async_step_reauth_confirm(self, user_input=None):

@staticmethod
@callback
def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow:
def async_get_options_flow(config_entry: VictorSmartKillConfigEntry) -> OptionsFlow:
"""Get the options flow for this handler."""
return VictorSmartKillOptionsFlowHandler(config_entry)

Expand All @@ -147,13 +150,14 @@ async def _test_credentials(self, username, password):
class VictorSmartKillOptionsFlowHandler(OptionsFlow):
"""Victor Smart-Kill config flow options handler."""

def __init__(self, config_entry: ConfigEntry):
def __init__(self, config_entry: VictorSmartKillConfigEntry):
"""Initialize HACS options flow."""
self.config_entry = config_entry
self.options = dict(config_entry.options)

async def async_step_init(
self, user_input=None # pylint: disable=unused-argument
self,
user_input=None, # pylint: disable=unused-argument
) -> FlowResult:
"""Manage the options."""
return await self.async_step_user()
Expand Down
11 changes: 7 additions & 4 deletions custom_components/victorsmartkill/diagnostics.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
"""Victor Smart-Kill diagnostics."""

from __future__ import annotations

import dataclasses as dc
from typing import Any

from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant

from custom_components.victorsmartkill import IntegrationContext
from custom_components.victorsmartkill import (
IntegrationContext,
VictorSmartKillConfigEntry,
)
from custom_components.victorsmartkill.const import DOMAIN

TO_REDACT_DATA = {
Expand All @@ -30,14 +33,14 @@


async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
hass: HomeAssistant, config_entry: VictorSmartKillConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
diagnostics = {
"config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT_CONFIG)
}

context: IntegrationContext = hass.data[DOMAIN][config_entry.entry_id]
context: IntegrationContext = config_entry.runtime_data
if context and context.coordinator:
if context.coordinator.data:
diagnostics["data"] = async_redact_data(
Expand Down
4 changes: 2 additions & 2 deletions custom_components/victorsmartkill/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@
"requirements": [
"victor-smart-kill==1.1.1"
],
"version": "2023.1.0"
}
"version": "2024.12.0"
}
10 changes: 6 additions & 4 deletions custom_components/victorsmartkill/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
SensorEntity,
SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_LATITUDE,
Expand All @@ -27,7 +26,10 @@
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
import victor_smart_kill as victor

from custom_components.victorsmartkill import IntegrationContext
from custom_components.victorsmartkill import (
IntegrationContext,
VictorSmartKillConfigEntry,
)
from custom_components.victorsmartkill.const import (
ATTR_LAST_KILL_DATE,
ATTR_LAST_REPORT_DATE,
Expand All @@ -41,11 +43,11 @@

async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
entry: VictorSmartKillConfigEntry,
async_add_entities: Callable[[Iterable[Entity], bool | None], None],
) -> None:
"""Set up sensor platform."""
context: IntegrationContext = hass.data[DOMAIN][entry.entry_id]
context: IntegrationContext = entry.runtime_data
traps: list[victor.Trap] = context.coordinator.data

entities = []
Expand Down
Loading