Skip to content

Commit

Permalink
add option flow for poll interval
Browse files Browse the repository at this point in the history
adjust default timeout
  • Loading branch information
chises committed Feb 11, 2024
1 parent 52cebdc commit 561e10c
Show file tree
Hide file tree
Showing 10 changed files with 82 additions and 52 deletions.
24 changes: 15 additions & 9 deletions custom_components/oilfox/OilFox.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ class OilFox:
"""OilFox Python Class."""

# https://github.com/foxinsights/customer-api
TIMEOUT = 30
TIMEOUT = 300
POLL_INTERVAL = 30
TOKEN_VALID = 900
hwid: str = ""
password: str = ""
Expand All @@ -27,16 +28,21 @@ class OilFox:
device_url = base_url + "/customer-api/v1/device/"
token_url = base_url + "/customer-api/v1/token"

def __init__(self, email, password, hwid, timeout=30):
def __init__(self, email, password, hwid, timeout=300, poll_interval=30):
"""Init Method for OilFox Class."""
self.email = email
self.password = password
self.hwid = hwid
self.TIMEOUT = timeout
self.POLL_INTERVAL = poll_interval
self.state = None
_LOGGER.info(
"Init OilFox with Username %s and http-timeout %s", self.email, self.TIMEOUT
)
#if self.hwid is None or self.hwid == "":
# _LOGGER.info(
# "Init OilFox with Username %s",
# self.email,
# self.TIMEOUT,
# self.POLL_INTERVAL,
# )

async def test_connection(self):
"""Test connection to OilFox Api."""
Expand Down Expand Up @@ -79,10 +85,10 @@ async def update_stats(self):
) as response:
if response.status == 200:
self.state = await response.json()
except asyncio.TimeoutError:
raise ConfigEntryNotReady( # noqa: TRY200
f"Update values failed because of http timeout (waited for {self.TIMEOUT} s)!"
)
# except asyncio.TimeoutError:
# raise ConfigEntryNotReady( # noqa: TRY200
# f"Update values failed because of http timeout (waited for {self.TIMEOUT} s)!"
# )

except Exception as err:
_LOGGER.error(
Expand Down
14 changes: 8 additions & 6 deletions custom_components/oilfox/UpdateCoordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import update_coordinator

from .const import DOMAIN
from .const import DOMAIN, POLL_INTERVAL
from .OilFox import OilFox

_LOGGER = logging.getLogger(__name__)
Expand All @@ -25,18 +25,20 @@ def __init__(
"""Initialize global OilFox data updater."""
self.oilfox_api = oilfox_api

# _LOGGER.info("Load poll interval: %s", POLL_INTERVAL)

super().__init__(
hass,
_LOGGER,
name=DOMAIN,
update_interval=timedelta(minutes=1),
update_interval=timedelta(minutes=POLL_INTERVAL),
)

async def _async_update_data(self) -> None:
"""Fetch data."""
# _LOGGER.debug("UpdateCoordinator _async_update_data")
try:
await self.oilfox_api.update_stats()
except Exception as err:
raise ConfigEntryNotReady(repr(err)) from err
# try:
await self.oilfox_api.update_stats()
# except Exception as err:
# raise ConfigEntryNotReady(repr(err)) from err
return self.oilfox_api.state
9 changes: 0 additions & 9 deletions custom_components/oilfox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,4 @@ async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
# unload_ok = all(
# await asyncio.gather(
# [hass.config_entries.async_forward_entry_unload(entry, "sensor")]
# )
# )
# Remove options_update_listener.
# hass.data[DOMAIN][entry.entry_id]["unsub_options_update_listener"]()
return await hass.config_entries.async_forward_entry_unload(entry, "sensor")

return True
31 changes: 19 additions & 12 deletions custom_components/oilfox/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError

from .const import DOMAIN, TIMEOUT, CONF_HTTP_TIMEOUT, CONF_EMAIL, CONF_PASSWORD
from .const import (
DOMAIN,
POLL_INTERVAL,
TIMEOUT,
CONF_HTTP_TIMEOUT,
CONF_POLL_INTERVAL,
CONF_EMAIL,
CONF_PASSWORD,
)
from .OilFox import OilFox

_LOGGER = logging.getLogger(__name__)
Expand All @@ -20,14 +28,6 @@
{vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str}
)

OPTIONS_SCHEMA = vol.Schema(
{
vol.Optional(CONF_HTTP_TIMEOUT, default=TIMEOUT): vol.All(
vol.Coerce(int), vol.Clamp(min=5, max=60)
)
}
)


async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate the user input allows us to connect.
Expand Down Expand Up @@ -122,12 +122,15 @@ async def async_step_init(
) -> FlowResult:
"""Manage the options."""
timeout = TIMEOUT
poll_interval = POLL_INTERVAL
if user_input is not None:
# _LOGGER.info("Option Flow 2:%s", repr(user_input))
return self.async_create_entry(title="", data=user_input)

if "http-timeout" in self.options:
timeout = self.options["http-timeout"]
if CONF_HTTP_TIMEOUT in self.options:
timeout = self.options[CONF_HTTP_TIMEOUT]
if CONF_POLL_INTERVAL in self.options:
poll_interval = self.options[CONF_POLL_INTERVAL]

return self.async_show_form(
step_id="init",
Expand All @@ -136,7 +139,11 @@ async def async_step_init(
vol.Required(
CONF_HTTP_TIMEOUT,
default=timeout,
): int
): vol.All(vol.Coerce(int), vol.Clamp(min=5, max=300)),
vol.Required(
CONF_POLL_INTERVAL,
default=poll_interval,
): vol.All(vol.Coerce(int), vol.Clamp(min=1, max=300)),
}
),
)
Expand Down
5 changes: 3 additions & 2 deletions custom_components/oilfox/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
CONF_EMAIL = "email"
CONF_PASSWORD = "password"
CONF_HTTP_TIMEOUT = "http-timeout"

