Adds migrations.py with automatic entity registry migration for renamed
sensor keys. Separated from coordinator/repairs.py (runtime issues) and
__init__.py _migrate_config_options() (config format changes).
- ENTITY_KEY_RENAMES dict maps old→new entity keys (extensible)
- _auto_migrate_entity_keys() updates unique_id, preserves entity_id
- Handles partial migration (new entity already exists → remove old)
- Creates persistent HA repair issue after migration via ir.async_create_issue()
- Called in async_setup_entry() after _migrate_config_options()
Migrates: trend_change_in_minutes → next_price_trend_change_in
Repair issue informs users about:
- Auto-migrated entity renames (entity_id preserved, no action needed)
- Duration sensor value unit change (hours → minutes): update automation
thresholds from `state < 0.25` to `state < 15` for 15-minute checks
All 5 language files (en, de, nb, nl, sv) updated with translations.
BREAKING CHANGE: Duration sensors (remaining time, starts in, period
duration, trend change countdown) now report state values in minutes
instead of hours. Display unit in dashboards remains hours by default.
Update numeric comparisons in automations accordingly.
Impact: Users upgrading from previous releases see an informational
repair notice guiding them through any required automation updates.
Entity renames are handled transparently with no loss of history.
Replaced int(time.minutes_until()) with time.minutes_until_rounded()
in trend calculator (3 locations). The int() call truncated values
(14.7 → 14) while timing sensors used standard rounding (14.7 → 15).
All duration sensors now use the same rounding method
(math.floor(seconds/60 + 0.5)), matching HA's timestamp rendering
behavior.
Impact: Trend countdown values may differ by ±1 minute compared to
previous behavior. Consistency across all duration sensors improved.
Changed native_unit_of_measurement from HOURS to MINUTES for all 7
duration sensors. HA auto-converts to hours for display via
suggested_unit_of_measurement=HOURS.
Sensors affected:
- next_price_trend_change_in
- best_price_period_duration, best_price_remaining_minutes,
best_price_next_in_minutes
- peak_price_period_duration, peak_price_remaining_minutes,
peak_price_next_in_minutes
Removed _minutes_to_hours() conversion function — calculator values
(minutes) are now passed through directly.
BREAKING CHANGE: State values for all duration sensors change from
hours to minutes (e.g. 1.5 → 90). The display unit remains hours
(suggested_unit_of_measurement). Automations using numeric state
comparisons must be updated (multiply old thresholds by 60).
Impact: Users with automations comparing duration sensor states
numerically need to update thresholds. Dashboard display is unchanged
for new installations. Existing installations retain their configured
display unit but the underlying numeric value changes.
Renamed trend_change_in_minutes → next_price_trend_change_in to align
with its sibling sensor next_price_trend_change (timestamp variant).
Follows the established best/peak price naming pattern where related
sensors share a common prefix (e.g. best_price_next_start_time /
best_price_next_in_minutes).
Updated entity key, translation key, friendly names (all 5 languages),
custom translations, coordinator constants, attribute routing, and
cache-clear mapping.
BREAKING CHANGE: Entity ID changes from
sensor.<home>_trend_change_in_minutes to
sensor.<home>_next_price_trend_change_in. Automations and dashboards
referencing the old entity ID must be updated.
Impact: Users with automations or dashboard cards referencing the old
sensor name need to update references. The sensor retains identical
functionality and attributes.
Skip expensive async_write_ha_state() when native_value hasn't changed
since last write. HA's state machine has built-in change detection, but
it only runs AFTER all properties and attributes are evaluated — the
expensive part we now avoid entirely.
Sensor platform (Timer #2 + #3):
- New _write_if_changed() method compares native_value before writing
- Timer #3 (30s, 7 entities): Skips all writes when no period active
- Timer #2 (15min, ~45 entities): Skips enum levels/ratings that stay
constant across quarter-hour intervals
- Replaces data_lifecycle_status-only pattern with unified approach
Binary sensor platform (Timer #2):
- Period sensors only write at actual period boundaries, not every 15min
Coordinator push updates always write (sentinel reset ensures freshness).
Impact: Eliminates asyncio "Executing TimerHandle took 1.4s" warnings
caused by redundant property evaluation in Timer #3 callbacks. Reduces
event loop blocking from ~1.4s to microseconds when values unchanged.
Add four optional parameters to the get_chartdata service:
- include_energy: Include raw energy/spot price (default: false)
- include_tax: Include tax component (default: false)
- energy_field: Custom field name (default: energy_price)
- tax_field: Custom field name (default: tax)
Custom field names allow direct compatibility with ApexCharts
and other charting tools without post-processing.
All code paths (all/segments/none insert_nulls modes) and the
last-interval handler include energy/tax when enabled.
Added translations for all 5 languages (en, de, nl, nb, sv).
Impact: Users can include price composition data in chart exports,
enabling visual breakdowns of energy cost vs. taxes in dashboards.
Add energy_price and tax attributes to interval and daily stat sensors:
- Interval sensors (current/next/previous): energy_price and tax from
the specific 15-minute interval
- Daily min/max sensors: energy_price and tax from the extreme interval
- Daily average sensors: energy_price_mean, energy_price_median,
tax_mean, tax_median — matching the existing mean/median pattern
used for the main price attribute
Calculator caches both mean and median for energy/tax using
calculate_median() from utils/average. All new attributes are
excluded from Recorder to prevent database bloat.
Impact: Users can see price composition (spot price vs. taxes) on
all major price sensors. Enables solar feed-in and net metering
automations based on raw energy prices.
Request `energy` and `tax` fields alongside `total` in both
quarter-hourly price queries. These represent the raw spot price and
the tax/fee component that together make up the total consumer price.
Updated hourly aggregation in formatters.py to carry energy/tax
values through to aggregated output.
Impact: Enables downstream consumers (sensors, services) to expose
price composition data. Useful for solar feed-in compensation and
net metering (saldering) calculations where the raw energy price
is needed separately from taxes.
Added brand/ directory to custom_components/tibber_prices/ with all
8 supported PNG variants, generated from existing SVGs in images/:
- icon.png / dark_icon.png (256×256)
- icon@2x.png / dark_icon@2x.png (512×512)
- logo.png / dark_logo.png (500×128)
- logo@2x.png / dark_logo@2x.png (1000×256)
Local brand images automatically take priority over CDN images and
are served via the HA brands proxy API (/api/brands/integration/).
Silently ignored on HA < 2026.3, no changes to manifest.json needed.
Updated AGENTS.md to document the brand/ directory under "ALLOWED in root".
Impact: Integration icon and logo now display correctly in HA ≥ 2026.3
without requiring a separate submission to the HA brands repository.
Renamed 8 price_trend_Xh entries to price_outlook_Xh and added 15 new
price_trajectory_Xh entries (2h–12h) in all 5 languages (de, en, nb, nl, sv).
translations/ (HA-native: name + 5 states per sensor):
- EN: "Price Outlook (Xh)" / "Price Trajectory (Xh)"
- DE: "Preisausblick (Xh)" / "Preisverlauf (Xh)"
- NB: "Prisutblikk (Xt)" / "Prisforløp (Xt)"
- NL: "Prijsvooruitzicht (Xu)" / "Prijstrajectorie (Xu)"
- SV: "Prisöversikt (Xh)" / "Prisutveckling (Xh)"
custom_translations/ (description + long_description + usage_tips):
- Outlook descriptions updated to explain window-average comparison
semantics (not price direction)
- Trajectory descriptions explain first-half vs second-half logic and
the "outlook: falling + trajectory: rising = you're AT the minimum" pattern
- Trajectory long_description and usage_tips in English for all languages;
description field in native language
Impact: Entity display names update to reflect the corrected semantic meaning.
Renamed 8 sensors to clarify what they actually measure, and added 7 new
sensors for a different (and often more useful) calculation.
--- WHY THE RENAME ---
The old name "price_trend_Xh" implied the sensor shows where prices are
heading. It doesn't — it compares CURRENT price vs the FUTURE WINDOW AVERAGE.
At a price minimum, it shows "strongly_falling" (because the cheap minimum
pulls the average below your current high price), which is the opposite of
intuitive. The name "price_outlook_Xh" correctly conveys: "is now cheaper
or more expensive than the next Nh on average?"
--- NEW: price_trajectory_Xh ---
These sensors compare FIRST HALF vs SECOND HALF of the window, revealing
actual price direction within the window:
price_trajectory_2h: avg(hour 1) vs avg(hour 2)
price_trajectory_3h: avg(first 1.5h) vs avg(second 1.5h)
price_trajectory_4h: avg(first 2h) vs avg(second 2h)
price_trajectory_5h: avg(first 2.5h) vs avg(second 2.5h)
price_trajectory_6h: avg(first 3h) vs avg(second 3h)
price_trajectory_8h: avg(first 4h) vs avg(second 4h)
price_trajectory_12h: avg(first 6h) vs avg(second 6h)
The key use case: at a price minimum, price_outlook_Xh shows "strongly_falling"
but price_trajectory_Xh shows "rising" — correctly revealing the upcoming
reversal. "outlook: falling + trajectory: rising" = you're AT the minimum.
--- IMPLEMENTATION ---
sensor/calculators/trend.py:
- get_price_outlook_value() (was: get_price_trend_value())
- New: get_price_trajectory_value(*, hours: int)
- New: _calculate_first_half_average(hours, next_interval_start)
- New: get_trajectory_attributes() → first_half_avg, second_half_avg, half_diff_%
- clear_trend_cache() also resets _trajectory_attributes
sensor/definitions.py:
- 8 SensorEntityDescription entries: key/translation_key price_trend_Xh → price_outlook_Xh
- New PRICE_TRAJECTORY_SENSORS tuple (2h–5h enabled by default, 6h/8h/12h disabled)
sensor/value_getters.py:
- 8 lambda entries renamed
- 7 new trajectory lambda entries added
sensor/attributes/trend.py:
- startswith("price_trend_") → startswith("price_outlook_")
- New elif branch routing price_trajectory_* to cached trajectory_attributes
sensor/core.py:
- startswith checks updated for both prefix families
- cached_data dict extended with "trajectory_attributes"
coordinator/constants.py:
- TIME_SENSITIVE_ENTITY_KEYS: 8 renamed + 7 new trajectory keys added
config_flow_handlers/entity_check.py:
- volatility + price_trend affected-entity lists: 8 renamed + 7 new
BREAKING CHANGE: Sensors price_trend_1h, price_trend_2h, price_trend_3h,
price_trend_4h, price_trend_5h, price_trend_6h, price_trend_8h,
price_trend_12h have been removed without a deprecation period.
Migration:
Replace price_trend_Xh → price_outlook_Xh everywhere (automations,
dashboards, templates). Behavior is identical — only the entity name
changed. If you want to detect actual price direction within the window
(e.g. "are prices rising or falling right now?"), use the new
price_trajectory_Xh sensors instead.
Impact: Users must update automations and dashboards. Entity IDs change from
sensor.<home>_price_trend_Xh to sensor.<home>_price_outlook_Xh. New
price_trajectory_Xh sensors provide complementary direction information.
Added `suggested_unit_of_measurement=UnitOfTime.HOURS` to all 7 DURATION
sensors to prevent HA from auto-selecting minutes as the display unit.
Without this, HA would pick "min" for small values (e.g., 0.75 h) and then
display large values as "1238 Min." instead of the intended "20 Std. 38 Min."
Affected sensors:
- trend_change_in_minutes
- best_price_period_duration / peak_price_period_duration
- best_price_remaining_minutes / peak_price_remaining_minutes
- best_price_next_in_minutes / peak_price_next_in_minutes
BREAKING CHANGE: Sensor state unit changes from minutes to hours for users
whose entity registry stored "min" as the display unit (the previous default).
Automations using the raw state value (e.g., `state < 60` for "less than 60
minutes") must be updated to use hours (e.g., `state < 1`).
The state attributes `remaining_minutes` and `next_in_minutes` continue to
provide integer minutes and are unaffected.
Impact: Duration sensors now display dynamically as "X h Y min" (e.g.,
"1 h 15 min") instead of a large minutes value like "1238 Min.". Users who
manually customized the unit in HA settings are not affected.
Added 3 new config fields to price trend options step:
- Trend Change Confirmation (2-6 intervals slider)
- Min Price Change for trend (display-unit-aware slider)
- Min Price Change for strong trend (display-unit-aware slider)
Price change sliders scale between base currency (EUR/NOK) storage and
display unit (ct/øre) presentation using get_display_unit_factor().
Added migration in __init__.py to convert old display-unit values to
base currency format.
Impact: Users can tune trend sensitivity: higher confirmation = fewer
false changes, higher min price change = no trends from tiny fluctuations.
New duration sensor showing time until next price trend change as hours
(e.g., 2.25 h). Registered in MINUTE_UPDATE_ENTITY_KEYS for per-minute
updates. Shares cached attributes with next_price_trend_change timestamp
sensor.
Added trend attributes to _unrecorded_attributes (threshold/volatility/diff
attributes excluded from recorder). Updated timer group size test expectation
from 6 to 7.
Impact: Users can display a live countdown to the next trend change on
dashboards and use it in automations (e.g., "if < 0.25 h, prepare").
Refactored trend calculator with direction-group-based trend change detection
(rising/strongly_rising treated as same group, falling/strongly_falling as same
group). Added minimum absolute price change thresholds (noise floor) to prevent
spurious trends at low price levels. Both percentage AND absolute conditions
must now be met.
Updated strongly threshold defaults from ±6% to ±9% (3x base for perceptual
scaling). Added missing strongly thresholds and new config keys to
get_default_options(). calculate_price_trend() now returns volatility_factor
as 4th tuple element for threshold transparency.
Added CONF_PRICE_TREND_CHANGE_CONFIRMATION (default: 3 intervals = 45min)
and CONF_PRICE_TREND_MIN_PRICE_CHANGE / _STRONGLY with validation limits.
Updated tests for new 4-tuple return value.
Impact: More stable trend detection — fewer false trend changes during low-price
periods. Direction-group logic prevents noise from "rising ↔ strongly_rising"
oscillations. Users can fine-tune noise floor for their market.
- Move UTC import from inline (inside _has_real_gaps_in_range) to
module-level in manager.py
- Hoist get_fetch_groups() out of while loop in _get_cached_intervals:
eliminates ~384 function calls per invocation
- Pre-compute criteria_by_day dict in build_periods before the for-loop:
eliminates ~381 redundant NamedTuple constructions per call; only
ref_price/avg_price vary by day (max 3 entries), flex/min_distance/
reverse_sort are constant throughout
Impact: Reduces unnecessary object creation during the hot paths called
every 15 minutes and during all relaxation phases.
PLW0108: Three lambdas were simple pass-throughs that added no value:
lambda data: aggregate_level_data(data) → aggregate_level_data
lambda: lifecycle_calculator.get_lifecycle_state() → lifecycle_calculator.get_lifecycle_state
Affected files:
sensor/calculators/rolling_hour.py (line 115)
sensor/helpers.py (line 139)
sensor/value_getters.py (line 220)
Impact: No behaviour change. Linter now passes with zero warnings.
Four non-MONETARY diagnostic sensors had state_class set, causing HA
Recorder to add them to long-term statistics tables unnecessarily:
- home_size (m²): SensorStateClass.MEASUREMENT
- main_fuse_size (A): SensorStateClass.MEASUREMENT
- number_of_residents: SensorStateClass.MEASUREMENT
- estimated_annual_consumption(kWh):SensorStateClass.TOTAL
All four are static user metadata retrieved from Tibber's user API
(cached for 24 h, rarely or never changes in practice). They carry no
time-series value: home_size and main_fuse_size don't change, and
estimated_annual_consumption is a rough Tibber estimate, not an actual
accumulating energy counter.
Setting state_class=None removes them from long-term statistics while
keeping normal state-change recording intact.
The three intentional non-None state_class values are unchanged:
- current_interval_price (MONETARY, TOTAL): Energy Dashboard
- current_interval_price_base (MONETARY, TOTAL): Energy Dashboard
- average_price_today (MONETARY, TOTAL): useful weekly/monthly trend
Impact: Reduced Recorder database growth; no user-visible sensor
behaviour change.
The timedelta import move (previous commit) was committed correctly, but a
subsequent automated formatting pass stripped the line that used it:
current_date = current_date + timedelta(days=1)
Without the increment the while loop never terminates, causing HA to hang
indefinitely during coordinator startup when period calculation is triggered.
Additionally, the timedelta module-level import was also reverted by the
same pass, so re-add it here.
Restore both the import and the loop increment so group_periods_by_day
correctly iterates one day at a time.
PLC0415 – suppress with noqa was already suppressing the warning, but the
import was still executed on every iteration of the while loop. Standard
library imports belong at module level both for correctness and performance.
Move 'from datetime import timedelta' to the top-level import block and
remove the now-unnecessary 'noqa: PLC0415' comment.
Impact: Negligible per-call overhead removed. More importantly, the code
no longer suppresses a linter warning that signals a real anti-pattern;
future static analysis runs will correctly flag any new inline imports.
RESOLUTION_CHANGE_ISO was a naive ISO string ("2025-10-01T00:00:00").
_split_at_resolution_boundary compared it against timezone-aware interval
strings via plain string ordering, which is unreliable when the strings
carry different UTC offsets (e.g. +02:00 vs +00:00). More critically,
the naive string was then split into ranges such as ("...", "2025-10-01T00:00:00")
which were parsed back to naive datetime objects in fetch_missing_ranges.
When routing.py then compared those naive objects against the tz-aware
boundary datetime, Python raised TypeError: can't compare offset-naive
and offset-aware datetimes.
Fix:
- Remove RESOLUTION_CHANGE_ISO; derive the boundary ISO string at
runtime from RESOLUTION_CHANGE_DATETIME.isoformat(), which produces
the UTC-normalised string "2025-10-01T00:00:00+00:00".
- Rewrite _split_at_resolution_boundary to parse each range's start/end
to datetime objects, normalise any defensively-naive values to UTC,
and compare against the RESOLUTION_CHANGE_DATETIME constant directly.
- Use the tz-aware boundary_iso string as the split point so downstream
fromisoformat() calls always return tz-aware datetime objects.
Impact: Ranges spanning 2025-10-01T00:00:00 UTC are now split correctly
regardless of the UTC offset carried by the original interval strings,
and no TypeError is raised when routing.py compares the boundary
endpoints to its own tz-aware boundary calculation.
On DST fall-back nights the clocks repeat an hour (e.g. 02:00 CET/CEST).
Tibber delivers quarter-hourly intervals for both the CEST (+02:00) and
CET (+01:00) copies of that hour. Both share the same 19-char naive local
key 'YYYY-MM-DDTHH:MM:SS', so _add_intervals treated the CET arrivals as
unwanted duplicates and sent them to _touch_intervals, which kept the CEST
data and silently discarded the CET price data. The fall-back hour's prices
were permanently lost from the pool.
Fix:
- Add module constant _DST_COLLISION_MAX_SAME_UTC_S (60 s) to distinguish
true duplicate arrivals (same UTC, ≤60 s apart) from DST collision pairs
(~3600 s apart).
- Add _handle_index_collision() helper that compares the UTC datetimes of
the existing and incoming interval. If they differ by more than the
threshold it stores the new interval in self._dst_extras keyed by the
normalised local timestamp and returns True.
- _add_intervals delegates every collision to _handle_index_collision and
only routes to touch when it returns False (true duplicate).
- _get_cached_intervals yields the saved extras after the main interval.
- After each GC run, stale entries are pruned from _dst_extras.
- to_dict / from_dict persist and restore _dst_extras across HA restarts.
Impact: The full fall-back hour (e.g. 02:00-02:45 CET) now appears in the
interval pool alongside the CEST copies, so sensors that query that hour
return correct prices instead of stale or missing data.
_get_sensor_interval_stats() computed expected_count via UTC time
arithmetic ((end - start).total_seconds() / 900 = 480 for 5 days), then
iterated through fixed-offset local timestamps adding timedelta(minutes=15).
On DST spring-forward days (e.g. last Sunday March in EU), clocks skip
from 02:00 to 03:00. The 4 local quarter-hour slots 02:00-02:45 never
exist, so the Tibber API never returns intervals for them. The iteration
still visits those 4 keys, finds them absent from the index, and reports
has_gaps=True (expected=480, actual=476). Since no API call can ever
fill those non-existent slots, the pool triggers an unnecessary gap-fill
fetch every 15 minutes for the entire spring-forward day.
Fix: keep the nominal expected_count for diagnostics, but determine
has_gaps via the new _has_real_gaps_in_range() helper that sorts
cached intervals by UTC time and checks consecutive UTC differences.
The 01:45+01:00 -> 03:00+02:00 transition is exactly 15 minutes in
UTC, so no gap is reported. Start/end boundary comparisons use naive
19-char local timestamps to stay consistent with the fixed-offset
arithmetic used by get_protected_range().
Impact: No spurious API fetches on DST spring-forward Sunday. Gap
detection for real missing data (API failures, first startup) remains
fully functional.
All three re-transform sites (_handle_options_update,
async_handle_config_override_update, _perform_midnight_data_rotation)
were building raw_data with only {'price_info': ...}, omitting
'currency' and 'home_id'.
data_transformation.py's transform_data() falls back to currency='EUR'
and home_id='' when those keys are missing. This caused all non-EUR
users (Norway/NOK, Sweden/SEK) to see wrong currency units in sensors
after every midnight turnover and after any options/override change,
until the next full API poll refilled coordinator.data with correct
values (up to 15 minutes of wrong units).
Fix: explicitly carry over coordinator.data's existing currency and
home_id into each raw_data dict. Also inline the redundant lambda
wrapper on calculate_periods_fn (PLW0108 ruff lint).
Impact: Norwegian and Swedish users no longer see EUR/ct units after
midnight or config changes. Sensor unit-of-measurement stays consistent
throughout the day regardless of re-transform triggers.
All entity descriptions had hardcoded English name= strings that were
never used at runtime: HA always prefers translations via translation_key
(entity.<platform>.<key>.name in translations/en.json), making the name=
fields dead code.
Removed 106 lines across all four platforms:
- sensor/definitions.py: 85 name= lines
- number/definitions.py: 12 name= lines
- binary_sensor/definitions.py: 6 name= lines
- switch/definitions.py: 3 name= lines
No functional change. The unique_id (entry_id + key) and translation_key
remain stable, ensuring entity IDs and friendly names are unaffected.
Impact: Cleaner definitions, no drift between name= strings and
translations. Aligns with HA standard: translations are the single
source of truth for entity names.
Previously all 26 MONETARY sensors had state_class=TOTAL, causing the
statistics and statistics_short_term tables to grow unbounded (never
auto-purged by HA).
Reduced to 3 sensors that genuinely benefit from long-term history:
- current_interval_price (main price sensor, trend over weeks/months)
- current_interval_price_base (required for Energy Dashboard)
- average_price_today (daily avg tracking over seasons)
Set state_class=None on 23 sensors where long-term history adds no
value: forecast/future sensors (next_avg_*h), daily snapshots
(lowest/highest_price_today), tomorrow sensors, rolling windows
(trailing/leading 24h), and next/previous interval sensors.
Note: state_class=None does not affect the States timeline (History
panel). Only the Statistics chart on entity detail pages is removed
for the affected sensors. Existing statistics data is retained.
Impact: ~88% reduction in statistics table writes. Prevents database
bloat reported by users with long-running installations.
Add calculation summary attributes to best_price_period and
peak_price_period binary sensors for diagnostic transparency.
New attributes (all excluded from recorder history):
- min_periods_configured: User's configured target per day (always shown)
- periods_found_total: Actual periods found across all days (always shown)
- flat_days_detected: Days where CV <= 10% reduced target to 1 (only when > 0)
- relaxation_incomplete: Some days couldn't reach the target (only when true)
These attributes explain observed behavior without requiring users to
read logs: seeing "flat_days_detected: 1" alongside
"min_periods_configured: 2, periods_found_total: 1" immediately
explains why the count is lower than configured on uniform-price days.
Implementation:
- _compute_day_effective_min() now returns (dict, int) tuple to propagate
the flat day count through to the metadata dict
- flat_days_detected added to metadata["relaxation"] in
calculate_periods_with_relaxation()
- build_final_attributes_simple() gains optional period_metadata parameter
- New add_calculation_summary_attributes() function handles the rendering
- Attributes are shown even when no period is currently active
Updated recorder-optimization.md: attribute counts + clarified that
timestamp is correctly excluded (entity native_value is recorded
separately by HA as the entity state itself).
Impact: Users can understand why they received fewer periods than
configured without enabling debug logging.
Three complementary fixes for pathological price days:
1. Adaptive min_periods for flat days (CV ≤ 10%):
On days with nearly uniform prices (e.g. solar surplus), enforcing
multiple distinct cheap periods is geometrically impossible.
_compute_day_effective_min() detects CV ≤ LOW_CV_FLAT_DAY_THRESHOLD
and reduces the effective target to 1 for that day (best price only;
peak price always runs full relaxation).
2. min_distance scaling on absolute low-price days:
When the daily average drops below 0.10 EUR (10 ct), percentage-based
min_distance becomes unreliable. The threshold is scaled linearly to
zero so the filter neither accepts the entire day nor blocks everything.
3. CV quality gate bypass for absolute low-price periods:
Periods with a mean below 0.10 EUR may show high relative CV even
though the absolute price differences are fractions of a cent.
Both _check_period_quality() and _check_merge_quality_gate() now
bypass the CV gate below this threshold.
Additionally: span-aware flex warnings now emit INFO/WARNING when
base_flex >= 25%/30% and at least one "normal" (non-V-shape) day
exists (FLEX_WARNING_VSHAPE_RATIO = 0.5). Previously the constants
were defined but never used.
Updated 3 test assertions in test_best_price_e2e.py: the flat-day
fixture (CV ~5.4%) correctly produces 1 period, not 2.
Impact: Best Price periods now appear reliably on V-shape solar days
and flat-price days. No more "0 periods" on days where the single
cheapest window is a valid and useful result.
_get_cached_intervals() used fixed-offset datetimes from fromisoformat()
for iteration. When start and end boundaries span a DST transition (e.g.,
+01:00 CET → +02:00 CEST), the loop's end check compared UTC values,
stopping 1 hour early on spring-forward days.
This caused the last 4 quarter-hourly intervals of "tomorrow" to be
missing, making the binary sensor "Tomorrow data available" show Off
even when full data was present.
Changed iteration to use naive local timestamps, matching the index key
format (timezone stripped via [:19]). The end boundary comparison now
works correctly regardless of DST transitions.
Impact: Binary sensor "Tomorrow data available" now correctly shows On
on DST spring-forward days. Affects all European users on the last
Sunday of March each year.
When runtime config override entities (number/switch) are enabled,
the Options Flow now displays warning indicators at the top of each
affected section. Users see which fields are being managed by config
entities and can still edit the base values if needed.
Changes:
- Add ConstantSelector warnings in Best Price/Peak Price sections
- Implement multi-language support for override warnings (de, en, nb, nl, sv)
- Add _get_override_translations() to load translated field labels
- Add _get_active_overrides() to detect enabled override entities
- Extend get_best_price_schema/get_peak_price_schema with translations param
- Add 14 number/switch config entities for runtime period tuning
- Document runtime configuration entities in user docs
Warning format adapts to overridden fields:
- Single: "⚠️ Flexibility controlled by config entity"
- Multiple: "⚠️ Flexibility and Minimum Distance controlled by config entity"
Impact: Users can now dynamically adjust period calculation parameters
via Home Assistant automations, scripts, or dashboards without entering
the Options Flow. Clear UI indicators show which settings are currently
overridden.
Add visual indicators to distinguish hourly aggregated data from
original 15-minute interval data in ApexCharts output.
Changes:
- Chart title: Append localized suffix like "(Ø hourly)" / "(Ø stündlich)"
- Y-axis label: Append "(Ø)" suffix, e.g., "øre/kWh (Ø)"
The suffix pattern avoids confusion with Scandinavian currency symbols
(øre/öre) which look similar to the average symbol (Ø) when used as prefix.
Added hourly_suffix translations for all 5 languages (en, de, sv, nb, nl).
Impact: Users can now clearly see when a chart displays averaged hourly
data rather than original 15-minute prices.
Implement clickable legend items to show/hide best/peak price period
overlays in generated ApexCharts YAML configuration.
Legend behavior by configuration:
- Only best price: No legend (overlay always visible)
- Only peak price: Legend shown, peak toggleable (starts hidden)
- Both enabled: Legend shown, both toggleable (best visible, peak hidden)
Changes:
- Best price overlay: in_legend only when peak also enabled
- Peak price overlay: always in_legend with hidden_by_default: true
- Enable experimental.hidden_by_default when peak price active
- Price level series (LOW/NORMAL/HIGH): hidden from legend when
overlays active, visible otherwise (preserves easy legend enable)
- Add triangle icons (▼/▲) before overlay names for visual distinction
- Custom legend markers (size: 0) only when overlays active
- Increased itemMargin for better visual separation
Impact: Users can toggle best/peak price period visibility directly
in the chart via legend click. Without overlays, legend behavior
unchanged - users can still enable it by setting show: true.
Add resolution parameter to get_chartdata and get_apexcharts_yaml services,
allowing users to choose between original 15-minute intervals or aggregated
hourly values for chart visualization.
Implementation uses rolling 5-interval window aggregation (-2, -1, 0, +1, +2
around :00 of each hour = 60 minutes total), matching the sensor rolling
hour methodology. Respects user's CONF_AVERAGE_SENSOR_DISPLAY setting for
mean vs median calculation.
Changes:
- formatters.py: Add aggregate_to_hourly() function preserving original
field names (startsAt, total, level, rating_level) for unified processing
- get_chartdata.py: Pre-aggregate data before processing when resolution is
'hourly', enabling same code path for filters/insert_nulls/connect_segments
- get_apexcharts_yaml.py: Add resolution parameter, pass to all 4 get_chartdata
service calls in generated JavaScript
- services.yaml: Add resolution field with interval/hourly selector
- icons.json: Add section icons for get_apexcharts_yaml fields
- translations: Add highlight_peak_price and resolution field translations
for all 5 languages (en, de, sv, nb, nl)
Impact: Users can now generate cleaner charts with 24 hourly data points
instead of 96 quarter-hourly intervals. The unified processing approach
ensures all chart features (filters, null insertion, segment connection)
work identically for both resolutions.
Added dynamic warnings when users configure settings for sensors that
are currently disabled. This improves UX by informing users that their
configuration changes won't have any visible effect until they enable
the relevant sensors.
Changes:
- Created entity_check.py helper module with sensor-to-step mappings
- Added check_relevant_entities_enabled() to detect disabled sensors
- Integrated warnings into 6 options flow steps (price_rating,
price_level, best_price, peak_price, price_trend, volatility)
- Made Chart Data Export info page content-aware: shows configuration
guide when sensor is enabled, shows enablement instructions when disabled
- Updated all 5 translation files (de, en, nb, nl, sv) with dynamic
placeholders {entity_warning} and {sensor_status_info}
Impact: Users now receive clear feedback when configuring settings for
disabled sensors, reducing confusion about why changes aren't visible.
Chart Data Export page now provides context-appropriate guidance.
Fixed inconsistency between "Current Electricity Price" and "Current Electricity Price
(Energy Dashboard)" sensors that were showing different prices and icons.
Changes:
- Add current_interval_price_base to TIME_SENSITIVE_ENTITY_KEYS so it updates at
quarter-hour boundaries instead of only on API polls. This ensures both sensors
update synchronously when a new 15-minute interval starts.
- Use interval_data["startsAt"] as timestamp for current interval price sensors
(both variants) instead of rounded calculation time. This prevents timestamp
divergence when sensors update at slightly different times.
- Include current_interval_price_base in icon color attribute mapping so both
sensors display the same dynamic cash icon based on current price level.
- Include current_interval_price_base in dynamic icon function so it gets the
correct icon based on current price level (VERY_CHEAP/CHEAP/NORMAL/EXPENSIVE).
Impact: Both sensors now show identical prices, timestamps, and icons as intended.
They update synchronously at interval boundaries (00, 15, 30, 45 minutes) and
correctly represent the Energy Dashboard compatible variant without lag or
inconsistencies.
Convert best_price and peak_price timing sensors to display in hours (UI-friendly)
while retaining minute values in attributes (automation-friendly). This improves
readability in dashboards by using Home Assistant's automatic duration formatting
"1 h 35 min" instead of decimal "1.58 h".
BREAKING CHANGE: State unit changed from minutes to hours for 6 timing sensors.
Affected sensors:
* best_price_period_duration, best_price_remaining_minutes, best_price_next_in_minutes
* peak_price_period_duration, peak_price_remaining_minutes, peak_price_next_in_minutes
Migration guide for users:
- If your automations use {{ state_attr(..., 'remaining_time') }} or similar:
No action needed - attribute values remain in minutes
- If your automations use {{ states('sensor.best_price_remaining_minutes') }} directly:
Update to use the minute attribute instead: {{ state_attr('sensor.best_price_remaining_minutes', 'remaining_minutes') }}
- If your dashboards display the state value:
Values now show as "1 h 35 min" instead of "95" - this is the intended improvement
- If your templates do math with the state: multiply by 60 to convert hours back to minutes
Before: remaining * 60
After: remaining_minutes (use attribute directly)
Implementation details:
- Timing sensors now use device_class=DURATION, unit=HOURS, precision=2
- State values converted from minutes to hours via _minutes_to_hours()
- New minute-precision attributes added for automation compatibility:
* period_duration_minutes (for checking if period is long enough)
* remaining_minutes (for countdown-based automation logic)
* next_in_minutes (for time-to-event automation triggers)
- Translation improvements across all 5 languages (en, de, nb, nl, sv):
* Descriptions now clarify state in hours vs attributes in minutes
* Long descriptions explain dual-format architecture
* Usage tips updated to reference minute attributes for automations
* All translation files synchronized (fixed order, removed duplicates)
- Type safety: Added type assertions (cast) for timing calculator results to
satisfy Pyright type checking (handles both float and datetime return types)
Home Assistant now automatically formats these durations as "1 h 35 min" for improved
UX, matching the behavior of battery.remaining_time and other duration sensors.
Rationale for breaking change:
The previous minute-based state was unintuitive for users ("95 minutes" doesn't
immediately convey "1.5 hours") and didn't match Home Assistant's standard duration
formatting. The new hour-based state with minute attributes provides:
- Better UX: Automatic "1 h 35 min" formatting in UI
- Full automation compatibility: Minute attributes for all calculation needs
- Consistency: Matches HA's duration sensor pattern (battery, timer, etc.)
Impact: Timing sensors now display in human-readable hours with full backward
compatibility via minute attributes. Users relying on direct state access must
migrate to minute attributes (simple change, documented above).
- Remove pool stats/fetch-age from lifecycle sensor to avoid stale data under state-change filtering; add `next_api_poll` for transparency.
- Clean lifecycle calculator by dropping unused helpers/constants and delete the obsolete cache age test.
- Clarify lifecycle state is diagnostics-only in coordinator comments, keep state-change filtering in timer test, and retain quarter-hour precision notes in constants.
- Keep sensor core aligned with lifecycle state filtering.
Impact: Lifecycle sensor now exposes only state-relevant fields without recorder noise, next API poll is visible, and dead code/tests tied to removed attributes are gone.