Commit graph

63 commits

Author SHA1 Message Date
github-actions[bot]
994eecdd3d docs: add version snapshot v0.27.0 and cleanup old versions [skip ci] 2026-03-29 18:59:51 +00:00
Julian Pawlowski
631cebeb55 feat(config_flow): show override warnings when config entities control settings
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.
2026-01-21 17:36:51 +00:00
Julian Pawlowski
c6b34984fa chore: Remove outdated documentation for sensors and troubleshooting in version v0.25.0b0; update versioning logic to skip documentation versioning for beta releases. 2025-12-25 23:06:27 +00:00
github-actions[bot]
3624f1c9a8 docs: add version snapshot v0.25.0b0 and cleanup old versions [skip ci] 2025-12-25 22:54:51 +00:00
Julian Pawlowski
15e09fa210 docs(user): unify entity ID examples and add "Entity ID tip" across guides
Added a consistent "Entity ID tip" block and normalized all example
entity IDs to the `<home_name>` placeholder across user docs. Updated
YAML and example references to current entity naming (e.g.,
`sensor.<home_name>_current_electricity_price`,
`sensor.<home_name>_price_today`,
`sensor.<home_name>_today_s_price_volatility`,
`binary_sensor.<home_name>_best_price_period`, etc.). Refreshed
automation examples to use language-independent attributes (e.g.
`price_volatility`) and improved robustness. Aligned ApexCharts examples
to use `sensor.<home_name>_chart_metadata` and corrected references for
tomorrow data availability.

Changed files:
- docs/user/docs/actions.md
- docs/user/docs/automation-examples.md
- docs/user/docs/chart-examples.md
- docs/user/docs/configuration.md
- docs/user/docs/dashboard-examples.md
- docs/user/docs/dynamic-icons.md
- docs/user/docs/faq.md
- docs/user/docs/icon-colors.md
- docs/user/docs/period-calculation.md
- docs/user/docs/sensors.md

Impact: Clearer, language-independent examples that reduce confusion and
prevent brittle automations; easier copy/paste adaptation across setups;
more accurate guidance for chart configuration and period/volatility usage.
2025-12-25 19:20:37 +00:00
github-actions[bot]
fc64aecdd9 docs: add version snapshot v0.24.0 and cleanup old versions [skip ci] 2025-12-22 23:42:52 +00:00
github-actions[bot]
5cc71901b9 docs: add version snapshot v0.23.1 and cleanup old versions [skip ci] 2025-12-21 10:48:25 +00:00
github-actions[bot]
19882fb17d docs: add version snapshot v0.23.0 and cleanup old versions [skip ci] 2025-12-18 15:19:19 +00:00
Julian Pawlowski
df1ee2943b docs: update AGENTS.md links to use main branch 2025-12-18 15:16:34 +00:00
Julian Pawlowski
f539c9119b Merge branch 'main' of https://github.com/jpawlowski/hass.tibber_prices 2025-12-18 15:15:23 +00:00
Julian Pawlowski
dff0faeef5 docs(dev): update GitHub links to use main branch
Changed all documentation links from version-specific tags (v0.20.0) to
main branch references. This makes documentation maintenance-free - links
stay current as code evolves.

Updated 38 files across:
- docs/developer/docs/ (7 files)
- docs/developer/versioned_docs/version-v0.21.0/ (8 files)
- docs/developer/versioned_docs/version-v0.22.0/ (8 files)

Impact: Documentation links no longer break when new versions are released.
Links always point to current code implementation.
2025-12-18 15:15:18 +00:00
Julian Pawlowski
b815aea8bf docs(user): add comprehensive average sensor documentation
Expanded user documentation with detailed guidance on average sensors:

1. sensors.md (+182 lines):
   - New 'Average Price Sensors' section with mean vs median explanation
   - 3 real-world automation examples (heat pump, dishwasher, EV charging)
   - Display configuration guide with use-case recommendations

2. configuration.md (+75 lines):
   - New 'Average Sensor Display Settings' section
   - Comparison table of display modes (mean/median/both)
   - Attribute availability details and recorder implications

3. Minor updates to installation.md and versioned docs

Impact: Users can now understand when to use mean vs median and how to
configure display format for their specific automation needs.
2025-12-18 15:15:00 +00:00
github-actions[bot]
c30af465c9 docs: add version snapshot v0.22.1 and cleanup old versions [skip ci] 2025-12-13 14:10:02 +00:00
github-actions[bot]
51cf230c48 docs: add version snapshot v0.22.0 and cleanup old versions [skip ci] 2025-12-11 08:44:26 +00:00
Julian Pawlowski
60e05e0815 refactor(currency)!: rename major/minor to base/subunit currency terminology
Complete terminology migration from confusing "major/minor" to clearer
"base/subunit" currency naming throughout entire codebase, translations,
documentation, tests, and services.

