Skip to content

Commit

Permalink
linting
Browse files Browse the repository at this point in the history
  • Loading branch information
magnuselden authored and magnuselden committed Sep 10, 2024
1 parent e272282 commit 103a14b
Show file tree
Hide file tree
Showing 14 changed files with 90 additions and 86 deletions.
2 changes: 1 addition & 1 deletion custom_components/peaqhvac/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@


LATEST_WATER_BOOST = "latest_water_boost"
NEXT_WATER_START = "next_water_start"
NEXT_WATER_START = "next_water_start"
58 changes: 32 additions & 26 deletions custom_components/peaqhvac/extensionmethods.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,33 +27,39 @@ def subtract(*args):


def parse_to_type(value, _type):
if isinstance(value, _type):
return value
elif _type is float:
try:
return float(value)
except ValueError:
return 0
elif _type is int:
try:
return int(float(value))
except ValueError:
return 0
elif _type is bool:
try:
if value is None:
return False
elif value.lower() == "on":
return True
elif value.lower() == "off":
return False
except ValueError as e:
msg = f"Could not parse bool, setting to false to be sure {value}, {e}"
_LOGGER.error(msg)
return False
elif _type is str:
return str(value)
match _type:
case t if t is float:
try:
return float(value)
except ValueError:
return 0
case t if t is int:
try:
return int(float(value))
except ValueError:
return 0
case t if t is bool:
return _parse_to_type_bool(value)
case t if t is str:
return str(value)
case _:
if isinstance(value, _type):
return value
raise TypeError(f"Could not parse {value} to {_type}")


def _parse_to_type_bool(value) -> bool:
try:
if value is None:
return False
if value.lower() == "on":
return True
if value.lower() == "off":
return False
except ValueError as e:
msg = f"Could not parse bool, setting to false to be sure {value}, {e}"
_LOGGER.error(msg)
return False

