Coverage for custom_components/appliance_autonotify/totals.py: 93%

109 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-28 12:19 +0000

1"""What a cycle came to: how long it took, the energy it used, and what that cost""" 

2 

3from __future__ import annotations 

4 

5import logging 

6from dataclasses import dataclass 

7from decimal import ROUND_HALF_UP, Decimal 

8from typing import TYPE_CHECKING, Any 

9 

10from homeassistant.components.sensor import ATTR_STATE_CLASS, SensorDeviceClass 

11from homeassistant.const import ATTR_DEVICE_CLASS, ATTR_UNIT_OF_MEASUREMENT, STATE_UNAVAILABLE, STATE_UNKNOWN, UnitOfEnergy 

12from homeassistant.exceptions import HomeAssistantError 

13from homeassistant.helpers import entity_registry as er 

14from homeassistant.util import dt as dt_util 

15from homeassistant.util.unit_conversion import EnergyConverter 

16 

17from .const import DURATION_FORMATS, DURATION_HOURS, DURATION_HOURS_MINUTES, DURATION_MINUTES 

18from .platforms import profile_for 

19 

20if TYPE_CHECKING: 

21 from datetime import datetime, timedelta 

22 

23 from homeassistant.core import HomeAssistant 

24 

25_LOGGER = logging.getLogger(__name__) 

26 

27ENERGY_DOMAIN = "energy" 

28# state classes of a meter that only goes up, best first 

29METER_STATE_CLASSES: tuple[str, ...] = ("total_increasing", "total") 

30# symbols of the commonest currencies, any other being shown by its code 

31CURRENCY_SYMBOLS: dict[str, str] = { 

32 "EUR": "€", 

33 "USD": "$", 

34 "GBP": "£", 

35 "CHF": "CHF", 

36 "JPY": "¥", 

37 "CNY": "¥", 

38 "INR": "₹", 

39 "PLN": "zł", 

40} 

41 

42 

43# languages that write the currency before the amount, such as $0.45, all others writing it after, as 0,45 €, with a 

44# space between where it's written in letters, such as CHF 0.45, and always in Dutch 

45SYMBOL_BEFORE_LANGUAGES: frozenset[str] = frozenset({"en", "zh", "hi", "ja", "ko", "nl"}) 

46 

47 

48# languages that write a decimal point, all others writing a decimal comma 

49DECIMAL_POINT_LANGUAGES: frozenset[str] = frozenset({"en", "ja", "zh", "ko", "th", "he", "hi", "ga", "mt"}) 

50 

51 

52@dataclass(frozen=True) 

53class CycleTotals: 

54 """What a cycle came to, each part None where it isn't known""" 

55 

56 started: datetime | None = None 

57 duration: timedelta | None = None 

58 energy: float | None = None 

59 cost: float | None = None 

60 

61 

62def _language(hass: HomeAssistant) -> str: 

63 return hass.config.language.split("-")[0] 

64 

65 

66def _cents(value: float) -> Decimal: 

67 """Rounded to two places as a person would, half a cent up, not to the nearest float""" 

68 return Decimal(str(round(value, 6))).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) 

69 

70 

71def _number(hass: HomeAssistant, value: float) -> str: 

72 text = str(_cents(value)) 

73 return text if _language(hass) in DECIMAL_POINT_LANGUAGES else text.replace(".", ",") 

74 

75 

76def format_time(when: datetime) -> str: 

77 """The time of day, in Home Assistant's time zone, such as 11:29""" 

78 return dt_util.as_local(when).strftime("%H:%M") 

79 

80 

81def format_duration(hass: HomeAssistant, duration: timedelta) -> str: 

82 """As short as a notification wants it, such as 50 min or 1 h 40 min, in the language of Home Assistant""" 

83 hours, minutes = divmod(max(round(duration.total_seconds() / 60), 1), 60) 

84 formats = DURATION_FORMATS.get(_language(hass), DURATION_FORMATS["en"]) 

85 if not hours: 

86 return formats[DURATION_MINUTES].format(minutes=minutes) 

87 return formats[DURATION_HOURS_MINUTES if minutes else DURATION_HOURS].format(hours=hours, minutes=minutes) 

88 

89 

90def format_energy(hass: HomeAssistant, kwh: float) -> str: 

91 return f"{_number(hass, kwh)} kWh" 

92 

93 

94def format_cost(hass: HomeAssistant, cost: float) -> str: 

95 currency = hass.config.currency 

96 symbol, amount = CURRENCY_SYMBOLS.get(currency, currency), _number(hass, cost) 

97 language = _language(hass) 

