Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
# Conflicts:
#	custom_components/peaqev/manifest.json
  • Loading branch information
magnuselden authored and magnuselden committed Mar 24, 2023
2 parents c931942 + df4ed5e commit 4838365
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 57 deletions.
6 changes: 2 additions & 4 deletions custom_components/peaqev/peaqservice/charger/charger.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,15 @@ async def _post_start_charger(self) -> None:
if self._charger.servicecalls.options.allowupdatecurrent and not self.hub.is_free_charge:
self.hub.state_machine.async_create_task(self._updatemaxcurrent())

async def _terminate_charger(self, debugmessage: str = None) -> None:
_LOGGER.debug(debugmessage)
async def _terminate_charger(self) -> None:
if self._call_ok():
await self.hub.state_machine.async_add_executor_job(self.session.core.terminate)
await self._update_internal_state(ChargerStates.Stop)
self.session_active = False
await self._call_charger(CallTypes.Off)
await self.hub.observer.async_broadcast("update charger done", True)

async def _pause_charger(self, debugmessage: str = None) -> None:
_LOGGER.debug(debugmessage)
async def _pause_charger(self) -> None:
if self._call_ok():
if self.hub.charger_done or self.params.chargecontroller_state is ChargeControllerStates.Idle:
await self._terminate_charger()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def get_allowed_amps(self) -> int:
if ret is not None:
return int(ret.state)
else:
_LOGGER.warning(f"Unable to get max amps. The sensor {self.entities.maxamps} returned state None. Setting max amps to 16 til I get a proper state.")
_LOGGER.debug(f"Unable to get max amps. The sensor {self.entities.maxamps} returned state None. Setting max amps to 16 til I get a proper state.")
return 16

def _validate_sensor(self, sensor: str) -> bool:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@

from peaqevcore.services.threshold.threshold import Threshold
from peaqevcore.services.threshold.threshold_lite import ThresholdLite
from peaqevcore.services.threshold.thresholdbase import ThresholdBase


