Skip to content

Commit

Permalink
Merge pull request #2 from patrickvorgers/revert-1-OptionsFlow-with-u…
Browse files Browse the repository at this point in the history
…pdate-interval

Revert "Make the update_interval configurable #54"
  • Loading branch information
patrickvorgers authored Aug 28, 2024
2 parents 0930258 + b571fe0 commit db82c63
Show file tree
Hide file tree
Showing 9 changed files with 52 additions and 217 deletions.
44 changes: 8 additions & 36 deletions custom_components/quatt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@
from __future__ import annotations

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_IP_ADDRESS, CONF_SCAN_INTERVAL, Platform
from homeassistant.const import CONF_IP_ADDRESS, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession

from .api import QuattApiClient
from .const import CONF_POWER_SENSOR, DEFAULT_SCAN_INTERVAL, DOMAIN, LOGGER
from .const import DOMAIN
from .coordinator import QuattDataUpdateCoordinator

PLATFORMS: list[Platform] = [
Platform.BINARY_SENSOR,
Platform.SENSOR,
Platform.BINARY_SENSOR,
]


Expand All @@ -26,7 +26,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator = QuattDataUpdateCoordinator(
hass=hass,
update_interval=entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL),
client=QuattApiClient(
ip_address=entry.data[CONF_IP_ADDRESS],
session=async_get_clientsession(hass),
Expand All @@ -36,8 +35,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await coordinator.async_config_entry_first_refresh()

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
# On update of the options reload the entry which reloads the coordinator
entry.async_on_unload(entry.add_update_listener(update_listener))
entry.async_on_unload(entry.add_update_listener(async_reload_entry))

return True

Expand All @@ -49,33 +47,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return unloaded


async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Update listener."""
await hass.config_entries.async_reload(entry.entry_id)


async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Migrate old entry."""

if config_entry.version == 1:
# Migrate CONF_POWER_SENSOR from data to options
# Set the unique_id of the cic
LOGGER.debug("Migrating config entry from version '%s'", config_entry.version)

new_data = {**config_entry.data}
new_options = {**config_entry.options}

if CONF_POWER_SENSOR in new_data:
new_options[CONF_POWER_SENSOR] = new_data.pop(CONF_POWER_SENSOR)

# Update the version to 2
config_entry.version = 2

hass.config_entries.async_update_entry(
config_entry,
data=new_data, # Updated data without CONF_POWER_SENSOR
options=new_options, # Updated options with CONF_POWER_SENSOR
version=config_entry.version
)

return True
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
70 changes: 8 additions & 62 deletions custom_components/quatt/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
"""Adds config flow for Quatt."""

from __future__ import annotations

import voluptuous as vol

from homeassistant import config_entries
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_IP_ADDRESS, CONF_SCAN_INTERVAL
from homeassistant.core import callback
from homeassistant.const import CONF_IP_ADDRESS
from homeassistant.helpers import selector
from homeassistant.helpers.aiohttp_client import async_create_clientsession

Expand All @@ -19,19 +15,16 @@
QuattApiClientError,
)
from .const import (
CONF_POWER_SENSOR,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
LOGGER,
MAX_SCAN_INTERVAL,
MIN_SCAN_INTERVAL,
CONF_POWER_SENSOR,
)


class QuattFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Config flow for Quatt."""

VERSION = 2
VERSION = 1

async def async_step_user(
self,
Expand All @@ -54,11 +47,6 @@ async def async_step_user(
LOGGER.exception(exception)
_errors["base"] = "unknown"
else:
# Check if this cic has already been configured
# Pre-version 2 config flows are not detected!
await self.async_set_unique_id(cic_hostname)
self._abort_if_unique_id_configured()

return self.async_create_entry(
title=cic_hostname,
data=user_input,
Expand All @@ -76,6 +64,11 @@ async def async_step_user(
type=selector.TextSelectorType.TEXT
),
),
vol.Optional(CONF_POWER_SENSOR): selector.EntitySelector(
selector.EntityFilterSelectorConfig(
device_class=SensorDeviceClass.POWER
)
),
}
),
errors=_errors,
Expand All @@ -89,50 +82,3 @@ async def _test_credentials(self, ip_address: str) -> str:
)
data = await client.async_get_data()
return data["system"]["hostName"]

@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Return the options flow handler for this config entry."""
return QuattOptionsFlowHandler(config_entry)


