Skip to content

Commit

Permalink
add avaiabiity retry to configure options
Browse files Browse the repository at this point in the history
  • Loading branch information
jeatheak committed Sep 28, 2024
1 parent ba08406 commit bcfb782
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 19 deletions.
46 changes: 40 additions & 6 deletions custom_components/mitsubishi_wf_rac/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,19 @@
from homeassistant.core import HomeAssistant

from homeassistant.const import (
CONF_HOST,
CONF_PORT,
CONF_NAME,
CONF_DEVICE_ID,
CONF_HOST,
CONF_PORT,
CONF_NAME,
CONF_DEVICE_ID,
Platform,
)

from .const import CONF_AIRCO_ID, DOMAIN, CONF_OPERATOR_ID
from .const import (
CONF_AIRCO_ID,
CONF_AVAILABILITY_CHECK,
CONF_AVAILABILITY_RETRY_LIMIT,
CONF_OPERATOR_ID
)
from .wfrac.device import Device

_LOGGER = logging.getLogger(__name__)
Expand All @@ -23,6 +28,7 @@

@dataclass
class MitsubishiWfRacData:
"""Class for storing runtime data."""
device: Device

type MitsubishiWfRacConfigEntry = ConfigEntry[MitsubishiWfRacData]
Expand All @@ -34,11 +40,22 @@ async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
new_data = entry.data.copy()
new_options = {
CONF_HOST: new_data.pop(CONF_HOST),
CONF_AVAILABILITY_CHECK: False,
CONF_AVAILABILITY_RETRY_LIMIT: 3,
}

hass.config_entries.async_update_entry(
entry, data=new_data, options=new_options, version=2
)
if entry.version == 2:
new_data = entry.data.copy()
new_options = entry.options.copy()
new_options["availability_retry"] = False
new_options["availability_retry_limit"] = 3

hass.config_entries.async_update_entry(
entry, data=new_data, options=new_options, version=3
)

return True

Expand All @@ -52,16 +69,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: MitsubishiWfRacConfigEnt
operator_id: str = entry.data[CONF_OPERATOR_ID]
port: int = entry.data[CONF_PORT]
airco_id: str = entry.data[CONF_AIRCO_ID]
availability_retry: bool = entry.options.get("availability_retry", False)
availability_retry_limit: int = entry.options.get("availability_retry_limit", 3)

try:
api = Device(hass, name, device, port, device_id, operator_id, airco_id)
api = Device(hass, name, device, port, device_id, operator_id, airco_id, availability_retry, availability_retry_limit)
await api.update() # initial update to get fresh values
entry.runtime_data = MitsubishiWfRacData(api)
except Exception as ex: # pylint: disable=broad-except
_LOGGER.warning("Something whent wrong setting up device [%s] %s", device, ex)

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

entry.async_on_unload(entry.add_update_listener(async_update_options))

return True

async def async_unload_entry(hass: HomeAssistant, entry: MitsubishiWfRacConfigEntry) -> bool:
Expand All @@ -70,8 +91,21 @@ async def async_unload_entry(hass: HomeAssistant, entry: MitsubishiWfRacConfigEn
# Unload entities for this entry/device.
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

if unload_ok:
_LOGGER.info("Unloaded entry for device [%s]", entry.data[CONF_NAME])
else:
_LOGGER.warning("Failed to unload entry for device [%s]", entry.data[CONF_NAME])

return unload_ok

async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Update options."""
reloaded = await hass.config_entries.async_reload(entry.entry_id)

if reloaded:
_LOGGER.info("Options updated to [%s]", entry.options)
else:
_LOGGER.warning("Failed to update options to [%s]", entry.options)

async def async_remove_entry(hass, entry: MitsubishiWfRacConfigEntry) -> None:
"""Handle removal of an entry."""
Expand Down
16 changes: 12 additions & 4 deletions custom_components/mitsubishi_wf_rac/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from homeassistant.core import HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResult

from .const import CONF_OPERATOR_ID, CONF_AIRCO_ID, DOMAIN
from .const import CONF_AVAILABILITY_CHECK, CONF_AVAILABILITY_RETRY_LIMIT, CONF_OPERATOR_ID, CONF_AIRCO_ID, DOMAIN
from .wfrac.repository import Repository

_LOGGER = logging.getLogger(__name__)
Expand All @@ -32,7 +32,7 @@
class WfRacConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow."""

VERSION = 2
VERSION = 3
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
_discovery_info = {}
DOMAIN = DOMAIN
Expand Down Expand Up @@ -133,7 +133,7 @@ async def _async_create_common(
info = await self._async_register_airco(self.hass, user_input)

data_input = user_input.copy()
options_input = {CONF_HOST: user_input[CONF_HOST]}
options_input = {CONF_HOST: user_input[CONF_HOST], CONF_AVAILABILITY_CHECK: True, CONF_AVAILABILITY_RETRY_LIMIT: 3}
data_input.pop(CONF_HOST)

return self.async_create_entry(
Expand Down Expand Up @@ -287,7 +287,15 @@ async def async_step_init(
CONF_HOST,
default=self.config_entry.options.get(CONF_HOST), # type: ignore
): str,
}
vol.Required(
CONF_AVAILABILITY_CHECK,
default=self.config_entry.options.get(CONF_AVAILABILITY_CHECK, True ), # type: ignore
): bool,
vol.Optional(
CONF_AVAILABILITY_RETRY_LIMIT,
default=self.config_entry.options.get( CONF_AVAILABILITY_RETRY_LIMIT, 3 ), # type: ignore
): int,
},
),
)