BREAKING CHANGES:

1. **Service API Parameters Renamed**:
   - `get_chartdata`: `minor_currency` → `subunit_currency`
   - `get_apexcharts_yaml`: Updated service_data references from
     `minor_currency: true` to `subunit_currency: true`
   - All automations/scripts using these parameters MUST be updated

2. **Configuration Option Key Changed**:
   - Config entry option: Display mode setting now uses new terminology
   - Internal key: `currency_display_mode` values remain "base"/"subunit"
   - User-facing labels updated in all 5 languages (de, en, nb, nl, sv)

3. **Sensor Entity Key Renamed**:
   - `current_interval_price_major` → `current_interval_price_base`
   - Entity ID changes: `sensor.tibber_home_current_interval_price_major`
     → `sensor.tibber_home_current_interval_price_base`
   - Energy Dashboard configurations MUST update entity references

4. **Function Signatures Changed**:
   - `format_price_unit_major()` → `format_price_unit_base()`
   - `format_price_unit_minor()` → `format_price_unit_subunit()`
   - `get_price_value()`: Parameter `in_euro` deprecated in favor of
     `config_entry` (backward compatible for now)

5. **Translation Keys Renamed**:
   - All language files: Sensor translation key
     `current_interval_price_major` → `current_interval_price_base`
   - Service parameter descriptions updated in all languages
   - Selector options updated: Display mode dropdown values

Changes by Category:

**Core Code (Python)**:
- const.py: Renamed all format_price_unit_*() functions, updated docstrings
- entity_utils/helpers.py: Updated get_price_value() with config-driven
  conversion and backward-compatible in_euro parameter
- sensor/__init__.py: Added display mode filtering for base currency sensor
- sensor/core.py:
  * Implemented suggested_display_precision property for dynamic decimal places
  * Updated native_unit_of_measurement to use get_display_unit_string()
  * Updated all price conversion calls to use config_entry parameter
- sensor/definitions.py: Renamed entity key and updated all
  suggested_display_precision values (2 decimals for most sensors)