class ThresholdFactory:
@staticmethod
def create(hub):
def create(hub) -> ThresholdBase:
if hub.options.peaqev_lite:
return ThresholdLite(hub)
return Threshold(hub)
41 changes: 13 additions & 28 deletions custom_components/peaqev/peaqservice/hub/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,11 @@ def __init__(
self.initializer = HubInitializer(self) #top level
self.gainloss = GainLoss(self) #power

tracker_entities = []

if not options.peaqev_lite:
tracker_entities.append(self.options.powersensor)
tracker_entities.append(self.sensors.totalhourlyenergy.entity)

self.chargingtracker_entities = []
trackers = self.__setup_tracking()
async_track_state_change(hass, trackers, self.state_changed)
self._set_observers()

self.chargingtracker_entities = self._set_chargingtracker_entities()
tracker_entities += self.chargingtracker_entities
async_track_state_change(hass, tracker_entities, self.state_changed)

@property
def enabled(self) -> bool:
return self.sensors.charger_enabled.value
Expand Down Expand Up @@ -160,6 +153,15 @@ def watt_cost(self) -> int:
return 0
return 0

def __setup_tracking(self) -> list:
tracker_entities = []
if not self.options.peaqev_lite:
tracker_entities.append(self.options.powersensor)
tracker_entities.append(self.sensors.totalhourlyenergy.entity)
self.chargingtracker_entities = self._set_chargingtracker_entities()
tracker_entities += self.chargingtracker_entities
return tracker_entities

"""Composition below here"""
def get_power_sensor_from_hass(self) -> float|None:
ret = self.state_machine.states.get(self.options.powersensor)
Expand All @@ -184,47 +186,30 @@ def prices(self) -> list:
return self.hours.prices
return []

@prices.setter
def prices(self, val) -> None:
if self.options.price.price_aware:
if self.hours.prices != val:
_LOGGER.debug(f"setting today's prices with: {val}")
self.hours.prices = val

@property
def prices_tomorrow(self) -> list:
if self.options.price.price_aware:
return self.hours.prices_tomorrow
return []

@prices_tomorrow.setter
def prices_tomorrow(self, val) -> None:
if self.options.price.price_aware:
if self.hours.prices_tomorrow != val:
_LOGGER.debug(f"setting tomorrow's prices with: {val}")
self.hours.prices_tomorrow = val

@property
def is_free_charge(self) -> bool:
if hasattr(self.sensors, "locale"):
return self.sensors.locale.data.free_charge(self.sensors.locale.data)
return False

def _update_prices(self, prices: list) -> None:
self.prices = prices[0]
self.prices_tomorrow = prices[1]
self.hours.update_prices(prices[0], prices[1])

def _update_average_monthly_price(self, val) -> None:
_LOGGER.debug(f"got new monthly average price {val}")
if self.options.price.price_aware and isinstance(val, float):
self.hours.update_top_price(val)
self.hours._core.update()

def _update_average_weekly_price(self, val) -> None:
_LOGGER.debug(f"got new weekly average price {val}")
if self.options.price.price_aware and isinstance(val, float):
self.hours.adjusted_average = val
self.hours._core.update()

@property
def charger_done(self) -> bool:
Expand Down
28 changes: 16 additions & 12 deletions custom_components/peaqev/peaqservice/hub/nordpool/nordpool.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class NordPoolUpdater:
def __init__(self, hub, is_active: bool = True):
self.model = NordPoolModel()
self.hub = hub
self._nordpool_entity: str = None
if is_active:
self._setup_nordpool()

Expand Down Expand Up @@ -47,18 +48,20 @@ def average_data(self) -> list:
return self.model.average_data

@property
def average_ready(self) -> bool:
return len(self.model.average_data) >= AVERAGE_MAX_LEN
def nordpool_entity(self) -> str:
return self._nordpool_entity

async def update_nordpool(self):
ret = self.hub.state_machine.states.get(self.nordpool_entity)
_result = NordpoolDTO()
if ret is not None:
await _result.set_model(ret)
if await self._update_set_prices(_result):
await self.hub.observer.async_broadcast("prices changed",[self.model.prices, self.model.prices_tomorrow])
elif self.hub.is_initialized:
_LOGGER.error("Could not get nordpool-prices")
if self.nordpool_entity is not None:
ret = self.hub.state_machine.states.get(self.nordpool_entity)
_result = NordpoolDTO()
if ret is not None:
await _result.set_model(ret)
if await self._update_set_prices(_result):
await self.hub.observer.async_broadcast("prices changed",
[self.model.prices, self.model.prices_tomorrow])
elif self.hub.is_initialized:
_LOGGER.error("Could not get nordpool-prices")

async def _update_average_month(self) -> None:
_new = await self._get_average_async(datetime.now().day)
Expand Down Expand Up @@ -99,7 +102,7 @@ def _setup_nordpool(self):
if len(list(entities)) < 1:
raise Exception("no entities found for Nordpool.")
if len(list(entities)) == 1:
self.nordpool_entity = entities[0]
self._nordpool_entity = entities[0]
_LOGGER.debug(f"Nordpool has been set up and is ready to be used with {self.nordpool_entity}")
asyncio.run_coroutine_threadsafe(
self.update_nordpool(), self.hub.state_machine.loop
Expand All @@ -109,7 +112,8 @@ def _setup_nordpool(self):
_LOGGER.error(f"more than one Nordpool entity found. Disabling Priceawareness until reboot of HA.")
except Exception as e:
self.hub.options.price.price_aware = False # todo: composition
_LOGGER.error(f"Peaqev was unable to get a Nordpool-entity. Disabling Priceawareness until reboot of HA: {e}")
_LOGGER.error(
f"Peaqev was unable to get a Nordpool-entity. Disabling Priceawareness until reboot of HA: {e}")

async def import_average_data(self, incoming: list):
if isinstance(incoming, list):
Expand Down
12 changes: 10 additions & 2 deletions custom_components/peaqev/peaqservice/hub/servicecalls.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,17 @@ async def call_schedule_needed_charge(
schedule_starttime: str = None,
override_settings: bool = False
):
dep_time = datetime.strptime(departure_time, '%y-%m-%d %H:%M')
dep_time = None
start_time = None
try:
dep_time = datetime.strptime(departure_time, '%Y-%m-%d %H:%M')
except ValueError:
_LOGGER.error(f"Could not parse departure time: {departure_time}")
if schedule_starttime is not None:
start_time = datetime.strptime(schedule_starttime, '%y-%m-%d %H:%M')
try:
start_time = datetime.strptime(schedule_starttime, '%Y-%m-%d %H:%M')
except ValueError:
_LOGGER.error(f"Could not parse schedule start time: {schedule_starttime}")
else:
start_time = datetime.now()
_LOGGER.debug(f"scheduler params. charge: {charge_amount}, dep-time: {dep_time}, start_time: {start_time}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@ def __init__(self, hub):

async def update_sensor(self, entity, value):
update_session = await self._update_sensor(entity, value)
if self.hub.options.price.price_aware is True:
if self.hub.options.price.price_aware:
if entity != self.hub.nordpool.nordpool_entity and (not self.hub.hours.is_initialized or time.time() - self.latest_nordpool_update > 60):
"""tweak to provoke nordpool to update more often"""
self.latest_nordpool_update = time.time()
await self.hub.nordpool.update_nordpool()
await self._handle_sensor_attribute()
if self.hub.charger.session_active and update_session and hasattr(self.hub.sensors, "carpowersensor"):
self.hub.charger.session.session_energy = self.hub.sensors.carpowersensor.value
if self.hub.options.price.price_aware is True:
if self.hub.options.price.price_aware:
self.hub.charger.session.session_price = float(self.hub.nordpool.state)
if self.hub.scheduler.schedule_created is True:
if self.hub.scheduler.schedule_created:
self.hub.scheduler.update()
if entity in self.hub.chargingtracker_entities and self.hub.is_initialized:
await self.hub.charger.charge()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ async def _update_sensor(self, entity, value) -> bool:
case self.hub.sensors.powersensormovingaverage24.entity:
self.hub.sensors.powersensormovingaverage24.value = value
case self.hub.nordpool.nordpool_entity:
await self.hub.nordpool.update_nordpool()
update_session = True
if self.hub.options.price.price_aware:
await self.hub.nordpool.update_nordpool()
update_session = True
return update_session

async def _handle_outlet_updates(self):
Expand Down Expand Up @@ -87,7 +88,8 @@ async def _update_sensor(self, entity, value) -> bool:
case self.hub.sensors.totalhourlyenergy.entity:
await self._update_total_energy_and_peak(value)
case self.hub.nordpool.nordpool_entity:
await self.hub.nordpool.update_nordpool()
if self.hub.options.price.price_aware:
await self.hub.nordpool.update_nordpool()
return False

async def _handle_outlet_updates(self):
Expand Down Expand Up @@ -127,8 +129,9 @@ async def _update_sensor(self, entity, value) -> bool:
case self.hub.sensors.powersensormovingaverage24.entity:
self.hub.sensors.powersensormovingaverage24.value = value
case self.hub.nordpool.nordpool_entity:
await self.hub.nordpool.update_nordpool()
update_session = True
if self.hub.options.price.price_aware:
await self.hub.nordpool.update_nordpool()
update_session = True
return update_session

class StateChangesLiteNoCharger(IStateChanges):
Expand All @@ -142,7 +145,8 @@ async def _update_sensor(self, entity, value) -> bool:
case self.hub.sensors.totalhourlyenergy.entity:
await self._update_total_energy_and_peak(value)
case self.hub.nordpool.nordpool_entity:
await self.hub.nordpool.update_nordpool()
if self.hub.options.price.price_aware:
await self.hub.nordpool.update_nordpool()
return False


0 comments on commit 4838365

Please sign in to comment.