98 if language not in SYMBOL_BEFORE_LANGUAGES: 

99 return f"{amount} {symbol}" 

100 return f"{symbol} {amount}" if symbol.isalpha() or language == "nl" else f"{symbol}{amount}" 

101 

102 

103def energy_entity_id(hass: HomeAssistant, device_id: str | None) -> str | None: 

104 """The sensor of the device that adds up the energy it uses, such as a smart plug's, where it has one, rather than 

105 one of the energy used since the last reading or saved, which some appliances have as well""" 

106 if device_id is None: 

107 return None 

108 found: list[tuple[int, str]] = [] 

109 for entry in er.async_entries_for_device(er.async_get(hass), device_id): 

110 if entry.domain != "sensor" or entry.disabled: 

111 continue 

112 state = hass.states.get(entry.entity_id) 

113 device_class = (state.attributes.get(ATTR_DEVICE_CLASS) if state else None) or entry.device_class 

114 device_class = device_class or entry.original_device_class 

115 if device_class != SensorDeviceClass.ENERGY: 

116 continue 

117 state_class = (state.attributes.get(ATTR_STATE_CLASS) if state else None) or (entry.capabilities or {}).get( 

118 ATTR_STATE_CLASS 

119 ) 

120 # only one that adds up, since what another says at the end less what it said at the start means nothing 

121 if state_class in METER_STATE_CLASSES: 

122 found.append((METER_STATE_CLASSES.index(state_class), entry.entity_id)) 

123 return min(found)[1] if found else None 

124 

125 

126def counts_program(hass: HomeAssistant, entity_id: str | None) -> bool: 

127 """Whether the energy sensor counts only the program under way, as Miele's does, rather than adding up all the 

128 energy the device has ever used""" 

129 entry = er.async_get(hass).async_get(entity_id) if entity_id else None 

130 return entry is not None and entry.translation_key in profile_for(entry.platform).program_meter_keys 

131 

132 

133def energy_reading(hass: HomeAssistant, entity_id: str | None) -> float | None: 

134 """The energy meter's reading, in kWh, None if it isn't known""" 

135 state = hass.states.get(entity_id) if entity_id else None 

136 if state is None or state.state in (STATE_UNAVAILABLE, STATE_UNKNOWN): 

137 return None 

138 try: 

139 return EnergyConverter.convert( 

140 float(state.state), 

141 state.attributes.get(ATTR_UNIT_OF_MEASUREMENT, UnitOfEnergy.KILO_WATT_HOUR), 

142 UnitOfEnergy.KILO_WATT_HOUR, 

143 ) 

144 except ValueError, HomeAssistantError: 

145 return None 

146 

147 

148def _price_of(hass: HomeAssistant, source: dict[str, Any]) -> float | None: 

149 """The price per kWh of a grid source, from an entity or as a number""" 

150 if number := source.get("number_energy_price"): 

151 return float(number) 

152 entity_id = source.get("entity_energy_price") 

153 state = hass.states.get(entity_id) if entity_id else None 

154 if state is None: 

155 return None 

156 try: 

157 price = float(state.state) 

158 except ValueError: 

159 return None 

160 # priced per kWh, unless the entity says otherwise 

161 unit = str(state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) or "").rsplit("/", 1)[-1] 

162 if unit in EnergyConverter.VALID_UNITS and unit != UnitOfEnergy.KILO_WATT_HOUR: 

163 price /= EnergyConverter.convert(1, unit, UnitOfEnergy.KILO_WATT_HOUR) 

164 return price 

165 

166 

167async def energy_price(hass: HomeAssistant) -> float | None: 

168 """The price of a kWh from the grid, as set on the Energy dashboard, None where there's none set""" 

169 if ENERGY_DOMAIN not in hass.config.components: 

170 return None 

171 from homeassistant.components.energy.data import async_get_manager 

172 

173 try: 

174 manager = await async_get_manager(hass) 

175 except Exception: 

176 _LOGGER.debug("APPLIANCES No energy settings to price a cycle with", exc_info=True) 

177 return None 

178 # read as plain dicts, since the shape of a grid source has changed between releases of Home Assistant 

179 settings: dict[str, Any] = dict(manager.data or {}) 

180 sources: list[dict[str, Any]] = settings.get("energy_sources", []) 

181 for source in sources: 

182 if source.get("type") != "grid": 

183 continue 

184 # one price per grid connection, or, as Home Assistant used to have them, one per meter 

185 for priced in [source, *source.get("flow_from", [])]: 

186 if (price := _price_of(hass, priced)) is not None: 

187 return price 

188 return None