- sensor/calculators/*.py: Updated all price conversion calls (8 calculators)
- sensor/helpers.py: Updated aggregate_price_data() signature with config_entry
- sensor/attributes/future.py: Updated future price attributes conversion

**Services**:
- services/chartdata.py: Renamed parameter minor_currency → subunit_currency
  throughout (53 occurrences), updated metadata calculation
- services/apexcharts.py: Updated service_data references in generated YAML
- services/formatters.py: Renamed parameter use_minor_currency →
  use_subunit_currency in aggregate_hourly_exact() and get_period_data()
- sensor/chart_metadata.py: Updated default parameter name

**Translations (5 Languages)**:
- All /translations/*.json:
  * Added new config step "display_settings" with comprehensive explanations
  * Renamed current_interval_price_major → current_interval_price_base
  * Updated service parameter descriptions (subunit_currency)
  * Added selector.currency_display_mode.options with translated labels
- All /custom_translations/*.json:
  * Renamed sensor description keys
  * Updated chart_metadata usage_tips references

**Documentation**:
- docs/user/docs/actions.md: Updated parameter table and feature list
- docs/user/versioned_docs/version-v0.21.0/actions.md: Backported changes

**Tests**:
- Updated 7 test files with renamed parameters and conversion logic:
  * test_connect_segments.py: Renamed minor/major to subunit/base
  * test_period_data_format.py: Updated period price conversion tests
  * test_avg_none_fallback.py: Fixed tuple unpacking for new return format
  * test_best_price_e2e.py: Added config_entry parameter to all calls
  * test_cache_validity.py: Fixed cache data structure (price_info key)
  * test_coordinator_shutdown.py: Added repair_manager mock
  * test_midnight_turnover.py: Added config_entry parameter
  * test_peak_price_e2e.py: Added config_entry parameter, fixed price_avg → price_mean
  * test_percentage_calculations.py: Added config_entry mock

**Coordinator/Period Calculation**:
- coordinator/periods.py: Added config_entry parameter to
  calculate_periods_with_relaxation() calls (2 locations)

Migration Guide:

1. **Update Service Calls in Automations/Scripts**:
   \`\`\`yaml
   # Before:
   service: tibber_prices.get_chartdata
   data:
     minor_currency: true

   # After:
   service: tibber_prices.get_chartdata
   data:
     subunit_currency: true
   \`\`\`

2. **Update Energy Dashboard Configuration**:
   - Settings → Dashboards → Energy
   - Replace sensor entity:
     `sensor.tibber_home_current_interval_price_major` →
     `sensor.tibber_home_current_interval_price_base`

3. **Review Integration Configuration**:
   - Settings → Devices & Services → Tibber Prices → Configure
   - New "Currency Display Settings" step added
   - Default mode depends on currency (EUR → subunit, Scandinavian → base)

Rationale:

The "major/minor" terminology was confusing and didn't clearly communicate:
- **Major** → Unclear if this means "primary" or "large value"
- **Minor** → Easily confused with "less important" rather than "smaller unit"

New terminology is precise and self-explanatory:
- **Base currency** → Standard ISO currency (€, kr, $, £)
- **Subunit currency** → Fractional unit (ct, øre, ¢, p)

This aligns with:
- International terminology (ISO 4217 standard)
- Banking/financial industry conventions
- User expectations from payment processing systems

Impact: Aligns currency terminology with international standards. Users must
update service calls, automations, and Energy Dashboard configuration after
upgrade.

Refs: User feedback session (December 2025) identified terminology confusion
2025-12-11 08:26:30 +00:00
Julian Pawlowski
284a7f4291 fix(periods): Periods are now correctly recalculated after tomorrow prices became available. 2025-12-09 16:57:57 +00:00
Julian Pawlowski
51a99980df feat(sensors)!: add configurable median/mean display for average sensors
Add user-configurable option to choose between median and arithmetic mean
as the displayed value for all 14 average price sensors, with the alternate
value exposed as attribute.

BREAKING CHANGE: Average sensor default changed from arithmetic mean to
median. Users who rely on arithmetic mean behavior may use the price_mean attribue now, or must manually reconfigure
via Settings → Devices & Services → Tibber Prices → Configure → General
Settings → "Average Sensor Display" → Select "Arithmetic Mean" to get this as sensor state.

Affected sensors (14 total):
- Daily averages: average_price_today, average_price_tomorrow
- 24h windows: trailing_price_average, leading_price_average
- Rolling hour: current_hour_average_price, next_hour_average_price
- Future forecasts: next_avg_3h, next_avg_6h, next_avg_9h, next_avg_12h

Implementation:
- All average calculators now return (mean, median) tuples
- User preference controls which value appears in sensor state
- Alternate value automatically added to attributes
- Period statistics (best_price/peak_price) extended with both values

Technical changes:
- New config option: CONF_AVERAGE_SENSOR_DISPLAY (default: "median")
- Calculator functions return tuples: (avg, median)
- Attribute builders: add_alternate_average_attribute() helper function
- Period statistics: price_avg → price_mean + price_median
- Translations: Updated all 5 languages (de, en, nb, nl, sv)
- Documentation: AGENTS.md, period-calculation.md, recorder-optimization.md

Migration path:
Users can switch back to arithmetic mean via:
Settings → Integrations → Tibber Prices → Configure
→ General Settings → "Average Sensor Display" → "Arithmetic Mean"

Impact: Median is more resistant to price spikes, providing more stable
automation triggers. Statistical analysis from coordinator still uses
arithmetic mean (e.g., trailing_avg_24h for rating calculations).

Co-developed-with: GitHub Copilot <copilot@github.com>
2025-12-08 17:53:40 +00:00
Julian Pawlowski
0f56e80838 Merge branch 'main' of https://github.com/jpawlowski/hass.tibber_prices 2025-12-07 21:06:57 +00:00
Julian Pawlowski
85e86cf80a fix(docs): update Developer Documentation link for clarity 2025-12-07 21:06:55 +00:00
github-actions[bot]
f67d712435 docs: add version snapshot v0.21.0 and cleanup old versions [skip ci] 2025-12-07 21:05:21 +00:00
Julian Pawlowski
83be54d5ad feat(coordinator): implement repairs system for proactive user notifications
Add repair notification system with three auto-clearing repair types:
- Tomorrow data missing (after 18:00)
- API rate limit exceeded (3+ consecutive errors)
- Home not found in Tibber account

Includes:
- coordinator/repairs.py: Complete TibberPricesRepairManager implementation
- Enhanced API error handling with explicit 5xx handling
- Translations for 5 languages (EN, DE, NB, NL, SV)
- Developer documentation in docs/developer/docs/repairs-system.md

Impact: Users receive actionable notifications for important issues instead
of only seeing stale data in logs.
2025-12-07 20:51:43 +00:00
Julian Pawlowski
4bd90ccdee chore: Update logo and icons for Tibber Prices Integration 2025-12-07 19:00:32 +00:00
Julian Pawlowski
334f462621 docs: update documentation structure for Docusaurus sites
Update all references to reflect two separate Docusaurus instances
(user + developer) with proper file paths and navigation management.

Changes:
- AGENTS.md: Document Docusaurus structure and file organization
- CONTRIBUTING.md: Add Docusaurus workflow guidelines
- docs/developer/docs/period-calculation-theory.md: Fix cross-reference
- docs/developer/sidebars.ts: Add recorder-optimization to navigation

Documentation organized as:
- docs/user/docs/*.md (user guides, via sidebars.ts)
- docs/developer/docs/*.md (developer guides, via sidebars.ts)
- AGENTS.md (AI patterns, conventions)

Impact: AI and contributors know where to place new documentation.
2025-12-07 16:59:06 +00:00
Julian Pawlowski
b99158d826 fix(docs): correct license reference from Apache 2.0 to MIT
Project uses MIT License, not Apache License 2.0.
2025-12-07 16:58:54 +00:00
Julian Pawlowski
a9c04dc0ec docs(developer): add recorder optimization guide
Add comprehensive documentation for _unrecorded_attributes
implementation, categorizing all excluded attributes with reasoning,
expected database impact, and decision framework for future attributes.

Added to Developer Docs → Advanced Topics navigation.

Content includes:
- 7 exclusion categories with examples
- Space savings calculations (60-85% reduction)
- Decision framework for new attributes
- Testing and validation guidelines
- SQL queries for verification
2025-12-07 16:57:53 +00:00
Julian Pawlowski
a7bbcb8dc9 docs: Add BMC logo SVG file to the images directory 2025-12-06 02:35:39 +00:00
Julian Pawlowski
c4b68c4cb1 fix(styles): add padding to hero section for improved layout 2025-12-06 02:07:47 +00:00
Julian Pawlowski
cc845ee675 fix(styles): adjust padding for heroBanner in CSS modules 2025-12-06 02:00:01 +00:00
Julian Pawlowski
e79bc97321 chore(docs): replace SVG logo with image for improved performance and compatibility 2025-12-06 01:57:44 +00:00
Julian Pawlowski
d71f3408b9 fix(docs): update developer documentation link in user intro
Change relative path ../development/ to absolute path /hass.tibber_prices/developer/
since user and developer docs are now separate Docusaurus instances.

Fixes broken link warning during build.
2025-12-06 01:54:13 +00:00
Julian Pawlowski
d73eda4b2f git commit -m "feat(docs): add dual Docusaurus sites with custom branding and Giscus integration
- Split documentation into separate User and Developer sites
- Migrated existing docs to proper Docusaurus structure
- Added custom Tibber-themed header logos (light + dark mode variants)
- Implemented custom color scheme matching integration branding
  - Hero gradient: Cyan → Dark Cyan → Gold
  - Removed standard Docusaurus purple/green theme
- Integrated Giscus comments system for community collaboration
  - User docs: Comments enabled on guides, examples, FAQ
  - User docs: Comments disabled on reference pages (glossary, sensors, troubleshooting)
  - Developer docs: No comments (GitHub Issues/PRs preferred)
- Added categorized sidebars with emoji navigation
- Created 8 new placeholder documentation pages
- Fixed image paths for baseUrl compatibility (local + GitHub Pages)
- Escaped MDX special characters in performance metrics
- Added GitHub Actions workflow for automated deployment
- Created helper scripts: dev-user, dev-developer, build-all

Breaking changes:
- Moved /docs/user/*.md to /docs/user/docs/*.md
- Moved /docs/development/*.md to /docs/developer/docs/*.md
2025-12-06 01:37:06 +00:00
Julian Pawlowski
b5db6053ba docs: Update chart examples and sensors documentation for chart_metadata integration 2025-12-05 21:44:46 +00:00
Julian Pawlowski
86afea9cce docs: Update README with example screenshots. 2025-12-05 21:37:31 +00:00
Julian Pawlowski
afb8ac2327 doc: Add comprehensive chart examples and screenshots for tibber_prices integration
- Created a new documentation file `chart-examples.md` detailing various chart configurations available through the `tibber_prices.get_apexcharts_yaml` action.
- Included descriptions, dependencies, and YAML generation examples for four chart modes: Today's Prices, Rolling 48h Window, and Rolling Window Auto-Zoom.
- Added a section on dynamic Y-axis scaling and best price period highlights.
- Established prerequisites for using the charts, including required cards and customization tips.
- Introduced a new `README.md` in the images/charts directory to document available chart screenshots and guidelines for capturing them.
2025-12-05 21:15:52 +00:00
Julian Pawlowski
c9a7dcdae7 feat(services): add rolling window options with auto-zoom for ApexCharts
Added two new rolling window options for get_apexcharts_yaml service to provide
flexible dynamic chart visualization:

- rolling_window: Fixed 48h window that automatically shifts between
  yesterday+today and today+tomorrow based on data availability
- rolling_window_autozoom: Same as rolling_window but with progressive zoom-in
  (2h lookback + remaining time until midnight, updates every 15min)

Implementation changes:
- Updated service schema validation to accept new day options
- Added entity mapping patterns for both rolling modes
- Implemented minute-based graph_span calculation with quarter-hour alignment
- Added config-template-card integration for dynamic span updates
- Used current_interval_price sensor as 15-minute update trigger
- Unified data loading: both rolling modes omit day parameter for dynamic selection
- Applied ternary operator pattern for cleaner day_param logic
- Made grid lines more subtle (borderColor #f5f5f5, strokeDashArray 0)

Translation updates:
- Added selector options in all 5 languages (de, en, nb, nl, sv)
- Updated field descriptions to include default behavior and new options
- Documented that rolling window is default when day parameter omitted

Documentation updates:
- Updated user docs (actions.md, automation-examples.md) with new options
- Added detailed explanation of day parameter options
- Included examples for both rolling_window and rolling_window_autozoom modes

Impact: Users can now create auto-adapting ApexCharts that show 48h rolling
windows with optional progressive zoom throughout the day. Requires
config-template-card for dynamic behavior.
2025-12-04 14:39:00 +00:00
Julian Pawlowski
ab9735928a refactor(docs): update terminology from "services" to "actions" for clarity and consistency 2025-12-02 18:35:59 +00:00
Julian Pawlowski
b78ddeaf43 feat(docs): update get_apexcharts_yaml service descriptions to clarify limitations and customization options 2025-12-02 16:47:36 +00:00
Julian Pawlowski
e156dfb061 feat(services): add rolling 48h window support to chart services
Add dynamic rolling window mode to get_chartdata and get_apexcharts_yaml
services that automatically adapts to data availability.

When 'day' parameter is omitted, services return 48-hour window:
- With tomorrow data (after ~13:00): today + tomorrow
- Without tomorrow data: yesterday + today

Changes:
- Implement rolling window logic in get_chartdata using has_tomorrow_data()
- Generate config-template-card wrapper in get_apexcharts_yaml for dynamic
  ApexCharts span.offset based on tomorrow_data_available binary sensor
- Update service descriptions in services.yaml
- Add rolling window descriptions to all translations (de, en, nb, nl, sv)
- Document rolling window mode in docs/user/services.md
- Add ApexCharts examples with prerequisites in docs/user/automation-examples.md

BREAKING CHANGE: get_apexcharts_yaml rolling window mode requires
config-template-card in addition to apexcharts-card for dynamic offset
calculation.

Impact: Users can create auto-adapting 48h price charts without manual day
selection. Fixed day views (day: today/yesterday/tomorrow) still work with
apexcharts-card only.
2025-12-01 23:46:09 +00:00
Julian Pawlowski
a90fef6f2d refactor(scripts): reorganize and standardize development scripts
Major restructuring of the scripts/ directory with consistent output
formatting, improved organization, and stricter error handling.

Breaking Changes:
- Updated development environment to Home Assistant 2025.7+
  - Removed Python 3.12 compatibility (HA 2025.7+ requires Python 3.13)
  - Updated all HA core requirements from 2025.7 requirement files
  - Added new dependencies: python-multipart, uv (for faster package management)
  - Updated GitHub Actions workflows to use Python 3.13

Changes:
- Created centralized output library (scripts/.lib/output.sh)
  - Unified color codes and Unicode symbols
  - Consistent formatting functions (log_header, log_success, log_error, etc.)
  - Support for embedded formatting codes (${BOLD}, ${GREEN}, etc.)

- Reorganized into logical subdirectories:
  - scripts/setup/ - Setup and maintenance scripts
    - bootstrap: Install/update dependencies (used in CI/CD)
    - setup: Full DevContainer setup (pyright, copilot, HACS)
    - reset: Reset config/ directory to fresh state (NEW)
    - sync-hacs: Sync HACS integrations
  - scripts/release/ - Release management scripts
    - prepare: Version bump and tagging
    - suggest-version: Semantic version suggestion
    - generate-notes: Release notes generation
    - check-if-released: Check release status
    - hassfest: Local integration validation

- Updated all scripts with:
  - set -euo pipefail for stricter error handling
  - Consistent SCRIPT_DIR pattern for reliable sourcing
  - Professional output with colors and emojis
  - Unified styling across all 17 scripts

- Removed redundant scripts:
  - scripts/update (was just wrapper around bootstrap)
  - scripts/json_schemas/ (moved to schemas/json/)

- Enhanced clean script:
  - Improved artifact cleanup
  - Better handling of accidental package installations
  - Hints for reset and deep clean options

- New reset script features:
  - Standard mode: Keep configuration.yaml
  - Full mode (--full): Reset configuration.yaml from git
  - Automatic re-setup after reset

- Updated documentation:
  - AGENTS.md: Updated script references and workflow guidance
  - docs/development/: Updated all references to new script structure

Impact: Development environment now requires Python 3.13 and Home Assistant
2025.7+. Developers get consistent, professional script output with better
error handling and logical organization. Single source of truth for styling
makes future updates trivial.
2025-11-26 13:11:52 +00:00
Julian Pawlowski
981fb08a69 refactor(price_info): price data handling to use unified interval retrieval
- Introduced `get_intervals_for_day_offsets` helper to streamline access to price intervals for yesterday, today, and tomorrow.
- Updated various components to replace direct access to `priceInfo` with the new helper, ensuring a flat structure for price intervals.
- Adjusted calculations and data processing methods to accommodate the new data structure.
- Enhanced documentation to reflect changes in caching strategy and data structure.
2025-11-24 10:49:34 +00:00
Julian Pawlowski
294d84128b refactor(services): rename and reorganize custom services for clarity and functionality 2025-11-23 13:17:21 +00:00
Julian Pawlowski
85fe9666a7 feat(coordinator): add atomic midnight turnover coordination
Introduced TibberPricesMidnightHandler to prevent duplicate midnight
turnover when multiple timers fire simultaneously.

Problem: Timer #1 (API poll) and Timer #2 (quarter-hour refresh) both
wake at midnight, each detecting day change and triggering cache clear.
Race condition caused duplicate turnover operations.

Solution:
- Atomic flag coordination: First timer sets flag, subsequent timers skip
- Persistent state survives HA restart (cache stores last_turnover_time)
- Day-boundary detection: Compares current.date() vs last_check.date()
- 13 comprehensive tests covering race conditions and HA restart scenarios

Architecture:
- coordinator/midnight_handler.py: 165 lines, atomic coordination logic
- coordinator/core.py: Integrated handler in coordinator initialization
- coordinator/listeners.py: Delegate midnight check to handler

Impact: Eliminates duplicate cache clears at midnight. Single atomic
turnover operation regardless of how many timers fire simultaneously.
2025-11-22 04:45:41 +00:00
Julian Pawlowski
47b0a298d4 feat(periods): add midnight-crossing periods and day volatility attributes
Periods can now naturally cross midnight boundaries, and new diagnostic
attributes help users understand price classification changes at midnight.

**New Features:**

1. Midnight-Crossing Period Support (relaxation.py):
   - group_periods_by_day() assigns periods to ALL spanned days
   - Periods crossing midnight appear in both yesterday and today
   - Enables period formation across calendar day boundaries
   - Ensures min_periods checking works correctly at midnight

2. Extended Price Data Window (relaxation.py):
   - Period calculation now uses full 3-day data (yesterday+today+tomorrow)
   - Enables natural period formation without artificial midnight cutoff
   - Removed date filter that excluded yesterday's prices

3. Day Volatility Diagnostic Attributes (period_statistics.py, core.py):
   - day_volatility_%: Daily price spread as percentage (span/avg × 100)
   - day_price_min/max/span: Daily price range in minor currency (ct/øre)
   - Helps detect when midnight classification changes are economically significant
   - Uses period start day's reference prices for consistency

**Documentation:**

4. Design Principles (period-calculation-theory.md):
   - Clarified per-day evaluation principle (always was the design)
   - Added comprehensive section on midnight boundary handling
   - Documented volatility threshold separation (sensor vs period filters)
   - Explained market context for midnight price jumps (EPEX SPOT timing)

5. User Guides (period-calculation.md, automation-examples.md):
   - Added \"Midnight Price Classification Changes\" troubleshooting section
   - Provided automation examples using volatility attributes
   - Explained why Best→Peak classification can change at midnight
   - Documented level filter volatility threshold behavior

**Architecture:**

- Per-day evaluation: Each interval evaluated against its OWN day's min/max/avg
  (not period start day) ensures mathematical correctness across midnight
- Period boundaries: Periods can naturally cross midnight but may split when
  consecutive days differ significantly (intentional, mathematically correct)
- Volatility thresholds: Sensor thresholds (user-configurable) remain separate
  from period filter thresholds (fixed internal) to prevent unexpected behavior

Impact: Periods crossing midnight are now consistently visible before and
after midnight turnover. Users can understand and handle edge cases where
price classification changes at midnight on low-volatility days.
2025-11-21 23:18:46 +00:00
Julian Pawlowski
46fcdb8ba3 docs(period-calculation): update default thresholds for Best Price and Peak Price periods 2025-11-20 11:52:15 +00:00
Julian Pawlowski
07f5990e06 docs(guidelines): update naming conventions for public and private classes 2025-11-20 10:29:45 +00:00
Julian Pawlowski
457fa7c03f refactor(periods): merge adjacent periods and remove is_extension logic
BREAKING CHANGE: Period overlap resolution now merges adjacent/overlapping periods
instead of marking them as extensions. This simplifies automation logic and provides
clearer period boundaries for users.

Previous Behavior:
- Adjacent periods created by relaxation were marked with is_extension=true
- Multiple short periods instead of one continuous period
- Complex logic needed to determine actual period length in automations

New Behavior:
- Adjacent/overlapping periods are merged into single continuous periods
- Newer period's relaxation attributes override older period's
- Simpler automation: one period = one continuous time window

Changes:
- Period Overlap Resolution (new file: period_overlap.py):
  * Added merge_adjacent_periods() to combine periods and preserve attributes
  * Rewrote resolve_period_overlaps() with simplified merge logic
  * Removed split_period_by_overlaps() (no longer needed)
  * Removed is_extension marking logic
  * Removed unused parameters: min_period_length, baseline_periods

- Relaxation Strategy (relaxation.py):
  * Removed all is_extension filtering from period counting
  * Simplified standalone counting to just len(periods)
  * Changed from period_merging import to period_overlap import
  * Added MAX_FLEX_HARD_LIMIT constant (0.50)
  * Improved debug logging for merged periods

- Code Quality:
  * Fixed all remaining linter errors (N806, PLR2004, PLR0912)
  * Extracted magic values to module-level constants:
    - FLEX_SCALING_THRESHOLD = 0.20
    - SCALE_FACTOR_WARNING_THRESHOLD = 0.8
    - MAX_FLEX_HARD_LIMIT = 0.50
  * Added appropriate noqa comments for unavoidable patterns

- Configuration (from previous work in this session):
  * Removed CONF_RELAXATION_STEP_BEST, CONF_RELAXATION_STEP_PEAK
  * Hard-coded 3% relaxation increment for reliability
  * Optimized defaults: RELAXATION_ATTEMPTS 8→11, ENABLE_MIN_PERIODS False→True,
    MIN_PERIODS undefined→2
  * Removed relaxation_step UI fields from config flow
  * Updated all 5 translation files

- Documentation:
  * Updated period_handlers/__init__.py: period_merging → period_overlap
  * No user-facing docs changes needed (already described continuous periods)

Rationale - Period Merging:
User experience was complicated by fragmented periods:
- Automations had to check multiple adjacent periods
- Binary sensors showed ON/OFF transitions within same cheap time
- No clear way to determine actual continuous period length

With merging:
- One continuous cheap time = one period
- Binary sensor clearly ON during entire period
- Attributes show merge history via merged_from dict
- Relaxation info preserved from newest/highest flex period

Rationale - Hard-Coded Relaxation Increment:
The configurable relaxation_step parameter proved problematic:
- High base flex + high step → rapid explosion (40% base + 10% step → 100% in 6 steps)
- Users don't understand the multiplicative nature
- 3% increment provides optimal balance: 11 attempts to reach 50% hard cap

Impact:
- Existing installations: Periods may appear longer (merged instead of split)
- Automations benefit from simpler logic (no is_extension checks needed)
- Custom relaxation_step values will use new 3% increment
- Users may need to adjust relaxation_attempts if they relied on high step sizes
2025-11-19 20:16:58 +00:00
Julian Pawlowski
3d1b6a64fc docs(architecture): update architecture documentation with Calculator Pattern details and sensor organization 2025-11-18 21:29:07 +00:00
Julian Pawlowski
c316d5deef refactor: resolve circular imports and enhance documentation
This commit completes multiple refactoring efforts and documentation improvements:

Code Structure Changes:
- Move round_to_nearest_quarter_hour() from sensor/helpers.py to average_utils.py
- Resolve circular import between price_utils.py and sensor/helpers.py
- Split api.py into api/ package (client.py, queries.py, exceptions.py, helpers.py)
- Split coordinator.py into coordinator/ package (core.py, cache.py, listeners.py, etc.)
- Move period_utils/ to coordinator/period_handlers/ for better organization
- All lint checks passing (no PLC0415 local import warnings)

Documentation Additions:
- Add docs/development/architecture.md with Mermaid diagrams (end-to-end flow, cache coordination)
- Add docs/development/timer-architecture.md (comprehensive 3-timer system documentation)
- Add docs/development/caching-strategy.md (4-layer cache system with invalidation logic)
- Update docs/development/README.md with cross-references
- Update AGENTS.md with new module structure and patterns

Smart Boundary Tolerance:
- Implement ±2 second tolerance for quarter-hour rounding
- Prevents premature interval switching during HA restarts (14:59:30 stays at 14:45)
- Enables boundary snapping for timer jitter (14:59:58 → 15:00)

Atomic Midnight Coordination:
- Add _check_midnight_turnover_needed() for race-free midnight handling
- Coordinate Timer #1 (HA DataUpdateCoordinator) with Timer #2 (quarter-hour refresh)
- Whoever runs first performs turnover, other skips gracefully

Timer Optimization:
- Change timer scheduling from second=1 to second=0 (absolute-time scheduling)
- Document load distribution rationale (unsynchronized API polling prevents thundering herd)
- Comprehensive explanation of 3 independent timers and their coordination

Impact: Cleaner code structure with resolved circular dependencies, comprehensive
documentation of timer and caching systems, and improved reliability during
boundary conditions and midnight turnovers. All changes are developer-facing
improvements with no user-visible behavior changes.
2025-11-18 17:32:36 +00:00
Julian Pawlowski
ef983d0a99 feat(sensor): migrate chart_data_export from binary_sensor to sensor platform
Migrated chart_data_export from binary_sensor to sensor to enable
compatibility with dashboard integrations (ApexCharts, etc.) that
require sensor entities for data selection.

Changes:
- Moved chart_data_export from binary_sensor/ to sensor/ platform
- Changed from boolean state (ON/OFF) to ENUM states ("pending", "ready", "error")
- Maintained all functionality: service call, attribute structure, caching
- Updated translations in all 5 languages (de, en, nb, nl, sv)
- Updated user documentation (sensors.md, services.md)
- Removed all chart_data_export code from binary_sensor platform

Technical details:
- State: "pending" (before first call), "ready" (data available), "error" (service failed)
- Attributes: timestamp + error (metadata) → descriptions → service response data
- Cache (_chart_data_response) bridges async service call and sync property access
- Service call: Triggered on async_added_to_hass() and async_update()

Impact: Dashboard integrations can now select chart_data_export sensor
in their entity pickers. No breaking changes for existing users - entity ID
changes from binary_sensor.* to sensor.*, but functionality identical.
2025-11-17 04:11:10 +00:00
Julian Pawlowski
38ce1c4c50 feat(chart_export): add Chart Data Export diagnostic sensor
Added optional diagnostic binary sensor that exposes get_chartdata
service results as entity attributes for legacy dashboard tools.

Key features:
- Entity: binary_sensor.tibber_home_NAME_chart_data_export
- Configurable via Options Flow Step 7 (YAML parameters)
- Calls get_chartdata service with user configuration
- Exposes response as attributes for chart cards
- Disabled by default (opt-in)
- Auto-refreshes on coordinator updates
- Manual refresh via homeassistant.update_entity

Implementation details:
- Added chart_data_export entity description to definitions.py
- Implemented state/attribute logic in binary_sensor/core.py
- Added YAML configuration schema in schemas.py
- Added validation in options_flow.py (Step 7)
- Service call validation with detailed error messages
- Attribute ordering: metadata first, descriptions next, service data last
- Dynamic icon mapping (database-export/database-alert)

Translations:
- Added chart_data_export_config to all 5 languages
- Added Step 7 descriptions with legacy warning
- Added invalid_yaml_syntax/invalid_yaml_structure error messages
- Added custom_translations for sensor descriptions

Documentation:
- Added Chart Data Export section to sensors.md
- Added comprehensive service guide to services.md
- Migration path from sensor to service
- Configuration instructions via Options Flow

Impact: Provides backward compatibility for dashboard tools that can
only read entity attributes (e.g., older ApexCharts versions). New
integrations should use tibber_prices.get_chartdata service directly.
2025-11-17 03:14:02 +00:00