Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
magnuselden authored and magnuselden committed Nov 5, 2024
1 parent 5aab75f commit 9b91a7d
Show file tree
Hide file tree
Showing 25 changed files with 251 additions and 405 deletions.
5 changes: 2 additions & 3 deletions custom_components/peaqhvac/binary_sensor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.components.binary_sensor import BinarySensorEntity, BinarySensorDeviceClass
from homeassistant.core import HomeAssistant

from .const import DOMAIN, PEAQENABLED
Expand All @@ -13,8 +13,7 @@

async def async_setup_entry(hass: HomeAssistant, config_entry, async_add_entities):
hub = hass.data[DOMAIN]["hub"]
peaqsensors = []
peaqsensors.append(PeaqBinarySensorEnabled(hub))
peaqsensors = [PeaqBinarySensorEnabled(hub)]
async_add_entities(peaqsensors)


Expand Down
3 changes: 1 addition & 2 deletions custom_components/peaqhvac/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,8 @@ async def _gather_sensors(hub, config) -> list:
}
]

ret = []
ret = [OffsetSensor(hub, config.entry_id, "calculated hvac offset")]

ret.append(OffsetSensor(hub, config.entry_id, "calculated hvac offset"))
for a in AVERAGESENSORS:
ret.append(AverageSensor(hub, config.entry_id, a))
for sensor in TRENDSENSORS:
Expand Down
8 changes: 2 additions & 6 deletions custom_components/peaqhvac/sensors/min_maxsensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,8 @@ def update(self) -> None:

@property
def extra_state_attributes(self) -> dict:
attr_dict = {}

attr_dict["max"] = float(self._max)
attr_dict["min"] = float(self._min)
attr_dict["median"] = float(self._median)
attr_dict["values"] = list(self._all_values)
attr_dict = {"max": float(self._max), "min": float(self._min), "median": float(self._median),
"values": list(self._all_values)}

return attr_dict

Expand Down
1 change: 1 addition & 0 deletions custom_components/peaqhvac/sensors/offsetsensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def __init__(self, hub, entry_id, name):
self._peaks_today = []
self._peaks_tomorrow = []
self._prognosis = []
self._aux_dict = {}

@property
def unit_of_measurement(self):
Expand Down
9 changes: 3 additions & 6 deletions custom_components/peaqhvac/sensors/trendsensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,9 @@ def icon(self) -> str:

@property
def extra_state_attributes(self) -> dict:
attr_dict = {}
attr_dict["samples"] = self._samples
attr_dict["oldest_sample"] = self._oldest_sample
attr_dict["newest_sample"] = self._newest_sample
attr_dict["samples_raw"] = self._samples_raw
attr_dict["latest_restart"] = self._latest_restart
attr_dict = {"samples": self._samples, "oldest_sample": self._oldest_sample,
"newest_sample": self._newest_sample, "samples_raw": self._samples_raw,
"latest_restart": self._latest_restart}
for k, v in self._extra_attributes.items():
attr_dict[k] = v[0](v[1])
return attr_dict
Expand Down
14 changes: 1 addition & 13 deletions custom_components/peaqhvac/service/hub/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class Hub:
def __init__(self, hass: HomeAssistant, hub_options: ConfigModel):
self._is_initialized = False
self.state_machine = hass
self.trackerentities = []
self.observer = Observer(hass) #todo: move to creation factory
self.options = hub_options
self.peaqev_discovered: bool = self.get_peaqev()
Expand All @@ -59,7 +60,6 @@ async def async_setup(self) -> None:
await self.prognosis.async_update_weather()

async def async_setup_trackers(self):
self.trackerentities = []
self.trackerentities.append(self.spotprice.entity)
self.trackerentities.extend(self.options.indoor_tempsensors)
self.trackerentities.extend(self.options.outdoor_tempsensors)
Expand All @@ -68,13 +68,6 @@ async def async_setup_trackers(self):
self.state_machine, self.trackerentities, self._async_on_change
)

def price_below_min(self, hour:datetime) -> bool:
try:
return self.spotprice.model.prices[hour.hour] <= self.sensors.peaqev_facade.min_price
except:
_LOGGER.warning(f"Unable to get price for hour {hour}. min_price: {self.sensors.peaqev_facade.min_price}, num_prices_today: {len(self.spotprice.model.prices)}")
return False