def dt_from_epoch(epoch: int) -> str:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(epoch))
Expand Down
4 changes: 2 additions & 2 deletions custom_components/peaqhvac/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ async def async_setup_entry(
"""Add sensors for passed config_entry in HA."""

hub = hass.data[DOMAIN]["hub"]
peaqsensors = await _gather_sensors(hub, config, hass)
peaqsensors = await _gather_sensors(hub, config)
async_add_entities(peaqsensors, update_before_add=True)


async def _gather_sensors(hub, config, hass) -> list:
async def _gather_sensors(hub, config) -> list:
TRENDSENSORS = [
{
"name": TRENDSENSOR_INDOORS,
Expand Down
4 changes: 2 additions & 2 deletions custom_components/peaqhvac/service/hub/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ async def async_offset_export_model(self) -> OffsetsExportModel:
ret = OffsetsExportModel(
(self.offset.model.peaks_today, self.offset.model.peaks_tomorrow))
ret.raw_offsets = self.offset.model.raw_offsets
ret.current_offset = self.hvac.model.current_offset_dict
ret.current_offset_tomorrow = self.hvac.model.current_offset_dict_tomorrow
ret.current_offset = self.offset.model.current_offset_dict
ret.current_offset_tomorrow = self.offset.model.current_offset_dict_tomorrow

return ret

43 changes: 22 additions & 21 deletions custom_components/peaqhvac/service/hvac/interfaces/ihvac.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(self, hass: HomeAssistant, hub: Hub, observer: IObserver):
self.water_heater = WaterHeater(hub=hub, observer=observer)
self.house_ventilation = HouseVentilation(hvac=self, observer=observer)

self.observer.add(ObserverTypes.OffsetRecalculation, self.update_offset)
self.observer.add(ObserverTypes.OffsetRecalculation, self.async_update_offset)
self.observer.add(ObserverTypes.UpdateOperation, self.request_periodic_updates)
self.observer.add("water boost start", self.async_boost_water)

Expand Down Expand Up @@ -127,37 +127,38 @@ async def async_update_hvac(self) -> None:
await self.house_ventilation.async_check_vent_boost()
await self.request_periodic_updates()

def update_offset(self) -> bool: # todo: make async
async def async_update_offset(self) -> bool:
ret = False
if self.hub.sensors.peaqev_installed:
if len(self.hub.sensors.peaqev_facade.offsets.get("today", {})) < 20:
return False
return ret
try:
self.get_offsets()
#self.get_offsets()
_hvac_offset = self.hvac_offset
new_offset, force_update = self.house_heater.get_adjusted_offset(self.model.current_offset)
if new_offset != self.model.current_offset:
self.model.current_offset = new_offset
self._force_update = force_update
if self.model.current_offset != _hvac_offset:
self.observer.broadcast(ObserverTypes.OffsetsChanged)
await self.observer.async_broadcast(ObserverTypes.OffsetsChanged)
if self._force_update:
self.observer.broadcast(ObserverTypes.UpdateOperation)
return True
return False
await self.observer.async_broadcast(ObserverTypes.UpdateOperation)
ret = True
except Exception as e:
_LOGGER.exception(f"Error in updating offsets: {e}")
return False

def get_offsets(self) -> None: # todo: make async
ret = self.hub.offset.get_offset()
if ret is not None:
self.model.current_offset_dict = {k: v for k, v in ret.calculated_offsets.items() if
k.date() == datetime.now().date()}
self.model.current_offset_dict_tomorrow = {k: v for k, v in ret.calculated_offsets.items() if
k.date() == datetime.now().date() + timedelta(days=1)}
self.model.current_offset_dict_combined = ret.calculated_offsets
else:
_LOGGER.debug("get_offsets returned None where it should not")
finally:
return ret

# def get_offsets(self) -> None: # todo: make async
# ret = self.hub.offset.get_offset()
# if ret is not None:
# self.model.current_offset_dict = {k: v for k, v in ret.calculated_offsets.items() if
# k.date() == datetime.now().date()}
# self.model.current_offset_dict_tomorrow = {k: v for k, v in ret.calculated_offsets.items() if
# k.date() == datetime.now().date() + timedelta(days=1)}
# self.model.current_offset_dict_combined = ret.calculated_offsets
# else:
# _LOGGER.debug("get_offsets returned None where it should not")

@staticmethod
def _get_sensors_for_callback(types: dict) -> list:
Expand Down Expand Up @@ -209,7 +210,7 @@ async def async_update_ventilation(self) -> None:
self.update_list[HvacOperations.VentBoost] = _vent_state

async def async_update_heat(self) -> None:
if await self._hass.async_add_executor_job(self.update_offset):
if await self.async_update_offset():
if await self.async_ready_to_update(HvacOperations.Offset):
self.update_list[HvacOperations.Offset] = self.model.current_offset

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from datetime import datetime, timedelta
from peaqevcore.common.models.observer_types import ObserverTypes
from peaqevcore.services.hourselection.hoursselection import Hoursselection
from custom_components.peaqhvac.service.hvac.offset.models.offsets_model import OffsetsModel
import custom_components.peaqhvac.service.hvac.offset.offset_cache as cache
from custom_components.peaqhvac.service.hvac.offset.offset_utils import (
max_price_lower_internal, offset_per_day, set_offset_dict)
Expand Down Expand Up @@ -46,16 +45,10 @@ def min_price(self) -> float:

@property
def current_offset(self) -> int:
offsets = self.get_offset()
return offsets.raw_offsets[0].get(datetime.now().hour, 0)

def get_offset(self) -> OffsetsModel:
"""External entrypoint to the class"""
self._set_offset()
return OffsetsModel(
self.model.calculated_offsets,
self.model.raw_offsets
)
return self.model.raw_offsets[0].get(datetime.now().hour, 0)

#self.model.current_offset_dict_combined = ret.calculated_offsets

def _update_prognosis(self) -> None:
self.model.prognosis = self._hub.prognosis.prognosis
Expand Down
6 changes: 3 additions & 3 deletions custom_components/peaqhvac/service/models/ihvac_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
@dataclass
class IHvacModel:
current_offset: int = 0
current_offset_dict: dict = field(default_factory=lambda: {})
current_offset_dict_tomorrow: dict = field(default_factory=lambda: {})
current_offset_dict_combined: dict = field(default_factory=lambda: {})
# current_offset_dict: dict = field(default_factory=lambda: {})
# current_offset_dict_tomorrow: dict = field(default_factory=lambda: {})
# current_offset_dict_combined: dict = field(default_factory=lambda: {})

listenerentities: list = field(default_factory=lambda: [])

10 changes: 9 additions & 1 deletion custom_components/peaqhvac/service/models/offset_model.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
from homeassistant.helpers.event import async_track_time_interval
from datetime import timedelta
from datetime import timedelta, datetime

from peaqevcore.common.models.observer_types import ObserverTypes

Expand Down Expand Up @@ -49,6 +49,14 @@ def tolerance(self) -> int:
def tolerance(self, val):
self._tolerance = val

@property
def current_offset_dict(self) -> dict:
return {k: v for k, v in self.calculated_offsets.items() if k.date() == datetime.now().date()}

@property
def current_offset_dict_tomorrow(self) -> dict:
return {k: v for k, v in self.calculated_offsets.items() if
k.date() == datetime.now().date() + timedelta(days=1)}

def recalculate_tolerance(self, *args):
if self.hub.options.hvac_tolerance is not None:
Expand Down
12 changes: 7 additions & 5 deletions custom_components/peaqhvac/service/peaqev_facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ def offsets(self) -> dict:
data = self._peaqevhub.hours.offsets
if data is not None:
return data
else:
_LOGGER.debug(f"peaqev offsets was None. {self._peaqevhub.hours} ")
_LOGGER.debug(f"peaqev offsets was None. {self._peaqevhub.hours} ")
return {}

@property
Expand All @@ -80,7 +79,8 @@ def above_stop_threshold(self) -> bool:
stop = self._peaqevhub.threshold.stop
current = self.exact_threshold
return current > (stop + 5)
except:
except Exception as e:
_LOGGER.exception(f"Error on above_stop_threshold {e}")
return False

@property
Expand All @@ -89,12 +89,14 @@ def below_start_threshold(self) -> bool:
start = self._peaqevhub.threshold.start
current = self.exact_threshold
return current < (start)
except:
except Exception as e:
_LOGGER.exception(f"Error on below_start_threshold {e}")
return False

@property
def average_this_month(self) -> float:
try:
return self._peaqevhub.spotprice.average_month
except:
except Exception as e:
_LOGGER.exception(f"Error on average_this_month {e}")
return 0
2 changes: 1 addition & 1 deletion custom_components/peaqhvac/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ async def servicehandler_boost_water(call):
hass.services.async_register(DOMAIN, "enable", servicehandler_enable)
hass.services.async_register(DOMAIN, "disable", servicehandler_disable)
hass.services.async_register(DOMAIN, "set_mode", servicehandler_set_mode)
hass.services.async_register(DOMAIN, "boost_water", servicehandler_boost_water)
hass.services.async_register(DOMAIN, "boost_water", servicehandler_boost_water)
6 changes: 3 additions & 3 deletions custom_components/peaqhvac/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,11 @@ def device_info(self):
def is_on(self) -> bool:
if self._switch["name"] == ENABLED:
return self._hub.sensors.peaqhvac_enabled.value
elif self._switch["name"] == CONTROL_WATER:
if self._switch["name"] == CONTROL_WATER:
return self._hub.hvac.water_heater.control_module
elif self._switch["name"] == CONTROL_HEAT:
if self._switch["name"] == CONTROL_HEAT:
return self._hub.hvac.house_heater.control_module
elif self._switch["name"] == CONTROL_VENTILATION:
if self._switch["name"] == CONTROL_VENTILATION:
return self._hub.hvac.house_ventilation.control_module

@property
Expand Down
5 changes: 3 additions & 2 deletions custom_components/peaqhvac/test/test_offsets.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest
from datetime import datetime, timedelta
from datetime import datetime
import random
import pytest
from ..service.hvac.house_heater.models.calculated_offset import CalculatedOffsetModel
from ..service.hvac.offset.offset_utils import (offset_per_day, set_offset_dict, adjust_to_threshold)
from ..service.hvac.offset.peakfinder import smooth_transitions
Expand All @@ -16,6 +16,7 @@
P231218 = [0.22, 0.2, 0.17, 0.15, 0.16, 0.22, 0.3, 0.38, 0.43, 0.4, 0.38, 0.36, 0.32, 0.32, 0.32, 0.33, 0.36, 0.4, 0.39, 0.35, 0.32, 0.29, 0.26, 0.22]
P231219 = [0.19, 0.15, 0.11, 0.1, 0.14, 0.2, 0.28, 0.41, 0.51, 0.52, 0.54, 0.51, 0.45, 0.41, 0.41, 0.4, 0.37, 0.36, 0.37, 0.32, 0.3, 0.27, 0.25, 0.24]


def test_offsets_cent_and_normal_match():
prices = P231213 + P231214
now_dt = datetime(2023,12,13,20,43,0)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest
from datetime import datetime, timedelta
from ..service.hvac.water_heater.water_heater_next_start import NextWaterBoost, TARGET_TEMP, MAX_TARGET_TEMP, NextStartPostModel
from datetime import datetime
from ..service.hvac.water_heater.water_heater_next_start import NextWaterBoost, NextStartPostModel


P240126 = [0.97,0.94,0.91,0.87,0.86,0.82,0.9,0.97,1,0.98,0.95,0.91,0.82,0.74,0.78,0.77,0.81,0.89,0.85,0.55,0.47,0.44,0.42,0.39]
Expand Down

0 comments on commit 103a14b

Please sign in to comment.