Skip to content

Commit

Permalink
Code quality improvements and debug logs for LaCrosse View (#91979)
Browse files Browse the repository at this point in the history
* Code quality improvements and debug logs for LaCrosse View

* Remove unrelated files

* Remove version bump

* Revert "Remove version bump"

This reverts commit ed44089.

* Revert "Remove unrelated files"

This reverts commit d9b48ae.
  • Loading branch information
IceBotYT committed May 25, 2023
1 parent 3fc0c9a commit 9231010
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 11 deletions.
6 changes: 6 additions & 0 deletions homeassistant/components/lacrosse_view/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""The LaCrosse View integration."""
from __future__ import annotations

import logging

from lacrosse_view import LaCrosse, LoginError

from homeassistant.config_entries import ConfigEntry
Expand All @@ -13,6 +15,7 @@
from .coordinator import LaCrosseUpdateCoordinator

PLATFORMS: list[Platform] = [Platform.SENSOR]
_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
Expand All @@ -22,17 +25,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

try:
await api.login(entry.data["username"], entry.data["password"])
_LOGGER.debug("Log in successful")
except LoginError as error:
raise ConfigEntryAuthFailed from error

coordinator = LaCrosseUpdateCoordinator(hass, api, entry)

_LOGGER.debug("First refresh")
await coordinator.async_config_entry_first_refresh()

hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
"coordinator": coordinator,
}

_LOGGER.debug("Setting up platforms")
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

return True
Expand Down
19 changes: 14 additions & 5 deletions homeassistant/components/lacrosse_view/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

from collections.abc import Mapping
import logging
from typing import Any

from lacrosse_view import LaCrosse, Location, LoginError
Expand All @@ -13,14 +14,15 @@
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.aiohttp_client import async_get_clientsession

from .const import DOMAIN, LOGGER
from .const import DOMAIN

STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required("username"): str,
vol.Required("password"): str,
}
)
_LOGGER = logging.getLogger(__name__)


async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> list[Location]:
Expand All @@ -29,14 +31,16 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> list[Loca
api = LaCrosse(async_get_clientsession(hass))

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()
_LOGGER.debug(locations)
except LoginError as error:
raise InvalidAuth from error

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

Expand All @@ -57,6 +61,7 @@ async def async_step_user(
) -> FlowResult:
"""Handle the initial step."""
if user_input is None:
_LOGGER.debug("Showing initial form")
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA
)
Expand All @@ -66,11 +71,12 @@ async def async_step_user(
try:
info = await validate_input(self.hass, user_input)
except InvalidAuth:
_LOGGER.exception("Could not login")
errors["base"] = "invalid_auth"
except NoLocations:
errors["base"] = "no_locations"
except Exception: # pylint: disable=broad-except
LOGGER.exception("Unexpected exception")
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
self.data = user_input
Expand All @@ -83,8 +89,11 @@ async def async_step_user(
)
await self.hass.config_entries.async_reload(self._reauth_entry.entry_id)
return self.async_abort(reason="reauth_successful")

_LOGGER.debug("Moving on to location step")
return await self.async_step_location()

_LOGGER.debug("Showing errors")
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
Expand All @@ -95,6 +104,7 @@ async def async_step_location(
"""Handle the location step."""

if not user_input:
_LOGGER.debug("Showing initial location selection")
return self.async_show_form(
step_id="location",
data_schema=vol.Schema(
Expand All @@ -113,7 +123,6 @@ async def async_step_location(
)

await self.async_set_unique_id(location_id)

self._abort_if_unique_id_configured()

return self.async_create_entry(
Expand Down
2 changes: 0 additions & 2 deletions homeassistant/components/lacrosse_view/const.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""Constants for the LaCrosse View integration."""
import logging

DOMAIN = "lacrosse_view"
LOGGER = logging.getLogger(__package__)
SCAN_INTERVAL = 30
10 changes: 8 additions & 2 deletions homeassistant/components/lacrosse_view/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

from datetime import timedelta
import logging
from time import time

from lacrosse_view import HTTPError, LaCrosse, Location, LoginError, Sensor
Expand All @@ -11,7 +12,9 @@
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
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]]):
Expand Down Expand Up @@ -39,7 +42,7 @@ def __init__(
self.id = entry.data["id"]
super().__init__(
hass,
LOGGER,
_LOGGER,
name="LaCrosse View",
update_interval=timedelta(seconds=SCAN_INTERVAL),
)
Expand All @@ -49,6 +52,7 @@ async def _async_update_data(self) -> list[Sensor]:
now = int(time())

if self.last_update < now - 59 * 60: # Get new token once in a hour
_LOGGER.debug("Refreshing token")
self.last_update = now
try:
await self.api.login(self.username, self.password)
Expand All @@ -66,6 +70,8 @@ async def _async_update_data(self) -> list[Sensor]:
except HTTPError as error:
raise ConfigEntryNotReady from error

_LOGGER.debug("Got data: %s", sensors)

# Verify that we have permission to read the sensors
for sensor in sensors:
if not sensor.permissions.get("read", False):
Expand Down
7 changes: 5 additions & 2 deletions homeassistant/components/lacrosse_view/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from collections.abc import Callable
from dataclasses import dataclass
import logging

from lacrosse_view import Sensor

Expand All @@ -28,7 +29,9 @@
DataUpdateCoordinator,
)

from .const import DOMAIN, LOGGER
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)


@dataclass
Expand Down Expand Up @@ -169,7 +172,7 @@ async def async_setup_entry(
f"title=LaCrosse%20View%20Unsupported%20sensor%20field:%20{field}"
)

LOGGER.warning(message)
_LOGGER.warning(message)
continue
sensor_list.append(
LaCrosseViewSensor(
Expand Down

0 comments on commit 9231010

Please sign in to comment.