class QuattOptionsFlowHandler(config_entries.OptionsFlow):
"""Options flow for Quatt."""

def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry

async def async_step_init(self, user_input=None):
"""Manage the options."""
_errors = {}

# Retrieve the current value of CONF_POWER_SENSOR from options
current_power_sensor = self.config_entry.options.get(CONF_POWER_SENSOR, "") if self.config_entry.options is not None else ""

if user_input is not None:
return self.async_create_entry(title="", data=user_input)

return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(
CONF_SCAN_INTERVAL,
default=self.config_entry.options.get(
CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
),
): vol.All(vol.Coerce(int), vol.Range(min=MIN_SCAN_INTERVAL, max=MAX_SCAN_INTERVAL)),
vol.Optional(
CONF_POWER_SENSOR,
description={"suggested_value": current_power_sensor if self.hass.states.get(current_power_sensor) else ""},
): selector.EntitySelector(
selector.EntityFilterSelectorConfig(
device_class=SensorDeviceClass.POWER
)
)
}
),
errors=_errors,
)
14 changes: 5 additions & 9 deletions custom_components/quatt/const.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Constants for quatt."""

from logging import Logger, getLogger
from typing import Final

from homeassistant.components.sensor import SensorDeviceClass, SensorEntityDescription
from homeassistant.const import EntityCategory, UnitOfTemperature
from homeassistant.components.sensor import SensorEntityDescription, SensorDeviceClass
from homeassistant.const import (
EntityCategory,
UnitOfTemperature,
)

LOGGER: Logger = getLogger(__package__)

Expand All @@ -15,11 +16,6 @@

CONF_POWER_SENSOR = "power_sensor"

# Defaults
DEFAULT_SCAN_INTERVAL: Final = 10
MIN_SCAN_INTERVAL: Final = 5
MAX_SCAN_INTERVAL: Final = 600

BINARY_SENSORS = [
# Heatpump 1
SensorEntityDescription(
Expand Down
37 changes: 16 additions & 21 deletions custom_components/quatt/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,17 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
UpdateFailed,
)
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .api import QuattApiClient, QuattApiClientAuthenticationError, QuattApiClientError
from .api import (
QuattApiClient,
QuattApiClientAuthenticationError,
QuattApiClientError,
)
from .const import CONF_POWER_SENSOR, DOMAIN, LOGGER


Expand All @@ -23,7 +30,6 @@ class QuattDataUpdateCoordinator(DataUpdateCoordinator):
def __init__(
self,
hass: HomeAssistant,
update_interval: int,
client: QuattApiClient,
) -> None:
"""Initialize."""
Expand All @@ -32,12 +38,12 @@ def __init__(
hass=hass,
logger=LOGGER,
name=DOMAIN,
update_interval=timedelta(seconds=update_interval),
update_interval=timedelta(seconds=10),
)

self._power_sensor_id: str = (
self.config_entry.options.get(CONF_POWER_SENSOR, "")
if (self.config_entry is not None) and (len(self.config_entry.options.get(CONF_POWER_SENSOR, "")) > 6)
self.config_entry.data.get(CONF_POWER_SENSOR)
if len(self.config_entry.data.get(CONF_POWER_SENSOR, "")) > 6
else None
)

Expand Down Expand Up @@ -77,7 +83,6 @@ def electicalPower(self):
STATE_UNKNOWN,
]:
return self.hass.states.get(self._power_sensor_id).state
return None

def computedWaterDelta(self, parent_key: str = None):
"""Compute waterDelta."""
Expand All @@ -89,16 +94,8 @@ def computedWaterDelta(self, parent_key: str = None):
temperatureWaterOut = self.getValue(parent_key + ".temperatureWaterOut")
temperatureWaterIn = self.getValue(parent_key + ".temperatureWaterIn")

LOGGER.debug(
"%s.computedWaterDelta.temperatureWaterOut %s",
parent_key,
temperatureWaterOut,
)
LOGGER.debug(
"%s.computedWaterDelta.temperatureWaterIn %s",
parent_key,
temperatureWaterIn,
)
LOGGER.debug("%s.computedWaterDelta.temperatureWaterOut %s", parent_key, temperatureWaterOut)
LOGGER.debug("%s.computedWaterDelta.temperatureWaterIn %s", parent_key, temperatureWaterIn)

if temperatureWaterOut is None or temperatureWaterIn is None:
return None
Expand Down Expand Up @@ -160,9 +157,7 @@ def computedQuattCop(self, parent_key: str = None):
"""Compute Quatt COP."""
if parent_key is None:
parent_key = ""
powerInput = self.getValue("hp1.powerInput", 0) + self.getValue(
"hp2.powerInput", 0
)
powerInput = self.getValue("hp1.powerInput", 0) + self.getValue("hp2.powerInput", 0)
powerOutput = self.getValue("hp1.power", 0) + self.getValue("hp2.power", 0)
else:
powerInput = self.getValue(parent_key + ".powerInput")
Expand Down Expand Up @@ -254,7 +249,7 @@ def getValue(self, value_path: str, default: float = None):
method = getattr(self, key)
return method(parent_key)
elif key not in value:
# Ignore any warnings about hp2 - for single quatt installations it is valid that hp2 does not exist.
"""Ignore any warnings about hp2 - for single quatt installations it is valid that hp2 does not exist."""
if key != "hp2":
LOGGER.warning("Could not find %s of %s", key, value_path)
LOGGER.debug("in %s", value)
Expand Down
2 changes: 0 additions & 2 deletions custom_components/quatt/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
"@marcoboers"
],
"config_flow": true,
"single_config_entry": false,
"documentation": "https://github.com/marcoboers/home-assistant-quatt",
"integration_type": "hub",
"iot_class": "local_polling",
"issue_tracker": "https://github.com/marcoboers/home-assistant-quatt/issues",
"requirements": [],
Expand Down
24 changes: 3 additions & 21 deletions custom_components/quatt/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,17 @@
"config": {
"step": {
"user": {
"description": "Set up your Quatt heatpump for monitoring.",
"description": "Set up your Quatt to allow monitoring.",
"data": {
"ip_address": "[%key:common::config_flow::data::ip%]"
},
"data_description": {
"ip_address": "Without http:// and port."
"ip_address": "Without http:// and port"
}
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]"
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured%]"
}
},
"options": {
"step": {
"init": {
"description": "Quatt options",
"data": {
"scan_interval": "Update interval (Seconds)",
"power_sensor": "Power sensor (Optional)"
},
"data_description": {
"scan_interval": "Number of seconds between requesting information from the Quatt.",
"power_sensor": "External energy sensor that measures the current energy consumption of the Quatt."
}
}
}
}
}
}
26 changes: 4 additions & 22 deletions custom_components/quatt/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,15 @@
"user": {
"description": "Set up your Quatt heatpump for monitoring.",
"data": {
"ip_address": "IP address / hostname"
"ip_address": "IP address"
},
"data_description": {
"ip_address": "Without http:// and port."
"ip_address": "Without http:// and port"
}
}
},
"error": {
"cannot_connect": "Failed to connect."
},
"abort": {
"already_configured": "Device is already configured."
}
},
"options": {
"step": {
"init": {
"description": "Quatt options",
"data": {
"scan_interval": "Update interval (Seconds)",
"power_sensor": "Power sensor (Optional)"
},
"data_description": {
"scan_interval": "Number of seconds between requesting information from the Quatt.",
"power_sensor": "External energy sensor that measures the current energy consumption of the Quatt."
}
}
"cannot_connect": "Failed to connect"
}
}
}
}
Loading

0 comments on commit db82c63

Please sign in to comment.