Clean up goalzero (#40817)
* cleanup goalzero code * more cleanup * mroe cleanup * log defined exception to error * return None if not configured * return False if not configured
This commit is contained in:
parent
7554c8d6c5
commit
6627ffff39
6 changed files with 19 additions and 50 deletions
|
@ -3,13 +3,11 @@ import asyncio
|
|||
import logging
|
||||
|
||||
from goalzero import Yeti, exceptions
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_HOST, CONF_NAME
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.update_coordinator import (
|
||||
CoordinatorEntity,
|
||||
|
@ -17,33 +15,10 @@ from homeassistant.helpers.update_coordinator import (
|
|||
UpdateFailed,
|
||||
)
|
||||
|
||||
from .const import (
|
||||
DATA_KEY_API,
|
||||
DATA_KEY_COORDINATOR,
|
||||
DEFAULT_NAME,
|
||||
DOMAIN,
|
||||
MIN_TIME_BETWEEN_UPDATES,
|
||||
)
|
||||
from .const import DATA_KEY_API, DATA_KEY_COORDINATOR, DOMAIN, MIN_TIME_BETWEEN_UPDATES
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
GOALZERO_SCHEMA = vol.Schema(
|
||||
vol.All(
|
||||
{
|
||||
vol.Required(CONF_HOST): cv.matches_regex(
|
||||
r"\A(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2 \
|
||||
[0-4][0-9]|[01]?[0-9][0-9]?)\Z"
|
||||
),
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{DOMAIN: vol.Schema(vol.All(cv.ensure_list, [GOALZERO_SCHEMA]))},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
|
||||
PLATFORMS = ["binary_sensor"]
|
||||
|
||||
|
@ -61,8 +36,6 @@ async def async_setup_entry(hass, entry):
|
|||
name = entry.data[CONF_NAME]
|
||||
host = entry.data[CONF_HOST]
|
||||
|
||||
_LOGGER.debug("Setting up %s integration with host %s", DOMAIN, host)
|
||||
|
||||
session = async_get_clientsession(hass)
|
||||
api = Yeti(host, hass.loop, session)
|
||||
try:
|
||||
|
@ -76,7 +49,6 @@ async def async_setup_entry(hass, entry):
|
|||
try:
|
||||
await api.get_state()
|
||||
except exceptions.ConnectError as err:
|
||||
_LOGGER.warning("Failed to update data from Yeti")
|
||||
raise UpdateFailed(f"Failed to communicating with API: {err}") from err
|
||||
|
||||
coordinator = DataUpdateCoordinator(
|
||||
|
@ -117,10 +89,10 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
|
|||
class YetiEntity(CoordinatorEntity):
|
||||
"""Representation of a Goal Zero Yeti entity."""
|
||||
|
||||
def __init__(self, _api, coordinator, name, sensor_name, server_unique_id):
|
||||
def __init__(self, api, coordinator, name, server_unique_id):
|
||||
"""Initialize a Goal Zero Yeti entity."""
|
||||
super().__init__(coordinator)
|
||||
self.api = _api
|
||||
self.api = api
|
||||
self._name = name
|
||||
self._server_unique_id = server_unique_id
|
||||
self._device_class = None
|
||||
|
|
|
@ -30,14 +30,13 @@ class YetiBinarySensor(YetiEntity, BinarySensorEntity):
|
|||
|
||||
def __init__(self, api, coordinator, name, sensor_name, server_unique_id):
|
||||
"""Initialize a Goal Zero Yeti sensor."""
|
||||
super().__init__(api, coordinator, name, sensor_name, server_unique_id)
|
||||
super().__init__(api, coordinator, name, server_unique_id)
|
||||
|
||||
self._condition = sensor_name
|
||||
|
||||
variable_info = BINARY_SENSOR_DICT[sensor_name]
|
||||
self._condition_name = variable_info[0]
|
||||
self._icon = variable_info[2]
|
||||
self.api = api
|
||||
self._device_class = variable_info[1]
|
||||
|
||||
@property
|
||||
|
@ -55,6 +54,7 @@ class YetiBinarySensor(YetiEntity, BinarySensorEntity):
|
|||
"""Return if the service is on."""
|
||||
if self.api.data:
|
||||
return self.api.data[self._condition] == 1
|
||||
return False
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
|
|
|
@ -34,19 +34,20 @@ class GoalZeroFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
|
|||
|
||||
try:
|
||||
await self._async_try_connect(host)
|
||||
except exceptions.ConnectError:
|
||||
errors["base"] = "cannot_connect"
|
||||
_LOGGER.error("Error connecting to device at %s", host)
|
||||
except exceptions.InvalidHost:
|
||||
errors["base"] = "invalid_host"
|
||||
_LOGGER.error("Invalid host at %s", host)
|
||||
except Exception: # pylint: disable=broad-except
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
return self.async_create_entry(
|
||||
title=name,
|
||||
data={CONF_HOST: host, CONF_NAME: name},
|
||||
)
|
||||
except exceptions.ConnectError:
|
||||
errors["base"] = "cannot_connect"
|
||||
_LOGGER.exception("Error connecting to device at %s", host)
|
||||
except exceptions.InvalidHost:
|
||||
errors["base"] = "invalid_host"
|
||||
_LOGGER.exception("Invalid data received from device at %s", host)
|
||||
except Exception: # pylint: disable=broad-except
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
|
||||
user_input = user_input or {}
|
||||
return self.async_show_form(
|
||||
|
@ -67,7 +68,8 @@ class GoalZeroFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
|
|||
async def _async_endpoint_existed(self, endpoint):
|
||||
for entry in self._async_current_entries():
|
||||
if endpoint == entry.data.get(CONF_HOST):
|
||||
return endpoint
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _async_try_connect(self, host):
|
||||
session = async_get_clientsession(self.hass)
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"invalid_host": "This is not the Yeti you are looking for",
|
||||
"invalid_host": "Invalid host provided",
|
||||
"unknown": "Unknown Error"
|
||||
},
|
||||
"abort": {
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
},
|
||||
"error": {
|
||||
"cannot_connect": "Failed to connect",
|
||||
"invalid_host": "This is not the Yeti you are looking for",
|
||||
"invalid_host": "Invalid host provided",
|
||||
"unknown": "Unknown Error"
|
||||
},
|
||||
"step": {
|
||||
|
|
|
@ -46,11 +46,6 @@ async def test_flow_user(hass):
|
|||
DOMAIN,
|
||||
context={"source": SOURCE_USER},
|
||||
)
|
||||
assert result["type"] == RESULT_TYPE_FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["errors"] == {}
|
||||
_flow_next(hass, result["flow_id"])
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=CONF_CONFIG_FLOW,
|
||||
|
|
Loading…
Add table
Reference in a new issue