Skip to content

Commit

Permalink
More typing fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
bramstroker committed Apr 30, 2023
1 parent a89b716 commit 10c6bc2
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 35 deletions.
22 changes: 11 additions & 11 deletions custom_components/powercalc/sensors/energy.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from homeassistant.components.integration.sensor import IntegrationSensor
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR, TIME_HOURS
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR, TIME_HOURS, UnitOfTime
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.typing import ConfigType
Expand Down Expand Up @@ -145,19 +145,19 @@ class VirtualEnergySensor(IntegrationSensor, EnergySensor):

def __init__(
self,
source_entity,
unique_id,
entity_id,
entity_category,
name,
round_digits,
unit_prefix,
unit_time,
integration_method,
source_entity: str,
unique_id: str | None,
entity_id: str,
entity_category: EntityCategory | None,
name: str | None,
round_digits: int,
unit_prefix: str | None,
unit_time: UnitOfTime,
integration_method: str,
powercalc_source_entity: str,
powercalc_source_domain: str,
sensor_config: ConfigType,
):
) -> None:
super().__init__(
source_entity=source_entity,
name=name,
Expand Down
26 changes: 12 additions & 14 deletions custom_components/powercalc/sensors/power.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def select_calculation_strategy(
"""Select the calculation strategy"""
config_mode = config.get(CONF_MODE)
if config_mode:
return config_mode
return CalculationStrategy(config_mode)

if config.get(CONF_LINEAR):
return CalculationStrategy.LINEAR
Expand Down Expand Up @@ -422,7 +422,7 @@ async def initial_update(event: Event) -> None:
self.async_on_remove(start.async_at_start(self.hass, initial_update))

@callback
def async_update(event_time: datetime | None = None):
def async_update(event_time: datetime | None = None) -> None:
"""Update the entity."""
self.async_schedule_update_ha_state(True)

Expand Down Expand Up @@ -541,12 +541,12 @@ def _switch_sub_profile_dynamically(self, state: State) -> None:

async def calculate_standby_power(self, state: State) -> Decimal:
"""Calculate the power of the device in OFF state"""
sleep_power: ConfigType = self._sensor_config.get(CONF_SLEEP_POWER)
sleep_power: ConfigType = self._sensor_config.get(CONF_SLEEP_POWER) # type: ignore
if sleep_power:
delay = sleep_power.get(CONF_DELAY)

@callback
def _update_sleep_power(_):
def _update_sleep_power(_: Any) -> None:
power = Decimal(sleep_power.get(CONF_POWER))
if self._multiply_factor_standby and self._multiply_factor:
power *= Decimal(self._multiply_factor)
Expand All @@ -559,7 +559,7 @@ def _update_sleep_power(_):

standby_power = self._standby_power
if self._power_calculator.can_calculate_standby():
standby_power = await self._power_calculator.calculate(state)
standby_power = await self._power_calculator.calculate(state) or 0

if self._multiply_factor_standby and self._multiply_factor:
standby_power *= Decimal(self._multiply_factor)
Expand All @@ -574,6 +574,9 @@ async def is_calculation_enabled(self) -> bool:
template = template.replace("[[entity]]", self.source_entity)
template = Template(template)

if not isinstance(template, Template):
return True

template.hass = self.hass
return bool(template.async_render())

Expand All @@ -592,7 +595,7 @@ def available(self) -> bool:
"""Return True if entity is available."""
return self._power is not None

def set_energy_sensor_attribute(self, entity_id: str):
def set_energy_sensor_attribute(self, entity_id: str) -> None:
"""Set the energy sensor on the state attributes"""
if self._sensor_config.get(CONF_DISABLE_EXTENDED_ATTRIBUTES):
return
Expand All @@ -602,18 +605,13 @@ def set_energy_sensor_attribute(self, entity_id: str):


class RealPowerSensor(PowerSensor):
"""Contains a reference to a existing real power sensor entity"""
"""Contains a reference to an existing real power sensor entity"""

def __init__(self, entity_id: str, device_id: str = None, unique_id: str = None):
self._entity_id = entity_id
def __init__(self, entity_id: str, device_id: str | None = None, unique_id: str | None = None) -> None:
self.entity_id = entity_id
self._device_id = device_id
self._unique_id = unique_id

@property
def entity_id(self) -> str:
"""Return the name of the sensor."""
return self._entity_id

@property
def device_id(self) -> str | None:
"""Return the device_id of the sensor."""
Expand Down
19 changes: 10 additions & 9 deletions custom_components/powercalc/strategy/lut.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from decimal import Decimal
from functools import partial
from typing import Union
from gzip import GzipFile

import numpy as np
from homeassistant.components import light
Expand Down Expand Up @@ -40,7 +41,7 @@

class LutRegistry:
def __init__(self) -> None:
self._lookup_dictionaries = {}
self._lookup_dictionaries: dict[str, dict] = {}

async def get_lookup_dictionary(
self, power_profile: PowerProfile, color_mode: ColorMode
Expand Down Expand Up @@ -75,13 +76,13 @@ async def get_lookup_dictionary(
return lookup_dict

@staticmethod
def get_lut_file(power_profile: PowerProfile, color_mode: ColorMode):
def get_lut_file(power_profile: PowerProfile, color_mode: ColorMode) -> GzipFile:
path = os.path.join(power_profile.get_model_directory(), f"{color_mode}.csv")

gzip_path = f"{path}.gz"
if os.path.exists(gzip_path):
_LOGGER.debug("Loading LUT data file: %s", gzip_path)
return gzip.open(gzip_path, "rt")
return gzip.open(gzip_path, "rt") # type: ignore

raise LutFileNotFound("Data file not found: %s")

Expand Down Expand Up @@ -186,23 +187,23 @@ def lookup_power(self, lookup_table: LookupDictType, light_setting: LightSetting
lookup_table[brightness_range[1]], light_setting
),
]
return np.interp(brightness, brightness_range, power_range)
return float(np.interp(brightness, brightness_range, power_range))

def lookup_power_for_brightness(
self, lut_value: Union[LookupDictType, float], light_setting: LightSetting
) -> float:
if light_setting.color_mode == ColorMode.BRIGHTNESS:
return lut_value
return lut_value # type: ignore

if not isinstance(lut_value, dict):
_LOGGER.warning("Cannot calculate power for LutStrategy, expecting a dictionary")
return 0

if light_setting.color_mode == ColorMode.COLOR_TEMP:
return self.get_nearest(lut_value, light_setting.color_temp or 0)
return self.get_nearest(lut_value, light_setting.color_temp or 0) # type: ignore
else:
sat_values = self.get_nearest(lut_value, light_setting.hue or 0)
return self.get_nearest(sat_values, light_setting.saturation or 0)
return self.get_nearest(sat_values, light_setting.saturation or 0) # type: ignore

@staticmethod
def get_nearest(dict: LookupDictType, search_key: int) -> float | LookupDictType:
Expand All @@ -216,7 +217,7 @@ def get_nearest_lower_brightness(dict: LookupDictType, search_key: int) -> int:
keys = dict.keys()
last_key = [*keys][-1]
if last_key < search_key:
return last_key
return int(last_key)

return max(
(k for k in dict.keys() if int(k) <= int(search_key)), default=[*keys][0]
Expand All @@ -227,7 +228,7 @@ def get_nearest_higher_brightness(dict: LookupDictType, search_key: int) -> int:
keys = dict.keys()
first_key = [*keys][0]
if first_key > search_key:
return first_key
return int(first_key)

return min((k for k in keys if int(k) >= int(search_key)), default=[*keys][-1])

Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ warn_redundant_casts = true
warn_unused_configs = true
warn_unused_ignores = true
#enable_error_code = ignore-without-code, redundant-self, truthy-iterable
disable_error_code = typeddict-item
disable_error_code = typeddict-item, arg-type
check_untyped_defs = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
Expand Down

0 comments on commit 10c6bc2

Please sign in to comment.