TIMEOUT = 30
CONF_POLL_INTERVAL = "poll-interval"
TIMEOUT = 300
POLL_INTERVAL = 30
2 changes: 1 addition & 1 deletion custom_components/oilfox/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
],
"ssdp": [],
"zeroconf": [],
"version": "1.0.1"
"version": "1.1.0"
}
38 changes: 29 additions & 9 deletions custom_components/oilfox/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@

import voluptuous as vol

from datetime import timedelta
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
# PLATFORM_SCHEMA,
SensorDeviceClass,
SensorEntity,
SensorStateClass,
Expand All @@ -30,7 +31,15 @@
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import TIMEOUT, CONF_EMAIL, CONF_PASSWORD, CONF_HTTP_TIMEOUT, DOMAIN
from .const import (
TIMEOUT,
POLL_INTERVAL,
CONF_EMAIL,
CONF_PASSWORD,
CONF_HTTP_TIMEOUT,
DOMAIN,
CONF_POLL_INTERVAL,
)
from .OilFox import OilFox

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -119,12 +128,12 @@
}

# Validation of the user's configuration
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_EMAIL): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
}
)
# PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
# {
# vol.Required(CONF_EMAIL): cv.string,
# vol.Required(CONF_PASSWORD): cv.string,
# }
# )


async def async_setup_platform(
Expand Down Expand Up @@ -173,7 +182,17 @@ async def async_setup_entry(
timeout = TIMEOUT
_LOGGER.info("Load default timeout value: %s", timeout)

if CONF_POLL_INTERVAL in config_entry.options:
poll_interval = config_entry.options[CONF_POLL_INTERVAL]
_LOGGER.info(
"Load custom poll interval: %s", config_entry.options[CONF_POLL_INTERVAL]
)
else:
poll_interval = POLL_INTERVAL
_LOGGER.info("Load default poll intervall: %s", poll_interval)

coordinator = hass.data[DOMAIN][config_entry.entry_id]
coordinator.update_interval = timedelta(minutes=poll_interval)
_LOGGER.debug("OilFox Coordinator Data Result: %s", repr(coordinator.data))
if coordinator.data is None or coordinator.data is False:
raise ConfigEntryNotReady(
Expand All @@ -195,7 +214,8 @@ async def async_setup_entry(
email,
password,
oilfox_device["hwid"],
timeout=config_entry.options[CONF_HTTP_TIMEOUT],
timeout=timeout,
poll_interval=poll_interval,
),
sensor[1],
hass,
Expand Down
3 changes: 2 additions & 1 deletion custom_components/oilfox/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"init": {
"title": "OilFox Options",
"data": {
"http-timeout": "HTTP Timeout in seconds"
"http-timeout": "HTTP Timeout in seconds",
"poll-interval": "Poll frequency in minutes"
},
"description": "OilFox Integration Options"
}
Expand Down
3 changes: 2 additions & 1 deletion custom_components/oilfox/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"step": {
"init": {
"data": {
"http-timeout": "HTTP Timeout in Sekunden"
"http-timeout": "HTTP Timeout in Sekunden",
"poll-interval": "Abfrageintervall in Minuten"
},
"description": "",
"title": "OilFox Options"
Expand Down
5 changes: 3 additions & 2 deletions custom_components/oilfox/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@
"step": {
"init": {
"data": {
"http-timeout": "HTTP Timeout in seconds"
"http-timeout": "HTTP Timeout in seconds",
"poll-interval": "Poll frequency in minutes"
},
"description": "",
"description": "OilFox Integration Options",
"title": "OilFox Options"
}
}
Expand Down

0 comments on commit 561e10c

Please sign in to comment.