@property
def is_initialized(self) -> bool:
if self._is_initialized:
Expand Down Expand Up @@ -125,11 +118,6 @@ async def call_enable_peaq(self):
async def call_disable_peaq(self):
self.sensors.peaqhvac_enabled.value = False

async def call_set_mode(self, mode):
# match towards enum. set hub to that state.
pass


async def async_get_internal_sensor(self, entity):
lookup = {
LATEST_WATER_BOOST: partial(getattr, self.hvac.water_heater, "latest_boost_call"),
Expand Down
21 changes: 11 additions & 10 deletions custom_components/peaqhvac/service/hub/target_temp.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
def adjusted_tolerances(offset: int, min_tolerance, max_tolerance) -> Tuple[float, float]:
# if abs(offset) <= 1:
return min_tolerance, max_tolerance
_max_tolerance = (
max_tolerance + (offset / 15) if offset > 0 else max_tolerance
)
_min_tolerance = (
min_tolerance + (abs(offset) / 10)
if offset < 0
else min_tolerance
)
return max(_min_tolerance, 0.1), max(_max_tolerance, 0.1)
# _max_tolerance = (
# max_tolerance + (offset / 15) if offset > 0 else max_tolerance
# )
# _min_tolerance = (
# min_tolerance + (abs(offset) / 10)
# if offset < 0
# else min_tolerance
# )
# return max(_min_tolerance, 0.1), max(_max_tolerance, 0.1)


class TargetTemp(ObserverBroadcaster):
Expand Down Expand Up @@ -106,7 +106,8 @@ def _init_tolerances(self, preset: HvacPresets = HvacPresets.Normal):



def _minmax(self, desired_temp) -> float:
@staticmethod
def _minmax(desired_temp) -> float:
if desired_temp < MINTEMP:
return MINTEMP
if desired_temp > MAXTEMP:
Expand Down
53 changes: 30 additions & 23 deletions custom_components/peaqhvac/service/hub/weather_prognosis.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ async def async_update_weather(self, *args):
if ret != self._weather_export_model:
self.observer.broadcast(ObserverTypes.PrognosisChanged)
self._weather_export_model = ret
_LOGGER.debug("Weather-prognosis updated", ret)

async def update_weather_prognosis(self):
try:
Expand Down Expand Up @@ -93,18 +94,15 @@ def get_hvac_prognosis(self, current_temperature: float) -> list:
corrected_temp_delta = 0
now = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)

valid_progs = [
p for idx, p in enumerate(self.prognosis_list) if p.DT >= now
]
valid_progs = [p for idx, p in enumerate(self.prognosis_list) if p.DT >= now]
if len(valid_progs) == 0:
return ret
for p in valid_progs:
c = p.DT - now
if c.seconds == 0:
corrected_temp_delta = round(
self._current_temperature - p.Temperature, 2
)
corrected_temp_delta = round(self._current_temperature - p.Temperature, 2)
continue

temp = self._get_temp(p, corrected_temp_delta, c)
hourdiff = int(c.seconds / 3600)
hour_prognosis = PrognosisExportModel(
Expand All @@ -115,12 +113,14 @@ def get_hvac_prognosis(self, current_temperature: float) -> list:
TimeDelta=hourdiff,
_base_temp = self._current_temperature
)
#_LOGGER.debug(f"Hour prognosis: {hour_prognosis.prognosis_temp}, {hour_prognosis.corrected_temp}, {hour_prognosis.DT}, {hour_prognosis.TimeDelta}")
ret.append(hour_prognosis)

self._hvac_prognosis_list = ret
return ret

def _get_temp(self, p, corrected_temp_delta, c):
@staticmethod
def _get_temp(p, corrected_temp_delta, c):
if 3600 <= c.seconds <= 14400:
decay_factor = 1 / (c.seconds / 3600)
corr = corrected_temp_delta * decay_factor
Expand All @@ -129,6 +129,7 @@ def _get_temp(self, p, corrected_temp_delta, c):
return p.Temperature

def _get_weatherprognosis_hourly_adjustment(self, hour, offset) -> int:
_LOGGER.debug(f"Getting weatherprognosis adjustment for hour {hour} with offset {offset}")
try:
now = datetime.now().replace(hour=hour, minute=0, second=0, microsecond=0)
proghour = now
Expand All @@ -142,31 +143,37 @@ def _get_weatherprognosis_hourly_adjustment(self, hour, offset) -> int:
adjustment_divisor = 2.5 if _next_prognosis.windchill_temp > -2 else 2
adj = (int(round((_next_prognosis.delta_temp_from_now / adjustment_divisor) * divisor, 0)) * -1)
ret = offset + adj
else:
_LOGGER.debug(f"Could not find next prognosis for hour {hour}")
return ret
except Exception as e:
_LOGGER.error(f"Could not get weatherprognosis adjustment: {e}")
return offset