Expand Down
2 changes: 2 additions & 0 deletions custom_components/mitsubishi_wf_rac/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

CONF_OPERATOR_ID = "operator_id"
CONF_AIRCO_ID = "airco_id"
CONF_AVAILABILITY_CHECK = "availability_check"
CONF_AVAILABILITY_RETRY_LIMIT = "availability_retry_limit"
ATTR_DEVICE_ID = "device_id"
ATTR_CONNECTED_ACCOUNTS = "connected_accounts"

Expand Down
4 changes: 3 additions & 1 deletion custom_components/mitsubishi_wf_rac/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
"init": {
"description": "Below are the options you can change for this airco.",
"data": {
"host": "[%key:common::config_flow::data::host%]"
"host": "[%key:common::config_flow::data::host%]",
"availability_check": "[%key:common::config_flow::data::avaiability%]",
"availability_retry_limit": "[%key:common::config_flow::data::avaiability_retry_limit%]"
},
"title": "WF-RAC AC connection info"
}
Expand Down
4 changes: 3 additions & 1 deletion custom_components/mitsubishi_wf_rac/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
"init": {
"description": "Below are the options you can change for this airco.",
"data": {
"host": "Host (IP) address"
"host": "Host (IP) address",
"availability_check": "Check availability",
"availability_retry_limit": "Retry limit"
},
"title": "WF-RAC AC connection info"
}
Expand Down
4 changes: 3 additions & 1 deletion custom_components/mitsubishi_wf_rac/translations/lt.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
"init": {
"description": "Žemiau pateikiamos parinktys, kurias galite keisti šiam oro kondicionieriui.",
"data": {
"host": "Host (IP) adresas"
"host": "Host (IP) adresas",
"availability_check": "Patikrinti prieinamumą",
"availability_retry_limit": "Pakartotinio bandymo limitas"
},
"title": "WF-RAC oro kondicionieriaus prisijungimo informacija"
}
Expand Down
4 changes: 3 additions & 1 deletion custom_components/mitsubishi_wf_rac/translations/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
"init": {
"description": "Hieronder zijn instellingen die je kan aanpassen voor deze airco.",
"data": {
"host": "Host (IP) address"
"host": "Host (IP) address",
"availability_check": "Controleer beschikbaarheid",
"availability_retry_limit": "Herhaal limiet"
},
"title": "WF-RAC AC connectie info"
}
Expand Down
26 changes: 21 additions & 5 deletions custom_components/mitsubishi_wf_rac/wfrac/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ def __init__( # pylint: disable=too-many-arguments
device_id: str,
operator_id: str,
airco_id: str,
availability_retry: bool,
availability_retry_limit: int,
) -> None:
self._api = Repository(hass, hostname, port, operator_id, device_id)
self._parser = RacParser()
Expand All @@ -44,6 +46,8 @@ def __init__( # pylint: disable=too-many-arguments
self._name = name
self._firmware = ""
self._connected_accounts = -1
self._availability_retry = availability_retry
self._availability_retry_limit = availability_retry_limit

@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def update(self):
Expand All @@ -53,11 +57,11 @@ async def update(self):
response = await self._api.get_aircon_stats()

if response is None:
self._available = False
self._set_availabilty(False)
_LOGGER.warning("Received no data for device %s", self._airco_id)
return
except Exception: # pylint: disable=broad-except
self._available = False
self._set_availabilty(False)
_LOGGER.exception(
"Error: something went wrong updating the airco [%s] values", self.name
)
Expand All @@ -68,10 +72,10 @@ async def update(self):
# pylint: disable = line-too-long
self._firmware = f'{response["firmType"]}, mcu: {response["mcu"]["firmVer"]}, wireless: {response["wireless"]["firmVer"]}'
self._airco = self._parser.translate_bytes(response["airconStat"])
self._available = True
self._set_availabilty(True)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Could not parse airco data")
self._available = False
self._set_availabilty(False)

async def delete_account(self):
"""Delete account (operator id) from the airco"""
Expand Down Expand Up @@ -115,9 +119,21 @@ async def set_airco(self, params: dict[str, Any]) -> None:

self._airco = self._parser.translate_bytes(response)

def _set_availabilty(self, available: bool):
"""Set availability after retry count"""
self._availability_retry += 1
if self._availability_retry >= self._availability_retry_limit:
self._available = available
self._available = False

# reset retry count if available
if available:
self._availability_retry = 0
self._available = True

def set_available(self, available: bool):
"""Set available status"""
self._available = available
self._set_availabilty(available)

@property
def device_info(self) -> DeviceInfo:
Expand Down

0 comments on commit bcfb782

Please sign in to comment.