Skip to content

Commit

Permalink
feat: implement config options to allow changing scan_interval (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
luuuis authored Dec 31, 2021
1 parent d4782d7 commit cbf76b0
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 12 deletions.
12 changes: 10 additions & 2 deletions custom_components/wibeee/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = {'disposers': {}}

_LOGGER.info(f"Setup config entry for {entry.title} (unique_id={entry.unique_id})")
_LOGGER.info(f"Setup config entry '{entry.title}' (unique_id={entry.unique_id})")

# Update things based on options
entry.async_on_unload(entry.add_update_listener(async_update_options))

# Forward the setup to the sensor platform.
hass.async_create_task(hass.config_entries.async_forward_entry_setup(entry, "sensor"))
Expand Down Expand Up @@ -48,5 +51,10 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)

_LOGGER.info(f"Unloaded config entry for {entry.title} (unique_id={entry.unique_id})")
_LOGGER.info(f"Unloaded config entry '{entry.title}' (unique_id={entry.unique_id})")
return dispose_ok and unload_ok


async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Update options."""
await hass.config_entries.async_reload(entry.entry_id)
34 changes: 31 additions & 3 deletions custom_components/wibeee/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@

import voluptuous as vol
from homeassistant import config_entries, exceptions
from homeassistant.const import (CONF_HOST)
from homeassistant.core import HomeAssistant
from homeassistant.const import (CONF_HOST, CONF_SCAN_INTERVAL)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.device_registry import format_mac

from .api import WibeeeAPI
from .const import DOMAIN
from .const import (DOMAIN, DEFAULT_SCAN_INTERVAL)

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -67,6 +67,34 @@ async def _show_setup_form(self, errors=None):
schema = vol.Schema({vol.Required(CONF_HOST): str, })
return self.async_show_form(step_id="user", data_schema=schema, errors=errors or {})

@staticmethod
@callback
def async_get_options_flow(config_entry):
return WibeeeOptionsFlowHandler(config_entry)


class WibeeeOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle options flow for Wibeee."""

def __init__(self, config_entry):
"""Initialize options flow."""
self.config_entry = config_entry

async def async_step_init(self, user_input=None):
"""Manage the options."""
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.Optional(
CONF_SCAN_INTERVAL,
default=self.config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL.total_seconds())
): int
}),
)


class NoDeviceInfo(exceptions.HomeAssistantError):
"""Error to indicate we couldn't get info from Wibeee."""
10 changes: 5 additions & 5 deletions custom_components/wibeee/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
REQUIREMENTS = ["xmltodict"]

import logging
from datetime import timedelta

import homeassistant.helpers.config_validation as cv
import voluptuous as vol
Expand Down Expand Up @@ -86,12 +87,12 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
"""Set up a Wibeee from a config entry."""
_LOGGER.debug("Setting up Wibeee Sensors...")
_LOGGER.debug(f"Setting up Wibeee Sensors for '{entry.unique_id}'...")

session = async_get_clientsession(hass)
host = entry.data[CONF_HOST]
scan_interval = entry.data.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
timeout = entry.data.get(CONF_TIMEOUT, DEFAULT_TIMEOUT)
scan_interval = timedelta(seconds=entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL.total_seconds()))
timeout = timedelta(seconds=entry.options.get(CONF_TIMEOUT, DEFAULT_TIMEOUT.total_seconds()))

api = WibeeeAPI(session, host, min(timeout, scan_interval))
device = await api.async_fetch_device_info(retries=5)
Expand All @@ -112,11 +113,10 @@ async def fetching_data(now=None):
if now is None:
raise PlatformNotReady from err

_LOGGER.debug(f"Start polling {host} with scan_interval: {scan_interval}")
remove_listener = async_track_time_interval(hass, fetching_data, scan_interval)
hass.data[DOMAIN][entry.entry_id]['disposers'].update(fetch_status=remove_listener)

_LOGGER.debug("Setup completed!")
_LOGGER.info(f"Setup completed for '{entry.unique_id}' (host={host}, scan_interval={scan_interval}, timeout={timeout})")
return True


Expand Down
15 changes: 13 additions & 2 deletions custom_components/wibeee/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"step": {
"user": {
"title": "Add Wibeee device",
"description": "Enter energy meter information.",
"description": "If using an IP address make sure the device is configured with a static IP address or DHCP assignment.",
"data": {
"host": "Hostname or IP address"
}
Expand All @@ -13,5 +13,16 @@
"no_device_info": "Couldn't read device info.",
"unknown": "Unknown error."
}
},
"options": {
"step": {
"init": {
"title": "Wibeee integration options",
"description": "Customize the integration.",
"data": {
"scan_interval": "Device polling interval in seconds."
}
}
}
}
}
}

0 comments on commit cbf76b0

Please sign in to comment.