def _set_prognosis(self, import_list: list):
ret = []
for i in import_list:
ret.append(
WeatherObject(
_DTstr=i["datetime"],
WeatherCondition=i["condition"],
Temperature=i["temperature"],
Wind_Speed=i["wind_speed"],
Wind_Bearing=i["wind_bearing"],
Precipitation_Probability=i["precipitation_probability"],
Precipitation=i["precipitation"],
try:
ret = []
for i in import_list:
ret.append(
WeatherObject(
_DTstr=i["datetime"],
WeatherCondition=i["condition"],
Temperature=i["temperature"],
Wind_Speed=i["wind_speed"],
Wind_Bearing=i["wind_bearing"],
Precipitation_Probability=i["precipitation_probability"],
Precipitation=i["precipitation"],
)
)
)
if ret != self.prognosis_list:
self.prognosis_list = ret
self.observer.broadcast(ObserverTypes.PrognosisChanged)
if ret != self.prognosis_list:
self.prognosis_list = ret
self.observer.broadcast(ObserverTypes.PrognosisChanged)
except Exception as e:
_LOGGER.error(f"Could not finalize _set_prognosis: {e}")

@staticmethod
def _correct_temperature_for_windchill(
self, temp: float, windspeed: float
temp: float, windspeed: float
) -> float:
windspeed_corrected = windspeed
ret = 13.12
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
from custom_components.peaqhvac.service.models.enums.demand import Demand
from peaqevcore.common.models.observer_types import ObserverTypes

from custom_components.peaqhvac.service.models.enums.hvacoperations import HvacOperations

_LOGGER = logging.getLogger(__name__)

OFFSET_MIN_VALUE = -10
Expand Down Expand Up @@ -114,8 +116,8 @@ async def async_calculated_offsetdata(self, current_offset: int) -> CalculatedOf
current_temp_trend_offset=temptrend)
if ret != self._calculated_offsetdata:
self._calculated_offsetdata = ret
_LOGGER.debug("Calculated offsetdata updated, so pushing update operation.")
await self.observer.async_broadcast(ObserverTypes.UpdateOperation, None)
# _LOGGER.debug("Calculated offsetdata updated, so pushing update operation.")
# await self.observer.async_broadcast(ObserverTypes.UpdateOperation, (HvacOperations.Offset, ret.sum_values()))
return ret

async def async_update_operation(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,24 +65,6 @@ def helper_get_demand(self) -> Demand:
)
return Demand.ErrorDemand

def _keep_compressor_running(self, offsetdata: CalculatedOffsetModel, force_update: bool) -> bool:
"""in certain conditions, up the offset to keep the compressor running for energy savings"""
dm_zero_prediction = self._hvac.hub.sensors.dm_trend.predicted_time_at_value(0)
now = datetime.now()
if dm_zero_prediction is not None:
if all([
self._hvac.hvac_mode is HvacMode.Heat,
self._hvac.compressor_frequency > 0,
self._hvac.hub.sensors.average_temp_outdoors.value < 0,
dm_zero_prediction < now + timedelta(hours=1)
]):
offsetdata.current_offset += 1
force_update = True
self.aux_offset_adjustments[OffsetAdjustments.KeepCompressorRunning] = 1
else:
self.aux_offset_adjustments[OffsetAdjustments.KeepCompressorRunning] = 0
return force_update

def temporarily_lower_offset(self, offsetdata: CalculatedOffsetModel) -> bool:
if self._wait_timer_breach.is_timeout():
if any([self._lower_offset_threshold_breach(), self._lower_offset_addon()]):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def _check_hvac_fan_speed(self) -> None:
)
self._latest_seen_fan_speed = self._hvac.fan_speed

async def async_check_vent_boost(self, caller=None) -> None:
async def async_check_vent_boost(self, *args) -> None:
if self._hvac.hub.sensors.temp_trend_indoors.samples > 0 and time.time() - self._wait_timer_boost.value > WAITTIMER_VENT:
if self._vent_boost_warmth():
await self.async_vent_boost_start("Vent boosting because of warmth.")
Expand Down
Loading

0 comments on commit 9b91a7d

Please sign in to comment.