Skip to content

Commit

Permalink
add pre-commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Konstantin Deev committed Aug 17, 2023
1 parent 739db11 commit f3685b7
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 72 deletions.
18 changes: 9 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ repos:
- id: mixed-line-ending
args: ["--fix=lf"]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.280
rev: v0.0.284
hooks:
- id: ruff
args: ["--fix"]
Expand All @@ -18,12 +18,12 @@ repos:
hooks:
- id: black

- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
# - repo: https://github.com/PyCQA/flake8
# rev: 6.1.0
# hooks:
# - id: flake8

- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
# - repo: https://github.com/PyCQA/isort
# rev: 5.12.0
# hooks:
# - id: isort
17 changes: 10 additions & 7 deletions custom_components/eyeonwater/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,23 +33,23 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try:
await eye_on_water_data.client.authenticate()
except EyeOnWaterAuthError:
_LOGGER.error("Username or password was not accepted")
_LOGGER.exception("Username or password was not accepted")
return False
except asyncio.TimeoutError as error:
raise ConfigEntryNotReady from error

try:
await eye_on_water_data.setup()
except Exception as e:
_LOGGER.error(f"Fetching meters failed: {e}")
raise e
_LOGGER.exception(f"Fetching meters failed: {e}")
raise

# Fetch actual meter_info for all meters
try:
await eye_on_water_data.read_meters()
except Exception as e:
_LOGGER.error(f"Reading meters failed: {e}")
raise e
raise

# load old hostorical data
_LOGGER.info("Start loading historical data")
Expand All @@ -75,7 +75,10 @@ async def async_update_data():
update_method=async_update_data,
update_interval=SCAN_INTERVAL,
request_refresh_debouncer=debounce.Debouncer(
hass, _LOGGER, cooldown=DEBOUNCE_COOLDOWN, immediate=True
hass,
_LOGGER,
cooldown=DEBOUNCE_COOLDOWN,
immediate=True,
),
)

Expand All @@ -85,7 +88,7 @@ async def async_update_data():
DATA_SMART_METER: eye_on_water_data,
}

watch_task = asyncio.create_task(coordinator.async_refresh())
asyncio.create_task(coordinator.async_refresh())

_LOGGER.debug("Start setup platforms")
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
Expand Down
1 change: 1 addition & 0 deletions custom_components/eyeonwater/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
),
]


async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the EyeOnWater sensors."""
coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR]
Expand Down
20 changes: 10 additions & 10 deletions custom_components/eyeonwater/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
"""Config flow for EyeOnWater integration."""
import asyncio
import contextlib
import logging
from typing import Any

from aiohttp import ClientError
import voluptuous as vol

from aiohttp import ClientError
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import aiohttp_client
Expand All @@ -24,12 +22,13 @@
{
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
}
},
)


def create_account_from_config(
hass: core.HomeAssistant, data: dict[str, Any]
hass: core.HomeAssistant,
data: dict[str, Any],
) -> Account:
"""Create account login from config."""
CountryCode = hass.config.country
Expand All @@ -38,21 +37,21 @@ def create_account_from_config(
elif CountryCode == "CA":
eow_hostname = CONF_EOW_HOSTNAME_CA
else:
msg = f"Unsupported country ({CountryCode}) setup in HomeAssistant."
raise CannotConnect(
f"Unsupported country ({CountryCode}) setup in HomeAssistant."
msg,
)

metric_measurement_system = hass.config.units is METRIC_SYSTEM
username = data[CONF_USERNAME]
password = data[CONF_PASSWORD]

account = Account(
return Account(
eow_hostname=eow_hostname,
username=username,
password=password,
metric_measurement_system=metric_measurement_system,
)
return account


async def validate_input(hass: core.HomeAssistant, data):
Expand Down Expand Up @@ -82,7 +81,6 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):

async def async_step_user(self, user_input=None):
"""Handle the initial step."""

errors = {}
if user_input is not None:
try:
Expand All @@ -103,7 +101,9 @@ async def async_step_user(self, user_input=None):
return self.async_create_entry(title=info["title"], data=user_input)

return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
step_id="user",
data_schema=DATA_SCHEMA,
errors=errors,
)


Expand Down
35 changes: 18 additions & 17 deletions custom_components/eyeonwater/coordinator.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
"""EyeOnWater coordinator."""
import logging
import datetime
from typing import List
import logging

from homeassistant.components.recorder.models import StatisticData, StatisticMetaData
from homeassistant.components.recorder.statistics import async_import_statistics
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import UpdateFailed
from homeassistant.components.recorder.models import StatisticData, StatisticMetaData
from homeassistant.components.recorder.statistics import async_import_statistics

from .const import WATER_METER_NAME


from .config_flow import create_account_from_config
from .eow import (
Account,
Client,
Meter,
EyeOnWaterAPIError,
EyeOnWaterAuthError,
EyeOnWaterResponseIsEmpty,
Meter,
)

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -59,7 +55,6 @@ async def read_meters(self):

async def import_historical_data(self, days_to_load: int = 2):
"""Import historical data for today and past N days."""

for meter in self.meters:
statistics = await self.get_historical_data(meter, days_to_load)

Expand All @@ -78,12 +73,16 @@ async def import_historical_data(self, days_to_load: int = 2):
async_import_statistics(self.hass, metadata, statistics)

async def get_historical_data(
self, meter: Meter, days_to_load: int = 2
) -> List[StatisticData]:
self,
meter: Meter,
days_to_load: int = 2,
) -> list[StatisticData]:
"""Retrieve historical data for today and past N days."""

today = datetime.datetime.now().replace(
hour=0, minute=0, second=0, microsecond=0
hour=0,
minute=0,
second=0,
microsecond=0,
)

date_list = [today - datetime.timedelta(days=x) for x in range(0, days_to_load)]
Expand All @@ -94,18 +93,20 @@ async def get_historical_data(
units = meter.native_unit_of_measurement.upper()

_LOGGER.info(
f"adding historical statistics for {meter.meter_id} on {date_list} with units {units}"
f"adding historical statistics for {meter.meter_id} on {date_list} with units {units}",
)

statistics = []

for date in date_list:
_LOGGER.debug(
f"requesting historical statistics for {meter.meter_id} on {date} with units {units}"
f"requesting historical statistics for {meter.meter_id} on {date} with units {units}",
)
try:
data = await meter.get_historical_data(
date=date, units=units, client=self.client
date=date,
units=units,
client=self.client,
)
except EyeOnWaterResponseIsEmpty:
# Suppress this exception. It's valid situation when data was not reported by EOW for the requested day
Expand All @@ -120,7 +121,7 @@ async def get_historical_data(
StatisticData(
start=row["start"],
sum=row["sum"],
)
),
)

return statistics
Loading

0 comments on commit f3685b7

Please sign in to comment.