Code quality improvements and debug logs for LaCrosse View (#91979)

* Code quality improvements and debug logs for LaCrosse View

* Remove unrelated files

* Remove version bump

* Revert "Remove version bump"

This reverts commit ed440899f97fe43932fd40f32e1316c403e1504c.

* Revert "Remove unrelated files"

This reverts commit d9b48ae4f9935c377c177f3bc048351b612a8cb8.
This commit is contained in:
IceBotYT 2023-05-25 06:37:16 -04:00 committed by GitHub
parent 3fc0c9a325
commit 9231010402
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 33 additions and 11 deletions

View File

@ -1,6 +1,8 @@
"""The LaCrosse View integration.""" """The LaCrosse View integration."""
from __future__ import annotations from __future__ import annotations
import logging
from lacrosse_view import LaCrosse, LoginError from lacrosse_view import LaCrosse, LoginError
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -13,6 +15,7 @@ from .const import DOMAIN
from .coordinator import LaCrosseUpdateCoordinator from .coordinator import LaCrosseUpdateCoordinator
PLATFORMS: list[Platform] = [Platform.SENSOR] PLATFORMS: list[Platform] = [Platform.SENSOR]
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
@ -22,17 +25,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
await api.login(entry.data["username"], entry.data["password"]) await api.login(entry.data["username"], entry.data["password"])
_LOGGER.debug("Log in successful")
except LoginError as error: except LoginError as error:
raise ConfigEntryAuthFailed from error raise ConfigEntryAuthFailed from error
coordinator = LaCrosseUpdateCoordinator(hass, api, entry) coordinator = LaCrosseUpdateCoordinator(hass, api, entry)
_LOGGER.debug("First refresh")
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = { hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
"coordinator": coordinator, "coordinator": coordinator,
} }
_LOGGER.debug("Setting up platforms")
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True return True

View File

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Mapping from collections.abc import Mapping
import logging
from typing import Any from typing import Any
from lacrosse_view import LaCrosse, Location, LoginError from lacrosse_view import LaCrosse, Location, LoginError
@ -13,7 +14,7 @@ from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN, LOGGER from .const import DOMAIN
STEP_USER_DATA_SCHEMA = vol.Schema( STEP_USER_DATA_SCHEMA = vol.Schema(
{ {
@ -21,6 +22,7 @@ STEP_USER_DATA_SCHEMA = vol.Schema(
vol.Required("password"): str, vol.Required("password"): str,
} }
) )
_LOGGER = logging.getLogger(__name__)
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> list[Location]: async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> list[Location]:
@ -29,14 +31,16 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> list[Loca
api = LaCrosse(async_get_clientsession(hass)) api = LaCrosse(async_get_clientsession(hass))
try: try:
await api.login(data["username"], data["password"]) if await api.login(data["username"], data["password"]):
_LOGGER.debug("Successfully logged in")
locations = await api.get_locations() locations = await api.get_locations()
_LOGGER.debug(locations)
except LoginError as error: except LoginError as error:
raise InvalidAuth from error raise InvalidAuth from error
if not locations: if not locations:
raise NoLocations("No locations found for account {}".format(data["username"])) raise NoLocations(f'No locations found for account {data["username"]}')
return locations return locations
@ -57,6 +61,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) -> FlowResult: ) -> FlowResult:
"""Handle the initial step.""" """Handle the initial step."""
if user_input is None: if user_input is None:
_LOGGER.debug("Showing initial form")
return self.async_show_form( return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA step_id="user", data_schema=STEP_USER_DATA_SCHEMA
) )
@ -66,11 +71,12 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
info = await validate_input(self.hass, user_input) info = await validate_input(self.hass, user_input)
except InvalidAuth: except InvalidAuth:
_LOGGER.exception("Could not login")
errors["base"] = "invalid_auth" errors["base"] = "invalid_auth"
except NoLocations: except NoLocations:
errors["base"] = "no_locations" errors["base"] = "no_locations"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
LOGGER.exception("Unexpected exception") _LOGGER.exception("Unexpected exception")
errors["base"] = "unknown" errors["base"] = "unknown"
else: else:
self.data = user_input self.data = user_input
@ -83,8 +89,11 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) )
await self.hass.config_entries.async_reload(self._reauth_entry.entry_id) await self.hass.config_entries.async_reload(self._reauth_entry.entry_id)
return self.async_abort(reason="reauth_successful") return self.async_abort(reason="reauth_successful")
_LOGGER.debug("Moving on to location step")
return await self.async_step_location() return await self.async_step_location()
_LOGGER.debug("Showing errors")
return self.async_show_form( return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
) )
@ -95,6 +104,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle the location step.""" """Handle the location step."""
if not user_input: if not user_input:
_LOGGER.debug("Showing initial location selection")
return self.async_show_form( return self.async_show_form(
step_id="location", step_id="location",
data_schema=vol.Schema( data_schema=vol.Schema(
@ -113,7 +123,6 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) )
await self.async_set_unique_id(location_id) await self.async_set_unique_id(location_id)
self._abort_if_unique_id_configured() self._abort_if_unique_id_configured()
return self.async_create_entry( return self.async_create_entry(

View File

@ -1,6 +1,4 @@
"""Constants for the LaCrosse View integration.""" """Constants for the LaCrosse View integration."""
import logging
DOMAIN = "lacrosse_view" DOMAIN = "lacrosse_view"
LOGGER = logging.getLogger(__package__)
SCAN_INTERVAL = 30 SCAN_INTERVAL = 30

View File

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging
from time import time from time import time
from lacrosse_view import HTTPError, LaCrosse, Location, LoginError, Sensor from lacrosse_view import HTTPError, LaCrosse, Location, LoginError, Sensor
@ -11,7 +12,9 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import LOGGER, SCAN_INTERVAL from .const import SCAN_INTERVAL
_LOGGER = logging.getLogger(__name__)
class LaCrosseUpdateCoordinator(DataUpdateCoordinator[list[Sensor]]): class LaCrosseUpdateCoordinator(DataUpdateCoordinator[list[Sensor]]):
@ -39,7 +42,7 @@ class LaCrosseUpdateCoordinator(DataUpdateCoordinator[list[Sensor]]):
self.id = entry.data["id"] self.id = entry.data["id"]
super().__init__( super().__init__(
hass, hass,
LOGGER, _LOGGER,
name="LaCrosse View", name="LaCrosse View",
update_interval=timedelta(seconds=SCAN_INTERVAL), update_interval=timedelta(seconds=SCAN_INTERVAL),
) )
@ -49,6 +52,7 @@ class LaCrosseUpdateCoordinator(DataUpdateCoordinator[list[Sensor]]):
now = int(time()) now = int(time())
if self.last_update < now - 59 * 60: # Get new token once in a hour if self.last_update < now - 59 * 60: # Get new token once in a hour
_LOGGER.debug("Refreshing token")
self.last_update = now self.last_update = now
try: try:
await self.api.login(self.username, self.password) await self.api.login(self.username, self.password)
@ -66,6 +70,8 @@ class LaCrosseUpdateCoordinator(DataUpdateCoordinator[list[Sensor]]):
except HTTPError as error: except HTTPError as error:
raise ConfigEntryNotReady from error raise ConfigEntryNotReady from error
_LOGGER.debug("Got data: %s", sensors)
# Verify that we have permission to read the sensors # Verify that we have permission to read the sensors
for sensor in sensors: for sensor in sensors:
if not sensor.permissions.get("read", False): if not sensor.permissions.get("read", False):

View File

@ -3,6 +3,7 @@ from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
import logging
from lacrosse_view import Sensor from lacrosse_view import Sensor
@ -28,7 +29,9 @@ from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator, DataUpdateCoordinator,
) )
from .const import DOMAIN, LOGGER from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
@dataclass @dataclass
@ -169,7 +172,7 @@ async def async_setup_entry(
f"title=LaCrosse%20View%20Unsupported%20sensor%20field:%20{field}" f"title=LaCrosse%20View%20Unsupported%20sensor%20field:%20{field}"
) )
LOGGER.warning(message) _LOGGER.warning(message)
continue continue
sensor_list.append( sensor_list.append(
LaCrosseViewSensor( LaCrosseViewSensor(