├── .gitattributes ├── .pylintrc ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── feature.yml │ └── issue.yml ├── FUNDING.yml ├── workflows │ ├── check-on-hold.yml │ ├── hacs-validate.yml │ ├── release-drafter.yml │ ├── format-code.yml │ └── release.yml ├── dependabot.yml ├── release-drafter.yml └── scripts │ └── update_hacs_manifest.py ├── requirements.txt ├── scripts ├── lint ├── setup └── develop ├── hacs.json ├── .gitignore ├── config └── configuration.yaml ├── custom_components └── stromligning │ ├── manifest.json │ ├── const.py │ ├── base.py │ ├── __init__.py │ ├── config_flow.py │ ├── translations │ ├── en.json │ └── da.json │ ├── binary_sensor.py │ ├── api.py │ └── sensor.py ├── .devcontainer.json ├── .ruff.toml ├── custom_templates └── FindCheapestPeriod.jinja ├── README.md └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MESSAGES CONTROL] 2 | disable=E1123 -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | buy_me_a_coffee: mtrab 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | colorlog==6.10.1 2 | homeassistant==2025.12.0 3 | ruff==0.14.8 4 | pip>=21.0,<25.4 5 | -------------------------------------------------------------------------------- /scripts/lint: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | ruff check . --fix -------------------------------------------------------------------------------- /scripts/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | python3 -m pip install --requirement requirements.txt -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Strømligning", 3 | "render_readme": true, 4 | "homeassistant": "2024.10.0", 5 | "zip_release": true, 6 | "filename": "stromligning.zip", 7 | "country": [ 8 | "DK" 9 | ] 10 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # artifacts 2 | __pycache__ 3 | .pytest* 4 | *.egg-info 5 | */build/* 6 | */dist/* 7 | 8 | 9 | # misc 10 | .coverage 11 | .vscode 12 | coverage.xml 13 | notes.txt 14 | 15 | 16 | # Home Assistant configuration 17 | config/* 18 | !config/configuration.yaml -------------------------------------------------------------------------------- /config/configuration.yaml: -------------------------------------------------------------------------------- 1 | default_config: 2 | 3 | logger: 4 | default: warning 5 | logs: 6 | custom_components.stromligning: debug 7 | pystromligning: debug 8 | 9 | # If you need to debug uncomment the line below (doc: https://www.home-assistant.io/integrations/debugpy/) 10 | # debugpy: 11 | -------------------------------------------------------------------------------- /.github/workflows/check-on-hold.yml: -------------------------------------------------------------------------------- 1 | name: Check if PR is on hold 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - opened 7 | - reopened 8 | - synchronize 9 | - edited 10 | - labeled 11 | - unlabeled 12 | 13 | jobs: 14 | fail-if-on-hold: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Fail if PR is on hold 18 | if: contains(github.event.pull_request.labels.*.name, 'pr-on-hold') 19 | run: | 20 | echo "This PR is currently on hold." 21 | exit 1 -------------------------------------------------------------------------------- /custom_components/stromligning/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "stromligning", 3 | "name": "Str\u00f8mligning", 4 | "after_dependencies": [ 5 | "http" 6 | ], 7 | "codeowners": [ 8 | "@MTrab" 9 | ], 10 | "config_flow": true, 11 | "documentation": "https://github.com/MTrab/stromligning/blob/master/README.md", 12 | "iot_class": "cloud_polling", 13 | "issue_tracker": "https://github.com/MTrab/stromligning/issues", 14 | "requirements": [ 15 | "pystromligning==0.1.4" 16 | ], 17 | "version": "1.1.2" 18 | } -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | labels: 8 | - dependencies 9 | - patch 10 | - skip-changelog 11 | - package-ecosystem: pip 12 | directory: "/.github/workflows" 13 | schedule: 14 | interval: daily 15 | labels: 16 | - dependencies 17 | - patch 18 | - skip-changelog 19 | - package-ecosystem: pip 20 | directory: "/" 21 | schedule: 22 | interval: daily 23 | time: "04:00" 24 | labels: 25 | - dependencies 26 | - patch 27 | -------------------------------------------------------------------------------- /.github/workflows/hacs-validate.yml: -------------------------------------------------------------------------------- 1 | name: Code validation 2 | 3 | on: 4 | push: 5 | schedule: 6 | - cron: "0 0 * * *" 7 | 8 | jobs: 9 | validate-hassfest: 10 | name: Hassfest validation 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: checkout 14 | uses: actions/checkout@v6 15 | - name: validation 16 | uses: home-assistant/actions/hassfest@master 17 | 18 | validate-hacs: 19 | name: HACS validation 20 | runs-on: "ubuntu-latest" 21 | steps: 22 | - name: checkout 23 | uses: "actions/checkout@v6" 24 | - name: validation 25 | uses: "hacs/action@main" 26 | with: 27 | category: "integration" -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: 7 | - main 8 | pull_request: 9 | types: [opened, reopened, synchronize] 10 | 11 | jobs: 12 | update_release_draft: 13 | name: Update release draft 14 | permissions: 15 | contents: write 16 | pull-requests: write 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v6 21 | with: 22 | fetch-depth: 0 23 | - name: Create Release 24 | uses: release-drafter/release-drafter@v6 25 | env: 26 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 27 | -------------------------------------------------------------------------------- /scripts/develop: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | pip uninstall -y pystromligning || true 8 | # Create config dir if not present 9 | if [[ ! -d "${PWD}/config" ]]; then 10 | mkdir -p "${PWD}/config" 11 | hass --config "${PWD}/config" --script ensure_config 12 | fi 13 | 14 | # Set the path to custom_components 15 | ## This let's us have the structure we want /custom_components/integration_blueprint 16 | ## while at the same time have Home Assistant configuration inside /config 17 | ## without resulting to symlinks. 18 | export PYTHONPATH="${PYTHONPATH}:${PWD}/custom_components" 19 | 20 | # Start Home Assistant 21 | hass --config "${PWD}/config" --debug -------------------------------------------------------------------------------- /custom_components/stromligning/const.py: -------------------------------------------------------------------------------- 1 | """Consts used in the integration.""" 2 | 3 | # Startup banner 4 | STARTUP = """ 5 | ------------------------------------------------------------------- 6 | Strømligning 7 | 8 | Version: %s 9 | This is a custom integration 10 | If you have any issues with this you need to open an issue here: 11 | https://github.com/mtrab/stromligning/issues 12 | ------------------------------------------------------------------- 13 | """ 14 | 15 | ATTR_PRICES = "prices" 16 | ATTR_FORECAST_DATA = "forecast_data" 17 | 18 | CONF_AGGREGATION = "aggregation" 19 | CONF_COMPANY = "company" 20 | CONF_DEFAULT_NAME = "Strømligning" 21 | CONF_FORECASTS = "forecasts" 22 | 23 | DEFAULT_TEMPLATE = "{{0.0|float(0)}}" 24 | DOMAIN = "stromligning" 25 | 26 | PLATFORMS = ["sensor", "binary_sensor"] 27 | 28 | UPDATE_SIGNAL = f"{DOMAIN}_SIGNAL_UPDATE" 29 | UPDATE_SIGNAL_NEXT = f"{DOMAIN}_SIGNAL_UPDATE_NEXT" 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Make a request for a new feature in the Strømligning integration 3 | title: "[FR]: " 4 | labels: ["enhancement"] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | This form is only for requesting new features to the integration. 10 | 11 | Remember to add a descriptive title after the predefined text. 12 | - type: textarea 13 | validations: 14 | required: true 15 | attributes: 16 | label: Describe the feature you wish to make a request for 17 | description: >- 18 | Provide a clear and concise description of what you wish for. 19 | The more precise and detailed the more likely it is to be accepted and made. 20 | - type: textarea 21 | attributes: 22 | label: Describe alternatives you've considered 23 | description: >- 24 | Have you considered any alternatives (ie. other existing integrations that can handle this) 25 | - type: textarea 26 | attributes: 27 | label: Additional context 28 | description: >- 29 | Add any other context or screenshots about the feature request here. 30 | -------------------------------------------------------------------------------- /.devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Strømligning", 3 | "image": "mcr.microsoft.com/devcontainers/python:3.13-bookworm", 4 | "postCreateCommand": "scripts/setup", 5 | "appPort": [ 6 | "9127:8123" 7 | ], 8 | "portsAttributes": { 9 | "8123": { 10 | "label": "Home Assistant - Stromligning", 11 | "onAutoForward": "notify" 12 | } 13 | }, 14 | "customizations": { 15 | "vscode": { 16 | "extensions": [ 17 | "ms-python.python", 18 | "github.vscode-pull-request-github", 19 | "ryanluker.vscode-coverage-gutters", 20 | "ms-python.vscode-pylance", 21 | "ms-python.isort", 22 | "ms-python.black-formatter" 23 | ], 24 | "settings": { 25 | "files.eol": "\n", 26 | "editor.tabSize": 4, 27 | "terminal.integrated.shell.linux": "/bin/bash", 28 | "python.defaultInterpreterPath": "/usr/bin/python3", 29 | "python.analysis.autoSearchPaths": false, 30 | "python.linting.pylintEnabled": true, 31 | "python.linting.enabled": true, 32 | "python.formatting.provider": "black", 33 | "editor.formatOnPaste": false, 34 | "editor.formatOnSave": true, 35 | "editor.formatOnType": true, 36 | "files.trimTrailingWhitespace": true 37 | } 38 | } 39 | }, 40 | "remoteUser": "root", 41 | "features": { 42 | "ghcr.io/devcontainers/features/rust:1": {} 43 | } 44 | } -------------------------------------------------------------------------------- /.github/workflows/format-code.yml: -------------------------------------------------------------------------------- 1 | name: Format code 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | format: 10 | name: Format with black and isort 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v6 15 | with: 16 | fetch-depth: 0 17 | - name: Set up Python 3.8 18 | uses: actions/setup-python@v6.1.0 19 | with: 20 | python-version: 3.8 21 | - name: Cache 22 | uses: actions/cache@v4.3.0 23 | with: 24 | path: ~/.cache/pip 25 | key: pip-format 26 | - name: Install dependencies 27 | run: | 28 | python -m pip install --upgrade pip wheel 29 | python -m pip install --upgrade black isort 30 | - name: Pull again 31 | run: git pull || true 32 | - name: Run formatting 33 | run: | 34 | python -m isort -v --multi-line 3 --trailing-comma -l 88 --recursive . 35 | python -m black -v . 36 | - name: Commit files 37 | run: | 38 | if [ $(git diff HEAD | wc -l) -gt 30 ] 39 | then 40 | git config user.email "41898282+github-actions[bot]@users.noreply.github.com" 41 | git config user.name "GitHub Actions" 42 | git commit -m "Run formatting" -a || true 43 | git push || true 44 | fi -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | workflow_dispatch: 5 | release: 6 | types: [published] 7 | 8 | env: 9 | COMPONENT_DIR: stromligning 10 | 11 | jobs: 12 | release_zip_file: 13 | name: Prepare release asset 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Check out repository 17 | uses: actions/checkout@v6 18 | - name: Update manifest.json version to ${{ github.event.release.tag_name }} 19 | run: | 20 | python3 ${{ github.workspace }}/.github/scripts/update_hacs_manifest.py --version ${{ github.event.release.tag_name }} --path /custom_components/stromligning/ 21 | - name: Commit manifest update 22 | run: | 23 | git config user.name github-actions 24 | git config user.email github-actions@github.com 25 | git add ./custom_components/stromligning/manifest.json 26 | git commit -m "Updated manifest.json" 27 | git push origin HEAD:main 28 | - name: Create zip 29 | run: | 30 | cd custom_components/stromligning 31 | zip stromligning.zip -r ./ 32 | - name: Upload zip to release 33 | uses: svenstaro/upload-release-action@2.11.3 34 | with: 35 | repo_token: ${{ secrets.GITHUB_TOKEN }} 36 | file: ./custom_components/stromligning/stromligning.zip 37 | asset_name: stromligning.zip 38 | tag: ${{ github.ref }} 39 | overwrite: true 40 | -------------------------------------------------------------------------------- /custom_components/stromligning/base.py: -------------------------------------------------------------------------------- 1 | """Entity base definitions.""" 2 | 3 | from collections.abc import Callable 4 | from dataclasses import dataclass 5 | from datetime import datetime, timedelta 6 | 7 | from homeassistant.components.binary_sensor import BinarySensorEntityDescription 8 | from homeassistant.components.sensor import SensorEntityDescription 9 | from homeassistant.util import dt as dt_utils 10 | 11 | from .api import StromligningAPI 12 | from .const import UPDATE_SIGNAL 13 | 14 | 15 | @dataclass(frozen=True) 16 | class StromligningBaseEntityDescriptionMixin: 17 | """Describes a basic Stromligning entity.""" 18 | 19 | value_fn: Callable[[StromligningAPI], bool | str | int | float | datetime | None] 20 | 21 | 22 | @dataclass(frozen=True) 23 | class StromligningSensorEntityDescription( 24 | SensorEntityDescription, StromligningBaseEntityDescriptionMixin 25 | ): 26 | """Describes a Stromligning sensor.""" 27 | 28 | unit_fn: Callable[[StromligningAPI], None] | None = None 29 | update_signal: str = UPDATE_SIGNAL 30 | 31 | 32 | @dataclass(frozen=True) 33 | class StromligningBinarySensorEntityDescription( 34 | BinarySensorEntityDescription, StromligningBaseEntityDescriptionMixin 35 | ): 36 | """Describes a Stromligning sensor.""" 37 | 38 | unit_fn: Callable[[StromligningAPI], None] | None = None 39 | 40 | 41 | @staticmethod 42 | def get_next_midnight() -> datetime: 43 | """Return a datetime for the next midnight.""" 44 | return dt_utils.as_local( 45 | datetime.fromisoformat( 46 | (dt_utils.now() + timedelta(days=1)) 47 | .replace(hour=0, minute=0, second=0, microsecond=0) 48 | .isoformat() 49 | ) 50 | ) 51 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: 'v$RESOLVED_VERSION' 2 | tag-template: 'v$RESOLVED_VERSION' 3 | change-template: '- #$NUMBER $TITLE @$AUTHOR' 4 | sort-direction: ascending 5 | exclude-labels: 6 | - 'skip-changelog' 7 | categories: 8 | - title: '⚒️ Breaking Changes' 9 | labels: 10 | - breaking-change 11 | 12 | - title: '🚀 Features' 13 | labels: 14 | - 'feature request' 15 | - 'enhancement' 16 | 17 | - title: '🐛 Bug Fixes' 18 | labels: 19 | - 'fix' 20 | - 'bugfix' 21 | - 'bug' 22 | 23 | - title: '🧬 Changes to Charge Owner informations' 24 | labels: 25 | - chargeowner 26 | - chargeowners 27 | 28 | - title: '🧬 New Charge Owner(s) added' 29 | labels: 30 | - 'new chargeowner' 31 | 32 | - title: '🧰 Maintenance' 33 | label: 'chore' 34 | 35 | - title: '📦 Dependencies' 36 | labels: 37 | - 'dependencies' 38 | 39 | version-resolver: 40 | major: 41 | labels: 42 | - 'major' 43 | minor: 44 | labels: 45 | - 'minor' 46 | patch: 47 | labels: 48 | - 'patch' 49 | default: patch 50 | template: | 51 | ## Changes 52 | 53 | $CHANGES 54 | 55 | ## Say thanks 56 | 57 | Buy Me A Coffee 58 | 59 | autolabeler: 60 | - label: 'bug' 61 | branch: 62 | - '/fix\/.+/' 63 | - label: 'feature request' 64 | branch: 65 | - '/feature\/.+/' 66 | -------------------------------------------------------------------------------- /.ruff.toml: -------------------------------------------------------------------------------- 1 | # The contents of this file is based on https://github.com/home-assistant/core/blob/dev/pyproject.toml 2 | 3 | target-version = "py311" 4 | 5 | select = [ 6 | "B007", # Loop control variable {name} not used within loop body 7 | "B014", # Exception handler with duplicate exception 8 | "C", # complexity 9 | "D", # docstrings 10 | "E", # pycodestyle 11 | "F", # pyflakes/autoflake 12 | "ICN001", # import concentions; {name} should be imported as {asname} 13 | "PGH004", # Use specific rule codes when using noqa 14 | "PLC0414", # Useless import alias. Import alias does not rename original package. 15 | "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass 16 | "SIM117", # Merge with-statements that use the same scope 17 | "SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys() 18 | "SIM201", # Use {left} != {right} instead of not {left} == {right} 19 | "SIM212", # Use {a} if {a} else {b} instead of {b} if not {a} else {a} 20 | "SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'. 21 | "SIM401", # Use get from dict with default instead of an if block 22 | "T20", # flake8-print 23 | "TRY004", # Prefer TypeError exception for invalid type 24 | "RUF006", # Store a reference to the return value of asyncio.create_task 25 | "UP", # pyupgrade 26 | "W", # pycodestyle 27 | ] 28 | 29 | ignore = [ 30 | "D202", # No blank lines allowed after function docstring 31 | "D203", # 1 blank line required before class docstring 32 | "D213", # Multi-line docstring summary should start at the second line 33 | "D404", # First word of the docstring should not be This 34 | "D406", # Section name should end with a newline 35 | "D407", # Section name underlining 36 | "D411", # Missing blank line before section 37 | "E501", # line too long 38 | "E731", # do not assign a lambda expression, use a def 39 | ] 40 | 41 | [flake8-pytest-style] 42 | fixture-parentheses = false 43 | 44 | [pyupgrade] 45 | keep-runtime-typing = true 46 | 47 | [mccabe] 48 | max-complexity = 25 -------------------------------------------------------------------------------- /custom_templates/FindCheapestPeriod.jinja: -------------------------------------------------------------------------------- 1 | {%- macro FindCheapestPeriod(earliestDatetime, latestDatetime, durationTimedelta, findLastPeriodBoolean) -%} 2 | 3 | {# Prepare input parameters #} 4 | {%- set earliestDatetime = now() if earliestDatetime is not defined or earliestDatetime is not datetime else earliestDatetime -%} 5 | {%- set latestDatetime = now()+timedelta(days=7) if latestDatetime is not defined or latestDatetime is not datetime else latestDatetime -%} 6 | {%- set durationTimedelta = timedelta(hours=1) if durationTimedelta is not defined or durationTimedelta < timedelta(hours=1) else durationTimedelta -%} 7 | {%- set durationMinutes = durationTimedelta.total_seconds() // 60 | int -%} 8 | {%- set durationHours = "%.0f"|format((durationMinutes+30) // 60 | round | float) | int -%} 9 | 10 | {# Retrieve energy prices #} 11 | {%- set energyPriceToday = "sensor.stromligning_current_price_vat" -%} 12 | {%- set energyPriceTomorrow = "binary_sensor.stromligning_tomorrow_available_vat" -%} 13 | {%- set today = state_attr(energyPriceToday, 'prices') -%} 14 | {%- set tomorrow = state_attr(energyPriceTomorrow, 'prices') -%} 15 | {%- set prices = (today if today else []) + (tomorrow if tomorrow else []) -%} 16 | 17 | {# Calculate cheapest period #} 18 | {%- set result = namespace(priceSum=999999, priceStartTime=None) -%} 19 | {%- set prices_len = (prices | length) - durationHours | int -%} 20 | {%- for n in range(prices_len) -%} 21 | {%- set priceStartTime = prices[n].start -%} 22 | {%- if earliestDatetime <= priceStartTime and priceStartTime <= latestDatetime -%} 23 | {%- set priceSum = namespace(value=0) -%} 24 | {%- for i in range(durationHours) -%} 25 | {%- set priceSum.value = priceSum.value + prices[n+i].price -%} 26 | {%- endfor -%} 27 | {%- if priceSum.valueBuy Me A Coffee 7 | 8 | Stromligning for Home Assistant integrates Day Ahead spotprices for electricity, from the Stromligning API. 9 | 10 | The integration automatically recognises tariff settings from the Home Assistant home location coordinates and allows you to select your electricity vendor. 11 | 12 | ## Table of Content 13 | 14 | [**Installation**](#installation) 15 | 16 | [**Setup**](#setup) 17 | 18 | [**Use the custom template to show the next x cheapest hours**](#use-the-custom-template-to-show-the-next-x-cheapest-hours) 19 |   20 | 21 | ## Installation: 22 | 23 | ### Option 1 (easy) - HACS: 24 | 25 | * Ensure that HACS is installed. 26 | * Search for and install the "Stromligning" integration. 27 | * Restart Home Assistant. 28 | 29 | ### Option 2 - Add custom repository to HACS: 30 | 31 | * See [this link](https://www.hacs.xyz/docs/faq/custom_repositories/) for how to add a custom repository to HACS. 32 | * Add `https://github.com/MTrab/stromligning` as custom repository of type Integration 33 | * Search for and install the "Stromligning" integration. 34 | * Restart Home Assistant. 35 | 36 | ### Option 3 - Manual installation: 37 | 38 | * Download the latest release. 39 | * Unpack the release and copy the custom\_components/stromligning directory into the custom\_components directory of your Home Assistant installation. 40 | * Restart Home Assistant. 41 | 42 | ## Setup 43 | 44 | My Home Assistant shortcut: 45 | 46 | [![](https://my.home-assistant.io/badges/config_flow_start.svg)](https://my.home-assistant.io/redirect/config_flow_start/?domain=stromligning) 47 | 48 | Or go to Home Assistant > Settings > Integrations 49 | 50 | Add "Stromligning" integration _(If it doesn't show, try CTRL+F5 to force a refresh of the page)_ 51 | 52 | ## Use the custom template to show the next x cheapest hours 53 | 54 | Copy the `custom_templates/FindCheapestPrice.jinja` to the `custom_templates` directory in your config folder (if it doesn't exist then create the folder) 55 | Reload Home Assistant and use the Jinja template by inserting the example below in a template sensor helper 56 | 57 | ``` 58 | {% from 'FindCheapestPeriod.jinja' import FindCheapestPeriod%} 59 | {% set earliestStartTime = now() %} 60 | {% set latestStartTime = now() + timedelta(days=2) %} 61 | {% set periodLength = timedelta(hours=3) %} 62 | {{ FindCheapestPeriod(earliestStartTime , latestStartTime , periodLength, false) }} 63 | ``` 64 | 65 | This will result in a sensor showing the cheapest 3 hours within the known prices 66 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue.yml: -------------------------------------------------------------------------------- 1 | name: Report a bug / issue 2 | description: Report an issue with the Strømligning integration 3 | labels: ["bug"] 4 | assignees: 5 | - MTrab 6 | body: 7 | - type: markdown 8 | attributes: 9 | value: | 10 | This issue form is for reporting bugs only! 11 | - type: textarea 12 | validations: 13 | required: true 14 | attributes: 15 | label: Describe the issue 16 | description: >- 17 | Describe the issue you are experiencing here. 18 | Describe what you were trying to do and what happened. 19 | 20 | Provide a clear and concise description of what the problem is. 21 | - type: markdown 22 | attributes: 23 | value: | 24 | ## Environment 25 | - type: input 26 | id: version 27 | validations: 28 | required: true 29 | attributes: 30 | label: What version of Home Assistant Core has the issue? 31 | placeholder: core- 32 | description: > 33 | Can be found in: [Settings ⇒ System ⇒ Repairs ⇒ Three Dots in Upper Right ⇒ System information](https://my.home-assistant.io/redirect/system_health/). 34 | 35 | [![Open your Home Assistant instance and show the system information.](https://my.home-assistant.io/badges/system_health.svg)](https://my.home-assistant.io/redirect/system_health/) 36 | - type: input 37 | attributes: 38 | label: What was the last working version of Home Assistant Core? 39 | placeholder: core- 40 | description: > 41 | If known, otherwise leave blank. 42 | - type: dropdown 43 | validations: 44 | required: true 45 | attributes: 46 | label: What type of installation are you running? 47 | description: > 48 | Can be found in: [Settings ⇒ System ⇒ Repairs ⇒ Three Dots in Upper Right ⇒ System information](https://my.home-assistant.io/redirect/system_health/). 49 | 50 | [![Open your Home Assistant instance and show the system information.](https://my.home-assistant.io/badges/system_health.svg)](https://my.home-assistant.io/redirect/system_health/) 51 | options: 52 | - Home Assistant OS 53 | - Home Assistant Container 54 | - Home Assistant Supervised 55 | - Home Assistant Core 56 | - type: markdown 57 | attributes: 58 | value: | 59 | # Details 60 | # - type: textarea 61 | # validations: 62 | # required: true 63 | # attributes: 64 | # label: Diagnostics information 65 | # placeholder: "drag-and-drop the diagnostics data file here (do not copy-and-paste the content)" 66 | # description: >- 67 | # This integrations provide the ability to [download diagnostic data](https://www.home-assistant.io/docs/configuration/troubleshooting/#debug-logs-and-diagnostics). 68 | 69 | # **It would really help if you could download the diagnostics data for the device you are having issues with, 70 | # and drag-and-drop that file into the textbox below.** 71 | 72 | # It generally allows pinpointing defects and thus resolving issues faster. 73 | 74 | # If you are unable to provide the diagnostics (ie. you cannot add the integration), please write **None** in this field. 75 | - type: textarea 76 | attributes: 77 | label: Anything in the logs that might be useful for us? 78 | description: For example, error message, or stack traces. 79 | render: txt 80 | - type: textarea 81 | attributes: 82 | label: Additional information 83 | description: > 84 | If you have any additional information for us, use the field below. 85 | -------------------------------------------------------------------------------- /custom_components/stromligning/__init__.py: -------------------------------------------------------------------------------- 1 | """Add support for Stromligning energy prices.""" 2 | 3 | import logging 4 | from datetime import datetime 5 | from random import randint 6 | 7 | from homeassistant.config_entries import ConfigEntry 8 | from homeassistant.core import HomeAssistant 9 | from homeassistant.exceptions import ConfigEntryNotReady 10 | from homeassistant.helpers.dispatcher import async_dispatcher_send 11 | from homeassistant.helpers.event import ( 12 | async_track_time_change, 13 | async_track_utc_time_change, 14 | ) 15 | from homeassistant.loader import async_get_integration 16 | from homeassistant.util import slugify as util_slugify 17 | from pystromligning import Aggregation 18 | from pystromligning.exceptions import InvalidAPIResponse, TooManyRequests 19 | 20 | from .api import StromligningAPI 21 | from .const import DOMAIN, PLATFORMS, STARTUP, UPDATE_SIGNAL 22 | 23 | LOGGER = logging.getLogger(__name__) 24 | 25 | 26 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 27 | """Set up Strømligning from a config entry.""" 28 | hass.data.setdefault(DOMAIN, {}) 29 | integration = await async_get_integration(hass, DOMAIN) 30 | LOGGER.info(STARTUP, integration.version) 31 | rand_min = randint(5, 40) 32 | rand_sec = randint(0, 59) 33 | 34 | api = StromligningAPI(hass, entry, rand_min, rand_sec) 35 | hass.data[DOMAIN][entry.entry_id] = api 36 | 37 | forecasts = entry.options.get("forecasts", False) 38 | aggregation = entry.options.get("aggregation", Aggregation.HOUR) 39 | 40 | try: 41 | await api.set_location() 42 | await api.update_prices() 43 | await api.prepare_data() 44 | 45 | async def get_new_data(n): # type: ignore pylint: disable=unused-argument, invalid-name 46 | """Fetch new data for tomorrows prices at 13:00ish CET.""" 47 | LOGGER.debug("Getting latest dataset") 48 | 49 | await api.update_prices() 50 | await api.prepare_data() 51 | 52 | async_dispatcher_send(hass, util_slugify(UPDATE_SIGNAL)) 53 | 54 | async def new_day(n): # type: ignore pylint: disable=unused-argument, invalid-name 55 | """Handle data on new day.""" 56 | LOGGER.debug("New day function called") 57 | 58 | if len(api.prices_tomorrow) > 0: 59 | api.prices_today = api.prices_tomorrow 60 | api.prices_tomorrow = [] 61 | api.tomorrow_available = False 62 | else: 63 | await api.update_prices() 64 | await api.prepare_data() 65 | 66 | async_dispatcher_send(hass, util_slugify(UPDATE_SIGNAL)) 67 | 68 | async def new_quarter(n): # type: ignore pylint: disable=unused-argument, invalid-name 69 | """Tell the sensor to update to a new quarter.""" 70 | LOGGER.debug("New quarter, updating state") 71 | 72 | if len(api.prices_tomorrow) == 0 and datetime.now().hour > 13: 73 | LOGGER.info( 74 | "Prices for tomorrow is missing - trying to fetch data from API" 75 | ) 76 | await api.update_prices() 77 | await api.prepare_data() 78 | 79 | async_dispatcher_send(hass, util_slugify(UPDATE_SIGNAL)) 80 | 81 | # Handle dataset updates 82 | update_tomorrow = async_track_time_change( 83 | hass, 84 | get_new_data, 85 | hour=13, # LOCAL time!! 86 | minute=rand_min, 87 | second=rand_sec, 88 | ) 89 | 90 | if forecasts: 91 | update_forecast = async_track_utc_time_change( 92 | hass, get_new_data, hour="/6", minute=10, second=0 # UTC time!! 93 | ) 94 | api.listeners.append(update_forecast) 95 | 96 | if aggregation == Aggregation.MIN15: 97 | update_new_quarter = async_track_time_change( 98 | hass, new_quarter, minute="/15", second=1 99 | ) 100 | else: 101 | update_new_quarter = async_track_time_change( 102 | hass, new_quarter, hour="/1", minute=0, second=1 103 | ) 104 | 105 | update_new_day = async_track_time_change( 106 | hass, new_day, hour=0, minute=0, second=1 107 | ) 108 | 109 | api.listeners.append(update_new_quarter) 110 | api.listeners.append(update_new_day) 111 | api.listeners.append(update_tomorrow) 112 | 113 | await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) 114 | 115 | return True 116 | except TooManyRequests: 117 | raise ConfigEntryNotReady("Too many requests to the API within 15 minutes") 118 | # LOGGER.info( 119 | # "You made too many requests to the API within a 15 minutes window - try again later" 120 | # ) 121 | 122 | # return False 123 | except InvalidAPIResponse as ex: 124 | LOGGER.error("Unable to connect to the Stromligning API: %s", ex) 125 | raise ConfigEntryNotReady from ex 126 | 127 | 128 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 129 | """Unload a config entry.""" 130 | for platform in PLATFORMS: 131 | unload_ok = await hass.config_entries.async_forward_entry_unload( 132 | entry, platform 133 | ) 134 | 135 | if unload_ok: 136 | for unsub in hass.data[DOMAIN][entry.entry_id].listeners: 137 | unsub() 138 | hass.data[DOMAIN].pop(entry.entry_id) 139 | 140 | return True 141 | 142 | return False 143 | 144 | 145 | async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: 146 | """Reload config entry.""" 147 | await async_unload_entry(hass, entry) 148 | await async_setup_entry(hass, entry) 149 | -------------------------------------------------------------------------------- /custom_components/stromligning/config_flow.py: -------------------------------------------------------------------------------- 1 | """Config flow for setting up the integration.""" 2 | 3 | import logging 4 | from typing import Any 5 | 6 | import voluptuous as vol 7 | from homeassistant import config_entries 8 | from homeassistant.const import CONF_NAME 9 | from homeassistant.core import callback 10 | from homeassistant.helpers.event import async_call_later 11 | from pystromligning import Aggregation, Stromligning 12 | from pystromligning.exceptions import TooManyRequests 13 | 14 | from . import async_setup_entry, async_unload_entry 15 | from .const import ( 16 | CONF_AGGREGATION, 17 | CONF_COMPANY, 18 | CONF_DEFAULT_NAME, 19 | CONF_FORECASTS, 20 | DOMAIN, 21 | ) 22 | 23 | LOGGER = logging.getLogger(__name__) 24 | 25 | 26 | class StromligningOptionsFlow(config_entries.OptionsFlow): 27 | """Stromligning options flow handler.""" 28 | 29 | def __init__(self, config_entry: config_entries.ConfigEntry) -> None: 30 | """Initialize Stromligning options flow.""" 31 | self._errors = {} 32 | 33 | async def _do_update( 34 | self, *args, **kwargs # pylint: disable=unused-argument 35 | ) -> None: 36 | """Update after settings change.""" 37 | await async_unload_entry(self.hass, self.config_entry) 38 | await async_setup_entry(self.hass, self.config_entry) 39 | 40 | async def async_step_init(self, user_input: Any | None = None): 41 | """Handle the initial options flow step.""" 42 | errors = {} 43 | 44 | api = self.hass.data[DOMAIN][self.config_entry.entry_id]._data 45 | 46 | if user_input is not None and "base" not in errors: 47 | LOGGER.debug("Saving settings") 48 | for company in api.available_companies: 49 | if company["name"] == user_input[CONF_COMPANY]: 50 | user_input[CONF_COMPANY] = company["id"] 51 | break 52 | 53 | async_call_later(self.hass, 2, self._do_update) 54 | return self.async_create_entry( 55 | title=self.config_entry.data.get(CONF_NAME), 56 | data=user_input, 57 | description=f"Strømligning - {self.config_entry.data.get(CONF_NAME)}", 58 | ) 59 | 60 | LOGGER.debug("Showing options form") 61 | 62 | selected_company: str | None = None 63 | company_list: list = [] 64 | for company in api.available_companies: 65 | if company["id"] == self.config_entry.options[CONF_COMPANY]: 66 | selected_company = company["name"] 67 | 68 | if company["name"] in company_list: 69 | continue 70 | 71 | company_list.append(company["name"]) 72 | 73 | scheme = vol.Schema( 74 | { 75 | vol.Required(CONF_COMPANY, default=selected_company): vol.In( 76 | company_list 77 | ), 78 | vol.Required( 79 | CONF_AGGREGATION, 80 | default=self.config_entry.options.get(CONF_AGGREGATION, "1h"), 81 | ): vol.In(Aggregation.values()), 82 | vol.Required( 83 | CONF_FORECASTS, 84 | default=self.config_entry.options.get(CONF_FORECASTS, False), 85 | ): bool, 86 | } 87 | ) 88 | 89 | return self.async_show_form(step_id="init", data_schema=scheme, errors=errors) 90 | 91 | 92 | class StromligningConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): 93 | """Handle a config flow for Stromligning.""" 94 | 95 | VERSION = 1 96 | CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL 97 | 98 | @staticmethod 99 | @callback 100 | def async_get_options_flow( 101 | config_entry: config_entries.ConfigEntry, 102 | ) -> StromligningOptionsFlow: 103 | """Get the options flow for this handler.""" 104 | return StromligningOptionsFlow(config_entry) 105 | 106 | async def async_step_user(self, user_input: Any | None = None): 107 | """Handle the initial config flow step.""" 108 | errors = {} 109 | 110 | try: 111 | api = Stromligning() 112 | await self.hass.async_add_executor_job( 113 | api.set_location, self.hass.config.latitude, self.hass.config.longitude 114 | ) 115 | except TooManyRequests: 116 | errors["base"] = "too_many_requests" 117 | 118 | if user_input is not None and "base" not in errors: 119 | await self.async_set_unique_id(f"{user_input[CONF_NAME]}_stromligning") 120 | 121 | for company in api.available_companies: 122 | if company["name"] == user_input[CONF_COMPANY]: 123 | user_input[CONF_COMPANY] = company["id"] 124 | break 125 | 126 | return self.async_create_entry( 127 | title=user_input[CONF_NAME], 128 | data={"name": user_input[CONF_NAME]}, 129 | options=user_input, 130 | description=f"Strømligning - {user_input[CONF_NAME]}", 131 | ) 132 | 133 | LOGGER.debug("Showing configuration form") 134 | 135 | company_list: list = [] 136 | for company in api.available_companies: 137 | if company["name"] in company_list: 138 | continue 139 | company_list.append(company["name"]) 140 | 141 | scheme = vol.Schema( 142 | { 143 | vol.Required(CONF_NAME, default=CONF_DEFAULT_NAME): str, 144 | vol.Required(CONF_COMPANY): vol.In(company_list), 145 | vol.Required(CONF_AGGREGATION): vol.In(Aggregation.values()), 146 | vol.Required(CONF_FORECASTS, default=False): bool, 147 | } 148 | ) 149 | 150 | return self.async_show_form(step_id="user", data_schema=scheme, errors=errors) 151 | -------------------------------------------------------------------------------- /custom_components/stromligning/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "abort": { 4 | "already_configured": "Integration with same name already existing" 5 | }, 6 | "error": { 7 | "too_many_requests": "Too many requests to the API - try again in 15 minutes" 8 | }, 9 | "step": { 10 | "user": { 11 | "data": { 12 | "name": "Name for this integration", 13 | "company": "Electricity provider", 14 | "aggregation": "Resolution of prices", 15 | "forecasts": "Include price forecasts for the next week? (may be inaccurate)" 16 | } 17 | } 18 | } 19 | }, 20 | "options": { 21 | "abort": { 22 | "already_configured": "Integration with same name already existing" 23 | }, 24 | "error": { 25 | "too_many_requests": "Too many requests to the API - try again in 15 minutes" 26 | }, 27 | "step": { 28 | "init": { 29 | "data": { 30 | "company": "Electricity provider", 31 | "aggregation": "Resolution of prices", 32 | "forecasts": "Include price forecasts for the next week? (may be inaccurate)" 33 | } 34 | } 35 | } 36 | }, 37 | "selector": { 38 | "aggregation": { 39 | "options": { 40 | "15m": "15 minutes", 41 | "1h": "Hourly" 42 | } 43 | } 44 | }, 45 | "entity": { 46 | "sensor": { 47 | "current_price_vat": { 48 | "name": "Current incl. VAT", 49 | "state_attributes": { 50 | "prices": { 51 | "name": "Prices today" 52 | } 53 | } 54 | }, 55 | "current_price_ex_vat": { 56 | "name": "Current excl. VAT", 57 | "state_attributes": { 58 | "prices": { 59 | "name": "Prices today" 60 | } 61 | } 62 | }, 63 | "distribution_vat": { 64 | "name": "Provider transportexpenses incl. VAT" 65 | }, 66 | "distribution_ex_vat": { 67 | "name": "Provider transportexpenses excl. VAT" 68 | }, 69 | "electricity_tax_vat": { 70 | "name": "Electricity tax incl. VAT" 71 | }, 72 | "electricity_tax_ex_vat": { 73 | "name": "Electricity tax excl. VAT" 74 | }, 75 | "forecasts_vat": { 76 | "name": "Price forecasts incl. VAT", 77 | "state_attributes": { 78 | "prices": { 79 | "name": "Prices next week" 80 | } 81 | } 82 | }, 83 | "forecasts_ex_vat": { 84 | "name": "Price forecasts excl. VAT", 85 | "state_attributes": { 86 | "prices": { 87 | "name": "Prices next week" 88 | } 89 | } 90 | }, 91 | "net_owner": { 92 | "name": "Net operator" 93 | }, 94 | "nettariff_vat": { 95 | "name": "Nettariff incl. VAT" 96 | }, 97 | "nettariff_ex_vat": { 98 | "name": "Nettariff excl. VAT" 99 | }, 100 | "next_data_refresh": { 101 | "name": "Next data update" 102 | }, 103 | "provider": { 104 | "name": "Provider agreement" 105 | }, 106 | "spotprice_vat": { 107 | "name": "Spotprice incl. VAT" 108 | }, 109 | "spotprice_ex_vat": { 110 | "name": "Spotprice excl. VAT" 111 | }, 112 | "surcharge_vat": { 113 | "name": "Spotprice surcharge incl. VAT" 114 | }, 115 | "surcharge_ex_vat": { 116 | "name": "Spotprice surcharge excl. VAT" 117 | }, 118 | "systemtariff_vat": { 119 | "name": "Systemtariff incl. VAT" 120 | }, 121 | "systemtariff_ex_vat": { 122 | "name": "Systemtariff excl. VAT" 123 | }, 124 | "today_min_vat": { 125 | "name": "Minimum price rest of the day incl. VAT", 126 | "state_attributes": { 127 | "at": { 128 | "name": "At" 129 | } 130 | } 131 | }, 132 | "today_min_ex_vat": { 133 | "name": "Minimum price rest of the day excl. VAT", 134 | "state_attributes": { 135 | "at": { 136 | "name": "At" 137 | } 138 | } 139 | }, 140 | "today_max_vat": { 141 | "name": "Maximum price rest of the day incl. VAT", 142 | "state_attributes": { 143 | "at": { 144 | "name": "At" 145 | } 146 | } 147 | }, 148 | "today_max_ex_vat": { 149 | "name": "Maximum price rest of the day excl. VAT", 150 | "state_attributes": { 151 | "at": { 152 | "name": "At" 153 | } 154 | } 155 | }, 156 | "today_mean_vat": { 157 | "name": "Mean price rest of the day incl. VAT" 158 | }, 159 | "today_mean_ex_vat": { 160 | "name": "Mean price rest of the day excl. VAT" 161 | }, 162 | "tomorrow_min_vat": { 163 | "name": "Minimum price tomorrow incl. VAT", 164 | "state": { 165 | "unknown": "Unknown" 166 | }, 167 | "state_attributes": { 168 | "at": { 169 | "name": "At" 170 | } 171 | } 172 | }, 173 | "tomorrow_min_ex_vat": { 174 | "name": "Minimum price tomorrow excl. VAT", 175 | "state": { 176 | "unknown": "Unknown" 177 | }, 178 | "state_attributes": { 179 | "at": { 180 | "name": "At" 181 | } 182 | } 183 | }, 184 | "tomorrow_max_vat": { 185 | "name": "Maximum price tomorrow incl. VAT", 186 | "state": { 187 | "unknown": "Unknown" 188 | }, 189 | "state_attributes": { 190 | "at": { 191 | "name": "At" 192 | } 193 | } 194 | }, 195 | "tomorrow_max_ex_vat": { 196 | "name": "Maximum price tomorrow excl. VAT", 197 | "state": { 198 | "unknown": "Unknown" 199 | }, 200 | "state_attributes": { 201 | "at": { 202 | "name": "At" 203 | } 204 | } 205 | }, 206 | "tomorrow_mean_vat": { 207 | "name": "Mean price tomorrow incl. VAT", 208 | "state": { 209 | "unknown": "Unknown" 210 | } 211 | }, 212 | "tomorrow_mean_ex_vat": { 213 | "name": "Mean price tomorrow excl. VAT", 214 | "state": { 215 | "unknown": "Unknown" 216 | } 217 | } 218 | }, 219 | "binary_sensor": { 220 | "tomorrow_available_vat": { 221 | "name": "Prices for tomorrow incl. VAT", 222 | "state": { 223 | "on": "Available", 224 | "off": "Not available yet" 225 | }, 226 | "state_attributes": { 227 | "available_at": { 228 | "name": "Available at" 229 | }, 230 | "prices": { 231 | "name": "Prices tomorrow" 232 | }, 233 | "forecast_data": { 234 | "name": "Origins from forecast data", 235 | "state": { 236 | "true": "Yes", 237 | "false": "No" 238 | } 239 | } 240 | } 241 | }, 242 | "tomorrow_available_ex_vat": { 243 | "name": "Prices for tomorrow excl. VAT", 244 | "state": { 245 | "on": "Available", 246 | "off": "Not available yet" 247 | }, 248 | "state_attributes": { 249 | "available_at": { 250 | "name": "Available at" 251 | }, 252 | "prices": { 253 | "name": "Prices tomorrow" 254 | }, 255 | "forecast_data": { 256 | "name": "Origins from forecast data", 257 | "state": { 258 | "true": "Yes", 259 | "false": "No" 260 | } 261 | } 262 | } 263 | }, 264 | "tomorrow_spotprice_vat": { 265 | "name": "Tomorrow spotprices incl. VAT", 266 | "state": { 267 | "on": "Available", 268 | "off": "Not available yet" 269 | }, 270 | "state_attributes": { 271 | "available_at": { 272 | "name": "Available at" 273 | }, 274 | "prices": { 275 | "name": "Spotprices tomorrow" 276 | }, 277 | "forecast_data": { 278 | "name": "Origins from forecast data", 279 | "state": { 280 | "true": "Yes", 281 | "false": "No" 282 | } 283 | } 284 | } 285 | }, 286 | "tomorrow_spotprice_ex_vat": { 287 | "name": "Tomorrow spotprices excl. VAT", 288 | "state": { 289 | "on": "Available", 290 | "off": "Not available yet" 291 | }, 292 | "state_attributes": { 293 | "available_at": { 294 | "name": "Available at" 295 | }, 296 | "prices": { 297 | "name": "Spotprices tomorrow" 298 | }, 299 | "forecast_data": { 300 | "name": "Origins from forecast data", 301 | "state": { 302 | "true": "Yes", 303 | "false": "No" 304 | } 305 | } 306 | } 307 | } 308 | } 309 | } 310 | } -------------------------------------------------------------------------------- /custom_components/stromligning/translations/da.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "abort": { 4 | "already_configured": "Integration med samme navn eksisterer allerede" 5 | }, 6 | "error": { 7 | "too_many_requests": "For mange API-forespørgsler – prøv igen om 15 minutter" 8 | }, 9 | "step": { 10 | "user": { 11 | "data": { 12 | "name": "Navn til integrationen", 13 | "company": "Elleverandør", 14 | "aggregation": "Dataopløsning på priser", 15 | "forecasts": "Inkluder prisudsigter for den næste uge? (kan være unøjagtige)" 16 | } 17 | } 18 | } 19 | }, 20 | "options": { 21 | "abort": { 22 | "already_configured": "Integration med samme navn eksisterer allerede" 23 | }, 24 | "error": { 25 | "too_many_requests": "For mange API-forespørgsler – prøv igen om 15 minutter" 26 | }, 27 | "step": { 28 | "init": { 29 | "data": { 30 | "company": "Elleverandør", 31 | "aggregation": "Dataopløsning på priser", 32 | "forecasts": "Inkluder prisudsigter for den næste uge? (kan være unøjagtige)" 33 | } 34 | } 35 | } 36 | }, 37 | "selector": { 38 | "aggregation": { 39 | "options": { 40 | "15m": "15 minutter", 41 | "1h": "1 time (gennemsnit)" 42 | } 43 | } 44 | }, 45 | "entity": { 46 | "sensor": { 47 | "current_price_vat": { 48 | "name": "Aktuel inkl. moms", 49 | "state_attributes": { 50 | "prices": { 51 | "name": "Priser i dag" 52 | } 53 | } 54 | }, 55 | "current_price_ex_vat": { 56 | "name": "Aktuel ekskl. moms", 57 | "state_attributes": { 58 | "prices": { 59 | "name": "Priser i dag" 60 | } 61 | } 62 | }, 63 | "distribution_vat": { 64 | "name": "Transporttarif til netselskab inkl. moms" 65 | }, 66 | "distribution_ex_vat": { 67 | "name": "Transporttarif til netselskab ekskl. moms" 68 | }, 69 | "electricity_tax_vat": { 70 | "name": "Elafgift inkl. moms" 71 | }, 72 | "electricity_tax_ex_vat": { 73 | "name": "Elafgift ekskl. moms" 74 | }, 75 | "forecasts_vat": { 76 | "name": "Prisudsigt inkl. moms", 77 | "state_attributes": { 78 | "prices": { 79 | "name": "Priser den næste uge" 80 | } 81 | } 82 | }, 83 | "forecasts_ex_vat": { 84 | "name": "Prisudsigt ekskl. moms", 85 | "state_attributes": { 86 | "prices": { 87 | "name": "Priser den næste uge" 88 | } 89 | } 90 | }, 91 | "net_owner": { 92 | "name": "Elnetselskab" 93 | }, 94 | "nettariff_vat": { 95 | "name": "Nettarif inkl. moms" 96 | }, 97 | "nettariff_ex_vat": { 98 | "name": "Nettarif ekskl. moms" 99 | }, 100 | "next_data_refresh": { 101 | "name": "Næste dataopdatering" 102 | }, 103 | "provider": { 104 | "name": "Elaftale" 105 | }, 106 | "spotprice_vat": { 107 | "name": "Spotpris inkl. moms" 108 | }, 109 | "spotprice_ex_vat": { 110 | "name": "Spotpris ekskl. moms" 111 | }, 112 | "surcharge_vat": { 113 | "name": "Tillæg til spotpris inkl. moms" 114 | }, 115 | "surcharge_ex_vat": { 116 | "name": "Tillæg til spotpris ekskl. moms" 117 | }, 118 | "systemtariff_vat": { 119 | "name": "Systemtarif inkl. moms" 120 | }, 121 | "systemtariff_ex_vat": { 122 | "name": "Systemtarif ekskl. moms" 123 | }, 124 | "today_min_vat": { 125 | "name": "Laveste pris resten af dagen inkl. moms", 126 | "state_attributes": { 127 | "at": { 128 | "name": "Tidspunkt" 129 | } 130 | } 131 | }, 132 | "today_min_ex_vat": { 133 | "name": "Laveste pris resten af dagen ekskl. moms", 134 | "state_attributes": { 135 | "at": { 136 | "name": "Tidspunkt" 137 | } 138 | } 139 | }, 140 | "today_max_vat": { 141 | "name": "Højeste pris resten af dagen inkl. moms", 142 | "state_attributes": { 143 | "at": { 144 | "name": "Tidspunkt" 145 | } 146 | } 147 | }, 148 | "today_max_ex_vat": { 149 | "name": "Højeste pris resten af dagen ekskl. moms", 150 | "state_attributes": { 151 | "at": { 152 | "name": "Tidspunkt" 153 | } 154 | } 155 | }, 156 | "today_mean_vat": { 157 | "name": "Gennemsnitspris resten af dagen inkl. moms" 158 | }, 159 | "today_mean_ex_vat": { 160 | "name": "Gennemsnitspris resten af dagen ekskl. moms" 161 | }, 162 | "tomorrow_min_vat": { 163 | "name": "Laveste pris i morgen inkl. moms", 164 | "state": { 165 | "unknown": "Ukendt" 166 | }, 167 | "state_attributes": { 168 | "at": { 169 | "name": "Tidspunkt" 170 | } 171 | } 172 | }, 173 | "tomorrow_min_ex_vat": { 174 | "name": "Laveste pris i morgen ekskl. moms", 175 | "state": { 176 | "unknown": "Ukendt" 177 | }, 178 | "state_attributes": { 179 | "at": { 180 | "name": "Tidspunkt" 181 | } 182 | } 183 | }, 184 | "tomorrow_max_vat": { 185 | "name": "Højeste pris i morgen inkl. moms", 186 | "state": { 187 | "unknown": "Ukendt" 188 | }, 189 | "state_attributes": { 190 | "at": { 191 | "name": "Tidspunkt" 192 | } 193 | } 194 | }, 195 | "tomorrow_max_ex_vat": { 196 | "name": "Højeste pris i morgen ekskl. moms", 197 | "state": { 198 | "unknown": "Ukendt" 199 | }, 200 | "state_attributes": { 201 | "at": { 202 | "name": "Tidspunkt" 203 | } 204 | } 205 | }, 206 | "tomorrow_mean_vat": { 207 | "name": "Gennemsnitspris i morgen inkl. moms", 208 | "state": { 209 | "unknown": "Ukendt" 210 | } 211 | }, 212 | "tomorrow_mean_ex_vat": { 213 | "name": "Gennemsnitspris i morgen ekskl. moms", 214 | "state": { 215 | "unknown": "Ukendt" 216 | } 217 | } 218 | }, 219 | "binary_sensor": { 220 | "tomorrow_available_vat": { 221 | "name": "Priser for i morgen inkl. moms", 222 | "state": { 223 | "on": "Klar", 224 | "off": "Endnu ikke klar" 225 | }, 226 | "state_attributes": { 227 | "available_at": { 228 | "name": "Forventes klar" 229 | }, 230 | "prices": { 231 | "name": "Priser for i morgen" 232 | }, 233 | "forecast_data": { 234 | "name": "Priser stammer fra udsigter", 235 | "state": { 236 | "true": "Ja", 237 | "false": "Nej" 238 | } 239 | } 240 | } 241 | }, 242 | "tomorrow_available_ex_vat": { 243 | "name": "Priser for i morgen ekskl. moms", 244 | "state": { 245 | "on": "Klar", 246 | "off": "Endnu ikke klar" 247 | }, 248 | "state_attributes": { 249 | "available_at": { 250 | "name": "Forventes klar" 251 | }, 252 | "prices": { 253 | "name": "Priser for i morgen" 254 | }, 255 | "forecast_data": { 256 | "name": "Priser stammer fra udsigter", 257 | "state": { 258 | "true": "Ja", 259 | "false": "Nej" 260 | } 261 | } 262 | } 263 | }, 264 | "tomorrow_spotprice_vat": { 265 | "name": "Spotpriser for i morgen inkl. moms", 266 | "state": { 267 | "on": "Klar", 268 | "off": "Endnu ikke klar" 269 | }, 270 | "state_attributes": { 271 | "available_at": { 272 | "name": "Forventes klar" 273 | }, 274 | "prices": { 275 | "name": "Spotpriser for i morgen" 276 | }, 277 | "forecast_data": { 278 | "name": "Priser stammer fra udsigter", 279 | "state": { 280 | "true": "Ja", 281 | "false": "Nej" 282 | } 283 | } 284 | } 285 | }, 286 | "tomorrow_spotprice_ex_vat": { 287 | "name": "Spotpriser for i morgen ekskl. moms", 288 | "state": { 289 | "on": "Klar", 290 | "off": "Endnu ikke klar" 291 | }, 292 | "state_attributes": { 293 | "available_at": { 294 | "name": "Forventes klar" 295 | }, 296 | "prices": { 297 | "name": "Spotpriser for i morgen" 298 | }, 299 | "forecast_data": { 300 | "name": "Priser stammer fra udsigter", 301 | "state": { 302 | "true": "Ja", 303 | "false": "Nej" 304 | } 305 | } 306 | } 307 | } 308 | } 309 | } 310 | } 311 | -------------------------------------------------------------------------------- /custom_components/stromligning/binary_sensor.py: -------------------------------------------------------------------------------- 1 | """Support for Stromligning binary_sensors.""" 2 | 3 | from __future__ import annotations 4 | 5 | import logging 6 | from datetime import timedelta 7 | 8 | from homeassistant.components import binary_sensor 9 | from homeassistant.components.binary_sensor import BinarySensorEntity 10 | from homeassistant.config_entries import ConfigEntry 11 | from homeassistant.const import CONF_NAME 12 | from homeassistant.core import HomeAssistant 13 | from homeassistant.helpers.dispatcher import async_dispatcher_connect 14 | from homeassistant.util import dt as dt_utils 15 | from homeassistant.util import slugify as util_slugify 16 | from pystromligning.exceptions import InvalidAPIResponse, TooManyRequests 17 | 18 | from .api import StromligningAPI 19 | from .base import StromligningBinarySensorEntityDescription, get_next_midnight 20 | from .const import ATTR_FORECAST_DATA, ATTR_PRICES, DOMAIN, UPDATE_SIGNAL 21 | 22 | LOGGER = logging.getLogger(__name__) 23 | 24 | BINARY_SENSORS = [ 25 | StromligningBinarySensorEntityDescription( 26 | key="tomorrow_available_vat", 27 | entity_category=None, 28 | device_class=None, 29 | icon="mdi:calendar-end", 30 | value_fn=lambda stromligning: stromligning.tomorrow_available, 31 | entity_registry_enabled_default=True, 32 | translation_key="tomorrow_available_vat", 33 | ), 34 | StromligningBinarySensorEntityDescription( 35 | key="tomorrow_available_ex_vat", 36 | entity_category=None, 37 | device_class=None, 38 | icon="mdi:calendar-end", 39 | value_fn=lambda stromligning: stromligning.tomorrow_available, 40 | entity_registry_enabled_default=False, 41 | translation_key="tomorrow_available_ex_vat", 42 | ), 43 | StromligningBinarySensorEntityDescription( 44 | key="tomorrow_spotprice_vat", 45 | entity_category=None, 46 | device_class=None, 47 | icon="mdi:transmission-tower-import", 48 | value_fn=lambda stromligning: stromligning.tomorrow_available, 49 | entity_registry_enabled_default=True, 50 | translation_key="tomorrow_spotprice_vat", 51 | ), 52 | StromligningBinarySensorEntityDescription( 53 | key="tomorrow_spotprice_ex_vat", 54 | entity_category=None, 55 | device_class=None, 56 | icon="mdi:transmission-tower-import", 57 | value_fn=lambda stromligning: stromligning.tomorrow_available, 58 | entity_registry_enabled_default=False, 59 | translation_key="tomorrow_spotprice_ex_vat", 60 | ), 61 | ] 62 | 63 | 64 | async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): 65 | """Setup binary_sensors.""" 66 | binary_sensors = [] 67 | 68 | for binary_sensor in BINARY_SENSORS: 69 | entity = StromligningBinarySensor(binary_sensor, hass, entry) 70 | LOGGER.debug( 71 | "Added binary_sensor with entity_id '%s'", 72 | entity.entity_id, 73 | ) 74 | binary_sensors.append(entity) 75 | 76 | async_add_devices(binary_sensors) 77 | 78 | 79 | class StromligningBinarySensor(BinarySensorEntity): 80 | """Representation of a Stromligning Binary_Sensor.""" 81 | 82 | _unrecorded_attributes = frozenset({ATTR_PRICES}) 83 | 84 | _attr_has_entity_name = True 85 | _attr_available = True 86 | 87 | def __init__( 88 | self, 89 | description: StromligningBinarySensorEntityDescription, 90 | hass: HomeAssistant, 91 | entry: ConfigEntry, 92 | ) -> None: 93 | """Initialize a Stromligning Binary_Sensor.""" 94 | super().__init__() 95 | 96 | self.entity_description: StromligningBinarySensorEntityDescription = description 97 | self._config = entry 98 | self._hass = hass 99 | self.api: StromligningAPI = hass.data[DOMAIN][entry.entry_id] 100 | 101 | self._attr_unique_id = util_slugify( 102 | f"{self.entity_description.key}_{self._config.entry_id}" 103 | ) 104 | self._attr_should_poll = True 105 | 106 | self._attr_device_info = { 107 | "identifiers": {(DOMAIN, self._config.entry_id)}, 108 | "name": self._config.data.get(CONF_NAME), 109 | "manufacturer": "Strømligning", 110 | } 111 | 112 | async_dispatcher_connect( 113 | self._hass, 114 | util_slugify(UPDATE_SIGNAL), 115 | self.handle_update, 116 | ) 117 | 118 | self.entity_id = binary_sensor.ENTITY_ID_FORMAT.format( 119 | util_slugify( 120 | f"{self._config.data.get(CONF_NAME)}_{self.entity_description.key}" 121 | ) 122 | ) 123 | 124 | async def handle_attributes(self) -> None: 125 | """Handle attributes.""" 126 | if self.entity_description.key == "tomorrow_available_vat": 127 | self._attr_extra_state_attributes = {} 128 | self._attr_extra_state_attributes.update( 129 | { 130 | "available_at": self.api.get_next_update().strftime("%H:%M:%S"), 131 | ATTR_FORECAST_DATA: self.api.forecast_data, 132 | } 133 | ) 134 | price_set: list = [] 135 | pset = {} 136 | for price in self.api.prices_tomorrow: 137 | if "start" in pset: 138 | pset.update({"end": price["date"]}) 139 | price_set.append(pset) 140 | pset = {} 141 | 142 | pset.update( 143 | { 144 | "price": price["price"]["total"], 145 | "start": price["date"], 146 | } 147 | ) 148 | pset.update({"end": get_next_midnight()}) 149 | price_set.append(pset) 150 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 151 | 152 | elif self.entity_description.key == "tomorrow_available_ex_vat": 153 | self._attr_extra_state_attributes = {} 154 | self._attr_extra_state_attributes.update( 155 | { 156 | "available_at": self.api.get_next_update().strftime("%H:%M:%S"), 157 | ATTR_FORECAST_DATA: self.api.forecast_data, 158 | } 159 | ) 160 | price_set: list = [] 161 | pset = {} 162 | for price in self.api.prices_tomorrow: 163 | if "start" in pset: 164 | pset.update({"end": price["date"]}) 165 | price_set.append(pset) 166 | pset = {} 167 | 168 | pset.update( 169 | { 170 | "price": price["price"]["value"], 171 | "start": price["date"], 172 | } 173 | ) 174 | pset.update({"end": get_next_midnight()}) 175 | price_set.append(pset) 176 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 177 | 178 | elif self.entity_description.key == "tomorrow_spotprice_vat": 179 | self._attr_extra_state_attributes = {} 180 | self._attr_extra_state_attributes.update( 181 | { 182 | "available_at": self.api.get_next_update().strftime("%H:%M:%S"), 183 | ATTR_FORECAST_DATA: self.api.forecast_data, 184 | } 185 | ) 186 | price_set: list = [] 187 | pset = {} 188 | for price in self.api.prices_tomorrow: 189 | if "start" in pset: 190 | pset.update({"end": price["date"]}) 191 | price_set.append(pset) 192 | pset = {} 193 | 194 | pset.update( 195 | { 196 | "price": price["details"]["electricity"]["total"], 197 | "start": price["date"], 198 | } 199 | ) 200 | pset.update({"end": get_next_midnight()}) 201 | price_set.append(pset) 202 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 203 | 204 | elif self.entity_description.key == "tomorrow_spotprice_ex_vat": 205 | self._attr_extra_state_attributes = {} 206 | self._attr_extra_state_attributes.update( 207 | { 208 | "available_at": self.api.get_next_update().strftime("%H:%M:%S"), 209 | ATTR_FORECAST_DATA: self.api.forecast_data, 210 | } 211 | ) 212 | price_set: list = [] 213 | pset = {} 214 | for price in self.api.prices_tomorrow: 215 | if "start" in pset: 216 | pset.update({"end": price["date"]}) 217 | price_set.append(pset) 218 | pset = {} 219 | 220 | pset.update( 221 | { 222 | "price": price["details"]["electricity"]["value"], 223 | "start": price["date"], 224 | } 225 | ) 226 | pset.update({"end": get_next_midnight()}) 227 | price_set.append(pset) 228 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 229 | 230 | elif self.entity_description.key == "tomorrow_spotprice_vat": 231 | self._attr_extra_state_attributes = {} 232 | self._attr_extra_state_attributes.update( 233 | { 234 | "available_at": self.api.get_next_update().strftime("%H:%M:%S"), 235 | ATTR_FORECAST_DATA: self.api.forecast_data, 236 | } 237 | ) 238 | price_set: list = [] 239 | pset = {} 240 | for price in self.api.prices_tomorrow: 241 | if "start" in pset: 242 | pset.update({"end": price["date"]}) 243 | price_set.append(pset) 244 | pset = {} 245 | 246 | pset.update( 247 | { 248 | "price": price["details"]["electricity"]["total"], 249 | "start": price["date"], 250 | } 251 | ) 252 | pset.update({"end": get_next_midnight()}) 253 | price_set.append(pset) 254 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 255 | 256 | elif self.entity_description.key == "tomorrow_spotprice_ex_vat": 257 | self._attr_extra_state_attributes = {} 258 | self._attr_extra_state_attributes.update( 259 | { 260 | "available_at": self.api.get_next_update().strftime("%H:%M:%S"), 261 | ATTR_FORECAST_DATA: self.api.forecast_data, 262 | } 263 | ) 264 | price_set: list = [] 265 | pset = {} 266 | for price in self.api.prices_tomorrow: 267 | if "start" in pset: 268 | pset.update({"end": price["date"]}) 269 | price_set.append(pset) 270 | pset = {} 271 | 272 | pset.update( 273 | { 274 | "price": price["details"]["electricity"]["value"], 275 | "start": price["date"], 276 | } 277 | ) 278 | pset.update({"end": get_next_midnight()}) 279 | price_set.append(pset) 280 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 281 | 282 | async def handle_update(self) -> None: 283 | """Handle data update.""" 284 | try: 285 | self._attr_is_on = self.entity_description.value_fn( 286 | self._hass.data[DOMAIN][self._config.entry_id] 287 | ) # type: ignore 288 | LOGGER.debug( 289 | "Setting value for '%s' to: %s", 290 | self.entity_id, 291 | self._attr_is_on, 292 | ) 293 | await self.handle_attributes() 294 | self._attr_available = True 295 | except TooManyRequests: 296 | if self._attr_available: 297 | LOGGER.warning( 298 | "You made too many requests to the API and have been banned for 15 minutes." 299 | ) 300 | self._attr_available = False 301 | except InvalidAPIResponse: 302 | if self._attr_available: 303 | LOGGER.error("The Stromligning API made an invalid response.") 304 | self._attr_available = False 305 | 306 | async def async_added_to_hass(self): 307 | await self.handle_update() 308 | return await super().async_added_to_hass() 309 | -------------------------------------------------------------------------------- /custom_components/stromligning/api.py: -------------------------------------------------------------------------------- 1 | """API connector for Stromligning.""" 2 | 3 | import logging 4 | from datetime import datetime, timedelta 5 | 6 | from homeassistant.config_entries import ConfigEntry 7 | from homeassistant.core import HomeAssistant 8 | from homeassistant.helpers.dispatcher import async_dispatcher_send 9 | from homeassistant.util import dt as dt_utils 10 | from homeassistant.util import slugify as util_slugify 11 | from pystromligning import Stromligning 12 | from pystromligning.exceptions import TooManyRequests 13 | 14 | from .const import CONF_AGGREGATION, CONF_COMPANY, CONF_FORECASTS, UPDATE_SIGNAL_NEXT 15 | 16 | RETRY_MINUTES = 5 17 | MAX_RETRY_MINUTES = 60 18 | 19 | LOGGER = logging.getLogger(__name__) 20 | 21 | 22 | class StromligningAPI: 23 | """An object to store Stromligning API date.""" 24 | 25 | def __init__( 26 | self, hass: HomeAssistant, entry: ConfigEntry, rand_min: int, rand_sec: int 27 | ) -> None: 28 | """Initialize the Stromligning connector object.""" 29 | self.next_update = f"13:{rand_min}:{rand_sec}" 30 | 31 | self._entry = entry 32 | 33 | self.hass = hass 34 | 35 | self._data = Stromligning(False) 36 | 37 | self.prices_today: list = [] 38 | self.prices_tomorrow: list = [] 39 | 40 | self.tomorrow_available: bool = False 41 | 42 | self.listeners = [] 43 | 44 | self.last_update: datetime | None = None 45 | 46 | async def set_location(self) -> None: 47 | """Set the location.""" 48 | LOGGER.debug( 49 | "Setting location to %s, %s", 50 | self.hass.config.latitude, 51 | self.hass.config.longitude, 52 | ) 53 | await self.hass.async_add_executor_job( 54 | self._data.set_location, 55 | self.hass.config.latitude, 56 | self.hass.config.longitude, 57 | ) 58 | 59 | LOGGER.debug( 60 | "Setting company to %s", 61 | self._entry.options.get(CONF_COMPANY), 62 | ) 63 | self._data.set_company(str(self._entry.options.get(CONF_COMPANY))) 64 | 65 | LOGGER.debug( 66 | "Setting aggregation to %s", 67 | self._entry.options.get(CONF_AGGREGATION, "1h"), 68 | ) 69 | self._data.set_aggregation(self._entry.options.get(CONF_AGGREGATION, "1h")) 70 | 71 | LOGGER.debug( 72 | "Setting forecast to %s", 73 | self._entry.options.get(CONF_FORECASTS, False), 74 | ) 75 | self._data.set_forecast(self._entry.options.get(CONF_FORECASTS, False)) 76 | 77 | async def update_prices(self) -> None: 78 | """Update the price object.""" 79 | today_midnight_utc = ( 80 | dt_utils.as_utc( 81 | dt_utils.now().replace(hour=0, minute=0, second=0, microsecond=0) 82 | ) 83 | .isoformat() 84 | .replace("+00:00", ".000Z") 85 | ) 86 | try: 87 | await self.hass.async_add_executor_job( 88 | self._data.update, today_midnight_utc 89 | ) 90 | self.last_update = dt_utils.now() 91 | except TooManyRequests: 92 | LOGGER.info( 93 | "You made too many requests to the API within a 15 minutes window - try again later" 94 | ) 95 | 96 | async def prepare_data(self) -> None: 97 | """Prepare the data for use in Home Assistant.""" 98 | LOGGER.debug("Preparing data") 99 | 100 | today_midnight_utc = dt_utils.as_utc( 101 | dt_utils.now().replace(hour=0, minute=0, second=0, microsecond=0) 102 | ) 103 | tomorrow_midnight_utc = dt_utils.as_utc( 104 | (dt_utils.now() + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0) 105 | ) 106 | day3_midnight_utc = dt_utils.as_utc( 107 | (dt_utils.now() + timedelta(days=2)).replace(hour=0, minute=0, second=0, microsecond=0) 108 | ) 109 | 110 | self.prices_today = [] 111 | self.prices_tomorrow = [] 112 | self.prices_forecasts = [] 113 | 114 | self.forecast_data: bool = False 115 | 116 | for price in self._data.prices: 117 | # Convert the price date to datetime first 118 | price_dt = datetime.fromisoformat(price["date"]) 119 | 120 | if today_midnight_utc <= price_dt < tomorrow_midnight_utc: 121 | price["date"] = dt_utils.as_local(price_dt) 122 | self.prices_today.append(price) 123 | elif tomorrow_midnight_utc <= price_dt < day3_midnight_utc: 124 | price["date"] = dt_utils.as_local(price_dt) 125 | self.prices_tomorrow.append(price) 126 | if price.get("forecast", False): 127 | self.forecast_data = True 128 | else: 129 | price["date"] = dt_utils.as_local(price_dt) 130 | self.prices_forecasts.append(price) 131 | 132 | LOGGER.debug("Found %s entries for tomorrow", len(self.prices_tomorrow)) 133 | if len(self.prices_tomorrow) >= 23 and not self.forecast_data: 134 | LOGGER.debug("Prices for tomorrow are valid") 135 | self.tomorrow_available = True 136 | else: 137 | LOGGER.debug("Prices for tomorrow are NOT valid") 138 | if not self.forecast_data: 139 | LOGGER.debug("Clearing prices for tomorrow") 140 | self.prices_tomorrow = [] 141 | self.tomorrow_available = False 142 | async_dispatcher_send(self.hass, util_slugify(UPDATE_SIGNAL_NEXT)) 143 | 144 | def get_current(self, vat: bool = True) -> str | None: 145 | """Get the current price""" 146 | for price in self.prices_today: 147 | if not price["date"].hour == dt_utils.now().hour: 148 | continue 149 | 150 | if ( 151 | price["date"].hour == dt_utils.now().hour 152 | and len(self.prices_today) == 24 153 | ) or ( 154 | price["date"].minute <= dt_utils.now().minute 155 | and ( 156 | (price["date"] + timedelta(minutes=15)).minute 157 | > dt_utils.now().minute 158 | or (price["date"] + timedelta(minutes=15)).minute == 0 159 | ) 160 | ): 161 | LOGGER.debug( 162 | "Returning '%s' as current price", 163 | (price["price"]["total"] if vat else price["price"]["value"]), 164 | ) 165 | return price["price"]["total"] if vat else price["price"]["value"] 166 | 167 | def get_forecasts(self, vat: bool = True) -> datetime | None: 168 | """Get forecasts""" 169 | 170 | return self.last_update 171 | 172 | def get_spot(self, vat: bool = True, tomorrow: bool = False) -> str | None: 173 | """Get spotprice""" 174 | for price in self.prices_today if not tomorrow else self.prices_tomorrow: 175 | if not price["date"].hour == dt_utils.now().hour: 176 | continue 177 | 178 | if ( 179 | price["date"].hour == dt_utils.now().hour 180 | and len(self.prices_today if not tomorrow else self.prices_tomorrow) 181 | == 24 182 | ) or ( 183 | price["date"].minute <= dt_utils.now().minute 184 | and ( 185 | (price["date"] + timedelta(minutes=15)).minute 186 | > dt_utils.now().minute 187 | or (price["date"] + timedelta(minutes=15)).minute == 0 188 | ) 189 | ): 190 | 191 | LOGGER.debug( 192 | "Returning '%s' as current spotprice", 193 | ( 194 | price["details"]["electricity"]["total"] 195 | if vat 196 | else price["details"]["electricity"]["value"] 197 | ), 198 | ) 199 | return ( 200 | price["details"]["electricity"]["total"] 201 | if vat 202 | else price["details"]["electricity"]["value"] 203 | ) 204 | 205 | def get_electricitytax(self, vat: bool = True) -> str | None: 206 | """Get electricity tax""" 207 | for price in self.prices_today: 208 | if not price["date"].hour == dt_utils.now().hour: 209 | continue 210 | 211 | if ( 212 | price["date"].hour == dt_utils.now().hour 213 | and len(self.prices_today) == 24 214 | ) or ( 215 | price["date"].minute <= dt_utils.now().minute 216 | and ( 217 | (price["date"] + timedelta(minutes=15)).minute 218 | > dt_utils.now().minute 219 | or (price["date"] + timedelta(minutes=15)).minute == 0 220 | ) 221 | ): 222 | 223 | LOGGER.debug( 224 | "Returning '%s' as current electricity tax", 225 | ( 226 | price["details"]["electricityTax"]["total"] 227 | if vat 228 | else price["details"]["electricityTax"]["value"] 229 | ), 230 | ) 231 | return ( 232 | price["details"]["electricityTax"]["total"] 233 | if vat 234 | else price["details"]["electricityTax"]["value"] 235 | ) 236 | 237 | def mean(self, data: list, vat: bool = True) -> float | None: 238 | """Calculate mean value of list.""" 239 | val = 0 240 | num = 0 241 | 242 | for i in data: 243 | val += i["price"]["total"] if vat else i["price"]["value"] 244 | num += 1 245 | 246 | return val / num if num > 0 else None 247 | 248 | def get_specific_today( 249 | self, 250 | option_type: str, 251 | full_day: bool = False, 252 | date: bool = False, 253 | vat: bool = True, 254 | ) -> str | float | datetime | None: 255 | """Get today specific price and time.""" 256 | res = {} 257 | 258 | try: 259 | if not full_day: 260 | dataset: list = [] 261 | for price in self.prices_today: 262 | if price["date"] >= dt_utils.now(): 263 | dataset.append(price) 264 | else: 265 | dataset = self.prices_today 266 | 267 | if option_type.lower() == "min": 268 | res = min(dataset, key=lambda k: k["price"]["value"]) 269 | elif option_type.lower() == "max": 270 | res = max(dataset, key=lambda k: k["price"]["value"]) 271 | elif option_type.lower() == "mean": 272 | return self.mean(dataset, vat) 273 | 274 | ret = { 275 | "date": res["date"].strftime("%H:%M:%S"), 276 | "price": (res["price"]["total"] if vat else res["price"]["value"]), 277 | } 278 | 279 | return ret["date"] if date else ret["price"] 280 | except ValueError: 281 | return None 282 | 283 | def get_specific_tomorrow( 284 | self, option_type: str, date: bool = False, vat: bool = True 285 | ) -> str | float | datetime | None: 286 | """Get tomorrow specific price and time.""" 287 | try: 288 | if not self.tomorrow_available: 289 | return None 290 | 291 | dataset = self.prices_tomorrow 292 | res = {} 293 | 294 | if option_type.lower() == "min": 295 | res = min(dataset, key=lambda k: k["price"]["value"]) 296 | elif option_type.lower() == "max": 297 | res = max(dataset, key=lambda k: k["price"]["value"]) 298 | elif option_type.lower() == "mean": 299 | return self.mean(dataset, vat) 300 | 301 | ret = { 302 | "date": res["date"].strftime("%H:%M:%S"), 303 | "price": (res["price"]["total"] if vat else res["price"]["value"]), 304 | } 305 | 306 | return ret["date"] if date else ret["price"] 307 | except ValueError: 308 | return None 309 | 310 | def get_next_update(self) -> datetime: 311 | """Get next API update timestamp.""" 312 | n_update = self.next_update.split(":") 313 | 314 | data_refresh = dt_utils.now().replace( 315 | hour=int(n_update[0]), 316 | minute=int(n_update[1]), 317 | second=int(n_update[2]), 318 | microsecond=0, 319 | ) 320 | 321 | if dt_utils.now() > data_refresh and self.tomorrow_available is False: 322 | data_refresh = data_refresh.replace( 323 | hour=dt_utils.now().hour + 1, minute=0, second=2 324 | ) 325 | elif dt_utils.now().hour > 13: 326 | data_refresh = data_refresh + timedelta(days=1) 327 | 328 | return data_refresh 329 | 330 | def get_net_owner(self) -> str: 331 | """Get net operator.""" 332 | return self._data.supplier["companyName"] 333 | 334 | def get_power_provider(self) -> str: 335 | """Get power provider.""" 336 | return self._data.company["name"] 337 | 338 | def get_surcharge(self, vat: bool = True) -> float | None: 339 | """Get surcharge from API.""" 340 | for price in self.prices_today: 341 | if not price["date"].hour == dt_utils.now().hour: 342 | continue 343 | 344 | if ( 345 | price["date"].hour == dt_utils.now().hour 346 | and len(self.prices_today) == 24 347 | ) or ( 348 | price["date"].minute <= dt_utils.now().minute 349 | and ( 350 | (price["date"] + timedelta(minutes=15)).minute 351 | > dt_utils.now().minute 352 | or (price["date"] + timedelta(minutes=15)).minute == 0 353 | ) 354 | ): 355 | LOGGER.debug( 356 | "Returning '%s' as current surcharge", 357 | ( 358 | price["details"]["surcharge"]["total"] 359 | if vat 360 | else price["details"]["surcharge"]["value"] 361 | ), 362 | ) 363 | return ( 364 | price["details"]["surcharge"]["total"] 365 | if vat 366 | else price["details"]["surcharge"]["value"] 367 | ) 368 | 369 | def get_transmission_tariff(self, tariff: str, vat: bool = True) -> float | None: 370 | """Get transmission tariff from API.""" 371 | for price in self.prices_today: 372 | if not price["date"].hour == dt_utils.now().hour: 373 | continue 374 | 375 | if ( 376 | price["date"].hour == dt_utils.now().hour 377 | and len(self.prices_today) == 24 378 | ) or ( 379 | price["date"].minute <= dt_utils.now().minute 380 | and ( 381 | (price["date"] + timedelta(minutes=15)).minute 382 | > dt_utils.now().minute 383 | or (price["date"] + timedelta(minutes=15)).minute == 0 384 | ) 385 | ): 386 | LOGGER.debug( 387 | "Returning '%s' as current %s tariff", 388 | ( 389 | price["details"]["transmission"][tariff]["total"] 390 | if vat 391 | else price["details"]["transmission"][tariff]["value"] 392 | ), 393 | tariff, 394 | ) 395 | return ( 396 | price["details"]["transmission"][tariff]["total"] 397 | if vat 398 | else price["details"]["transmission"][tariff]["value"] 399 | ) 400 | 401 | def get_distribution(self, vat: bool = True) -> float | None: 402 | """Get distribution from API.""" 403 | for price in self.prices_today: 404 | if not price["date"].hour == dt_utils.now().hour: 405 | continue 406 | 407 | if ( 408 | price["date"].hour == dt_utils.now().hour 409 | and len(self.prices_today) == 24 410 | ) or ( 411 | price["date"].minute <= dt_utils.now().minute 412 | and ( 413 | (price["date"] + timedelta(minutes=15)).minute 414 | > dt_utils.now().minute 415 | or (price["date"] + timedelta(minutes=15)).minute == 0 416 | ) 417 | ): 418 | LOGGER.debug( 419 | "Returning '%s' as current distribution value", 420 | ( 421 | price["details"]["distribution"]["total"] 422 | if vat 423 | else price["details"]["distribution"]["value"] 424 | ), 425 | ) 426 | return ( 427 | price["details"]["distribution"]["total"] 428 | if vat 429 | else price["details"]["distribution"]["value"] 430 | ) 431 | -------------------------------------------------------------------------------- /custom_components/stromligning/sensor.py: -------------------------------------------------------------------------------- 1 | """Support for Stromligning sensors.""" 2 | 3 | from __future__ import annotations 4 | 5 | import logging 6 | from datetime import timedelta 7 | 8 | import homeassistant.helpers.config_validation as cv 9 | from homeassistant.components import sensor 10 | from homeassistant.components.sensor import ( 11 | SensorDeviceClass, 12 | SensorEntity, 13 | SensorStateClass, 14 | ) 15 | from homeassistant.config_entries import ConfigEntry 16 | from homeassistant.const import CONF_NAME, EntityCategory 17 | from homeassistant.core import HomeAssistant 18 | from homeassistant.helpers.dispatcher import async_dispatcher_connect 19 | from homeassistant.util import dt as dt_utils 20 | from homeassistant.util import slugify as util_slugify 21 | from pystromligning.exceptions import InvalidAPIResponse, TooManyRequests 22 | 23 | from .api import StromligningAPI 24 | from .base import StromligningSensorEntityDescription, get_next_midnight 25 | from .const import ATTR_PRICES, CONF_FORECASTS, DOMAIN, UPDATE_SIGNAL_NEXT 26 | 27 | LOGGER = logging.getLogger(__name__) 28 | 29 | SENSORS = [ 30 | StromligningSensorEntityDescription( 31 | key="current_price_vat", 32 | entity_category=None, 33 | state_class=SensorStateClass.TOTAL, 34 | device_class=SensorDeviceClass.MONETARY, 35 | icon="mdi:flash", 36 | value_fn=lambda stromligning: stromligning.get_current(True), 37 | suggested_display_precision=2, 38 | entity_registry_enabled_default=True, 39 | translation_key="current_price_vat", 40 | unit_of_measurement="kr/kWh", # type: ignore 41 | ), 42 | StromligningSensorEntityDescription( 43 | key="current_price_ex_vat", 44 | entity_category=None, 45 | state_class=SensorStateClass.TOTAL, 46 | device_class=SensorDeviceClass.MONETARY, 47 | icon="mdi:flash", 48 | value_fn=lambda stromligning: stromligning.get_current(False), 49 | suggested_display_precision=2, 50 | entity_registry_enabled_default=False, 51 | translation_key="current_price_ex_vat", 52 | unit_of_measurement="kr/kWh", # type: ignore 53 | ), 54 | StromligningSensorEntityDescription( 55 | key="spotprice_vat", 56 | entity_category=None, 57 | state_class=SensorStateClass.TOTAL, 58 | device_class=SensorDeviceClass.MONETARY, 59 | icon="mdi:transmission-tower-import", 60 | value_fn=lambda stromligning: stromligning.get_spot(True), 61 | suggested_display_precision=2, 62 | entity_registry_enabled_default=True, 63 | translation_key="spotprice_vat", 64 | unit_of_measurement="kr/kWh", # type: ignore 65 | ), 66 | StromligningSensorEntityDescription( 67 | key="spotprice_ex_vat", 68 | entity_category=None, 69 | state_class=SensorStateClass.TOTAL, 70 | device_class=SensorDeviceClass.MONETARY, 71 | icon="mdi:transmission-tower-import", 72 | value_fn=lambda stromligning: stromligning.get_spot(False), 73 | suggested_display_precision=2, 74 | entity_registry_enabled_default=False, 75 | translation_key="spotprice_ex_vat", 76 | unit_of_measurement="kr/kWh", # type: ignore 77 | ), 78 | StromligningSensorEntityDescription( 79 | key="electricity_tax_vat", 80 | entity_category=None, 81 | state_class=SensorStateClass.TOTAL, 82 | device_class=SensorDeviceClass.MONETARY, 83 | icon="mdi:currency-eur", 84 | value_fn=lambda stromligning: stromligning.get_electricitytax(True), 85 | suggested_display_precision=2, 86 | entity_registry_enabled_default=True, 87 | translation_key="electricity_tax_vat", 88 | unit_of_measurement="kr/kWh", # type: ignore 89 | ), 90 | StromligningSensorEntityDescription( 91 | key="electricity_tax_ex_vat", 92 | entity_category=None, 93 | state_class=SensorStateClass.TOTAL, 94 | device_class=SensorDeviceClass.MONETARY, 95 | icon="mdi:currency-eur", 96 | value_fn=lambda stromligning: stromligning.get_electricitytax(False), 97 | suggested_display_precision=2, 98 | entity_registry_enabled_default=False, 99 | translation_key="electricity_tax_ex_vat", 100 | unit_of_measurement="kr/kWh", # type: ignore 101 | ), 102 | StromligningSensorEntityDescription( 103 | key="today_min_vat", 104 | entity_category=None, 105 | state_class=SensorStateClass.TOTAL, 106 | device_class=SensorDeviceClass.MONETARY, 107 | icon="mdi:flash", 108 | value_fn=lambda stromligning: stromligning.get_specific_today("min", vat=True), 109 | suggested_display_precision=2, 110 | entity_registry_enabled_default=True, 111 | translation_key="today_min_vat", 112 | unit_of_measurement="kr/kWh", # type: ignore 113 | ), 114 | StromligningSensorEntityDescription( 115 | key="today_min_ex_vat", 116 | entity_category=None, 117 | state_class=SensorStateClass.TOTAL, 118 | device_class=SensorDeviceClass.MONETARY, 119 | icon="mdi:flash", 120 | value_fn=lambda stromligning: stromligning.get_specific_today("min", vat=False), 121 | suggested_display_precision=2, 122 | entity_registry_enabled_default=False, 123 | translation_key="today_min_ex_vat", 124 | unit_of_measurement="kr/kWh", # type: ignore 125 | ), 126 | StromligningSensorEntityDescription( 127 | key="today_max_vat", 128 | entity_category=None, 129 | state_class=SensorStateClass.TOTAL, 130 | device_class=SensorDeviceClass.MONETARY, 131 | icon="mdi:flash", 132 | value_fn=lambda stromligning: stromligning.get_specific_today("max", vat=True), 133 | suggested_display_precision=2, 134 | entity_registry_enabled_default=True, 135 | translation_key="today_max_vat", 136 | unit_of_measurement="kr/kWh", # type: ignore 137 | ), 138 | StromligningSensorEntityDescription( 139 | key="today_max_ex_vat", 140 | entity_category=None, 141 | state_class=SensorStateClass.TOTAL, 142 | device_class=SensorDeviceClass.MONETARY, 143 | icon="mdi:flash", 144 | value_fn=lambda stromligning: stromligning.get_specific_today("max", vat=False), 145 | suggested_display_precision=2, 146 | entity_registry_enabled_default=False, 147 | translation_key="today_max_ex_vat", 148 | unit_of_measurement="kr/kWh", # type: ignore 149 | ), 150 | StromligningSensorEntityDescription( 151 | key="today_mean_vat", 152 | entity_category=None, 153 | state_class=SensorStateClass.TOTAL, 154 | device_class=SensorDeviceClass.MONETARY, 155 | icon="mdi:flash", 156 | value_fn=lambda stromligning: stromligning.get_specific_today("mean", vat=True), 157 | suggested_display_precision=2, 158 | entity_registry_enabled_default=True, 159 | translation_key="today_mean_vat", 160 | unit_of_measurement="kr/kWh", # type: ignore 161 | ), 162 | StromligningSensorEntityDescription( 163 | key="today_mean_ex_vat", 164 | entity_category=None, 165 | state_class=SensorStateClass.TOTAL, 166 | device_class=SensorDeviceClass.MONETARY, 167 | icon="mdi:flash", 168 | value_fn=lambda stromligning: stromligning.get_specific_today( 169 | "mean", vat=False 170 | ), 171 | suggested_display_precision=2, 172 | entity_registry_enabled_default=False, 173 | translation_key="today_mean_ex_vat", 174 | unit_of_measurement="kr/kWh", # type: ignore 175 | ), 176 | StromligningSensorEntityDescription( 177 | key="tomorrow_min_vat", 178 | entity_category=None, 179 | state_class=SensorStateClass.TOTAL, 180 | device_class=SensorDeviceClass.MONETARY, 181 | icon="mdi:flash", 182 | value_fn=lambda stromligning: stromligning.get_specific_tomorrow( 183 | "min", vat=True 184 | ), 185 | suggested_display_precision=2, 186 | entity_registry_enabled_default=True, 187 | translation_key="tomorrow_min_vat", 188 | unit_of_measurement="kr/kWh", # type: ignore 189 | ), 190 | StromligningSensorEntityDescription( 191 | key="tomorrow_min_ex_vat", 192 | entity_category=None, 193 | state_class=SensorStateClass.TOTAL, 194 | device_class=SensorDeviceClass.MONETARY, 195 | icon="mdi:flash", 196 | value_fn=lambda stromligning: stromligning.get_specific_tomorrow( 197 | "min", vat=False 198 | ), 199 | suggested_display_precision=2, 200 | entity_registry_enabled_default=False, 201 | translation_key="tomorrow_min_ex_vat", 202 | unit_of_measurement="kr/kWh", # type: ignore 203 | ), 204 | StromligningSensorEntityDescription( 205 | key="tomorrow_max_vat", 206 | entity_category=None, 207 | state_class=SensorStateClass.TOTAL, 208 | device_class=SensorDeviceClass.MONETARY, 209 | icon="mdi:flash", 210 | value_fn=lambda stromligning: stromligning.get_specific_tomorrow( 211 | "max", vat=True 212 | ), 213 | suggested_display_precision=2, 214 | entity_registry_enabled_default=True, 215 | translation_key="tomorrow_max_vat", 216 | unit_of_measurement="kr/kWh", # type: ignore 217 | ), 218 | StromligningSensorEntityDescription( 219 | key="tomorrow_max_ex_vat", 220 | entity_category=None, 221 | state_class=SensorStateClass.TOTAL, 222 | device_class=SensorDeviceClass.MONETARY, 223 | icon="mdi:flash", 224 | value_fn=lambda stromligning: stromligning.get_specific_tomorrow( 225 | "max", vat=False 226 | ), 227 | suggested_display_precision=2, 228 | entity_registry_enabled_default=False, 229 | translation_key="tomorrow_max_ex_vat", 230 | unit_of_measurement="kr/kWh", # type: ignore 231 | ), 232 | StromligningSensorEntityDescription( 233 | key="tomorrow_mean_vat", 234 | entity_category=None, 235 | state_class=SensorStateClass.TOTAL, 236 | device_class=SensorDeviceClass.MONETARY, 237 | icon="mdi:flash", 238 | value_fn=lambda stromligning: stromligning.get_specific_tomorrow( 239 | "mean", vat=True 240 | ), 241 | suggested_display_precision=2, 242 | entity_registry_enabled_default=True, 243 | translation_key="tomorrow_mean_vat", 244 | unit_of_measurement="kr/kWh", # type: ignore 245 | ), 246 | StromligningSensorEntityDescription( 247 | key="tomorrow_mean_ex_vat", 248 | entity_category=None, 249 | state_class=SensorStateClass.TOTAL, 250 | device_class=SensorDeviceClass.MONETARY, 251 | icon="mdi:flash", 252 | value_fn=lambda stromligning: stromligning.get_specific_tomorrow( 253 | "mean", vat=False 254 | ), 255 | suggested_display_precision=2, 256 | entity_registry_enabled_default=False, 257 | translation_key="tomorrow_mean_ex_vat", 258 | unit_of_measurement="kr/kWh", # type: ignore 259 | ), 260 | StromligningSensorEntityDescription( 261 | key="next_data_refresh", 262 | entity_category=EntityCategory.DIAGNOSTIC, 263 | state_class=None, 264 | device_class=SensorDeviceClass.TIMESTAMP, 265 | icon="mdi:clock-fast", 266 | value_fn=lambda stromligning: stromligning.get_next_update(), 267 | entity_registry_enabled_default=True, 268 | translation_key="next_data_refresh", 269 | update_signal=UPDATE_SIGNAL_NEXT, 270 | ), 271 | StromligningSensorEntityDescription( 272 | key="net_owner", 273 | entity_category=EntityCategory.DIAGNOSTIC, 274 | state_class=None, 275 | device_class=None, 276 | icon="mdi:transmission-tower-export", 277 | value_fn=lambda stromligning: stromligning.get_net_owner(), 278 | entity_registry_enabled_default=False, 279 | translation_key="net_owner", 280 | ), 281 | StromligningSensorEntityDescription( 282 | key="provider", 283 | entity_category=EntityCategory.DIAGNOSTIC, 284 | state_class=None, 285 | device_class=None, 286 | icon="mdi:home-lightning-bolt", 287 | value_fn=lambda stromligning: stromligning.get_power_provider(), 288 | entity_registry_enabled_default=False, 289 | translation_key="provider", 290 | ), 291 | StromligningSensorEntityDescription( 292 | key="surcharge_vat", 293 | entity_category=None, 294 | state_class=SensorStateClass.TOTAL, 295 | device_class=SensorDeviceClass.MONETARY, 296 | icon="mdi:plus-circle-multiple", 297 | value_fn=lambda stromligning: stromligning.get_surcharge(vat=True), 298 | entity_registry_enabled_default=True, 299 | translation_key="surcharge_vat", 300 | unit_of_measurement="kr/kWh", # type: ignore 301 | ), 302 | StromligningSensorEntityDescription( 303 | key="surcharge_ex_vat", 304 | entity_category=None, 305 | state_class=SensorStateClass.TOTAL, 306 | device_class=SensorDeviceClass.MONETARY, 307 | icon="mdi:plus-circle-multiple", 308 | value_fn=lambda stromligning: stromligning.get_surcharge(vat=False), 309 | entity_registry_enabled_default=False, 310 | translation_key="surcharge_ex_vat", 311 | unit_of_measurement="kr/kWh", # type: ignore 312 | ), 313 | StromligningSensorEntityDescription( 314 | key="systemtariff_vat", 315 | entity_category=None, 316 | state_class=SensorStateClass.TOTAL, 317 | device_class=SensorDeviceClass.MONETARY, 318 | icon="mdi:transmission-tower-export", 319 | value_fn=lambda stromligning: stromligning.get_transmission_tariff( 320 | tariff="systemTariff", vat=True 321 | ), 322 | suggested_display_precision=2, 323 | entity_registry_enabled_default=True, 324 | translation_key="systemtariff_vat", 325 | unit_of_measurement="kr/kWh", # type: ignore 326 | ), 327 | StromligningSensorEntityDescription( 328 | key="systemtariff_ex_vat", 329 | entity_category=None, 330 | state_class=SensorStateClass.TOTAL, 331 | device_class=SensorDeviceClass.MONETARY, 332 | icon="mdi:transmission-tower-export", 333 | value_fn=lambda stromligning: stromligning.get_transmission_tariff( 334 | tariff="systemTariff", vat=False 335 | ), 336 | suggested_display_precision=2, 337 | entity_registry_enabled_default=False, 338 | translation_key="systemtariff_ex_vat", 339 | unit_of_measurement="kr/kWh", # type: ignore 340 | ), 341 | StromligningSensorEntityDescription( 342 | key="nettariff_vat", 343 | entity_category=None, 344 | state_class=SensorStateClass.TOTAL, 345 | device_class=SensorDeviceClass.MONETARY, 346 | icon="mdi:transmission-tower-export", 347 | value_fn=lambda stromligning: stromligning.get_transmission_tariff( 348 | tariff="netTariff", vat=True 349 | ), 350 | suggested_display_precision=2, 351 | entity_registry_enabled_default=True, 352 | translation_key="nettariff_vat", 353 | unit_of_measurement="kr/kWh", # type: ignore 354 | ), 355 | StromligningSensorEntityDescription( 356 | key="nettariff_ex_vat", 357 | entity_category=None, 358 | state_class=SensorStateClass.TOTAL, 359 | device_class=SensorDeviceClass.MONETARY, 360 | icon="mdi:transmission-tower-export", 361 | value_fn=lambda stromligning: stromligning.get_transmission_tariff( 362 | tariff="netTariff", vat=False 363 | ), 364 | suggested_display_precision=2, 365 | entity_registry_enabled_default=False, 366 | translation_key="nettariff_ex_vat", 367 | unit_of_measurement="kr/kWh", # type: ignore 368 | ), 369 | StromligningSensorEntityDescription( 370 | key="distribution_vat", 371 | entity_category=None, 372 | state_class=SensorStateClass.TOTAL, 373 | device_class=SensorDeviceClass.MONETARY, 374 | icon="mdi:transmission-tower-export", 375 | value_fn=lambda stromligning: stromligning.get_distribution(vat=True), 376 | suggested_display_precision=2, 377 | entity_registry_enabled_default=True, 378 | translation_key="distribution_vat", 379 | unit_of_measurement="kr/kWh", # type: ignore 380 | ), 381 | StromligningSensorEntityDescription( 382 | key="distribution_ex_vat", 383 | entity_category=None, 384 | state_class=SensorStateClass.TOTAL, 385 | device_class=SensorDeviceClass.MONETARY, 386 | icon="mdi:transmission-tower-export", 387 | value_fn=lambda stromligning: stromligning.get_distribution(vat=False), 388 | suggested_display_precision=2, 389 | entity_registry_enabled_default=False, 390 | translation_key="distribution_ex_vat", 391 | unit_of_measurement="kr/kWh", # type: ignore 392 | ), 393 | StromligningSensorEntityDescription( 394 | key="forecasts_vat", 395 | entity_category=None, 396 | state_class=None, 397 | device_class=SensorDeviceClass.TIMESTAMP, 398 | icon="mdi:electron-framework", 399 | value_fn=lambda stromligning: stromligning.get_forecasts(vat=True), 400 | entity_registry_enabled_default=True, 401 | translation_key="forecasts_vat", 402 | ), 403 | StromligningSensorEntityDescription( 404 | key="forecasts_ex_vat", 405 | entity_category=None, 406 | state_class=None, 407 | device_class=SensorDeviceClass.TIMESTAMP, 408 | icon="mdi:electron-framework", 409 | value_fn=lambda stromligning: stromligning.get_forecasts(vat=False), 410 | entity_registry_enabled_default=True, 411 | translation_key="forecasts_ex_vat", 412 | ), 413 | ] 414 | 415 | 416 | async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): 417 | """Setup sensors.""" 418 | sensors = [] 419 | 420 | forecasts = entry.options.get(CONF_FORECASTS, False) 421 | 422 | for sensor in SENSORS: 423 | if "forecast" in sensor.key and not forecasts: 424 | continue 425 | 426 | entity = StromligningSensor(sensor, hass, entry) 427 | LOGGER.debug( 428 | "Added sensor with entity_id '%s'", 429 | entity.entity_id, 430 | ) 431 | sensors.append(entity) 432 | 433 | async_add_devices(sensors) 434 | 435 | 436 | class StromligningSensor(SensorEntity): 437 | """Representation of a Stromligning Sensor.""" 438 | 439 | _unrecorded_attributes = frozenset({ATTR_PRICES}) 440 | 441 | _attr_has_entity_name = True 442 | _attr_available = True 443 | 444 | def __init__( 445 | self, 446 | description: StromligningSensorEntityDescription, 447 | hass: HomeAssistant, 448 | entry: ConfigEntry, 449 | ) -> None: 450 | """Initialize a Stromligning Sensor.""" 451 | super().__init__() 452 | 453 | self.entity_description = description 454 | self._config = entry 455 | self._hass = hass 456 | self.api: StromligningAPI = hass.data[DOMAIN][entry.entry_id] 457 | 458 | self._attr_unique_id = util_slugify( 459 | f"{self.entity_description.key}_{self._config.entry_id}" 460 | ) 461 | self._attr_should_poll = True 462 | 463 | self._attr_device_info = { 464 | "identifiers": {(DOMAIN, self._config.entry_id)}, 465 | "name": self._config.data.get(CONF_NAME), 466 | "manufacturer": "Strømligning", 467 | } 468 | 469 | self._attr_native_unit_of_measurement = ( 470 | self.entity_description.unit_of_measurement 471 | ) 472 | 473 | async_dispatcher_connect( 474 | self._hass, 475 | util_slugify(self.entity_description.update_signal), 476 | self.handle_update, 477 | ) 478 | 479 | self.entity_id = sensor.ENTITY_ID_FORMAT.format( 480 | util_slugify( 481 | f"{self._config.data.get(CONF_NAME)}_{self.entity_description.key}" 482 | ) 483 | ) 484 | 485 | async def handle_attributes(self) -> None: 486 | """Handle attributes.""" 487 | if self.entity_description.key == "current_price_vat": 488 | self._attr_extra_state_attributes = {} 489 | price_set: list = [] 490 | pset = {} 491 | for price in self.api.prices_today: 492 | if "start" in pset: 493 | pset.update({"end": price["date"]}) 494 | price_set.append(pset) 495 | pset = {} 496 | 497 | pset.update( 498 | { 499 | "price": price["price"]["total"], 500 | "start": price["date"], 501 | } 502 | ) 503 | pset.update({"end": get_next_midnight()}) 504 | price_set.append(pset) 505 | 506 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 507 | elif self.entity_description.key == "current_price_ex_vat": 508 | self._attr_extra_state_attributes = {} 509 | price_set: list = [] 510 | pset = {} 511 | for price in self.api.prices_today: 512 | if "start" in pset: 513 | pset.update({"end": price["date"]}) 514 | price_set.append(pset) 515 | pset = {} 516 | 517 | pset.update( 518 | { 519 | "price": price["price"]["value"], 520 | "start": price["date"], 521 | } 522 | ) 523 | pset.update({"end": get_next_midnight()}) 524 | price_set.append(pset) 525 | 526 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 527 | elif self.entity_description.key == "distribution_vat": 528 | self._attr_extra_state_attributes = {} 529 | price_set: list = [] 530 | pset = {} 531 | for price in self.api.prices_today: 532 | if "start" in pset: 533 | pset.update({"end": price["date"]}) 534 | price_set.append(pset) 535 | pset = {} 536 | 537 | pset.update( 538 | { 539 | "price": price["details"]["distribution"]["total"], 540 | "start": price["date"], 541 | } 542 | ) 543 | pset.update({"end": get_next_midnight()}) 544 | price_set.append(pset) 545 | 546 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 547 | elif self.entity_description.key == "distribution_ex_vat": 548 | self._attr_extra_state_attributes = {} 549 | price_set: list = [] 550 | pset = {} 551 | for price in self.api.prices_today: 552 | if "start" in pset: 553 | pset.update({"end": price["date"]}) 554 | price_set.append(pset) 555 | pset = {} 556 | 557 | pset.update( 558 | { 559 | "price": price["details"]["distribution"]["value"], 560 | "start": price["date"], 561 | } 562 | ) 563 | pset.update({"end": get_next_midnight()}) 564 | price_set.append(pset) 565 | 566 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 567 | elif self.entity_description.key == "today_min_vat": 568 | self._attr_extra_state_attributes = {} 569 | self._attr_extra_state_attributes.update( 570 | {"at": self.api.get_specific_today("min", date=True, vat=True)} 571 | ) 572 | elif self.entity_description.key == "today_min_ex_vat": 573 | self._attr_extra_state_attributes = {} 574 | self._attr_extra_state_attributes.update( 575 | {"at": self.api.get_specific_today("min", date=True, vat=False)} 576 | ) 577 | elif self.entity_description.key == "today_max_vat": 578 | self._attr_extra_state_attributes = {} 579 | self._attr_extra_state_attributes.update( 580 | {"at": self.api.get_specific_today("max", date=True, vat=True)} 581 | ) 582 | elif self.entity_description.key == "today_max_ex_vat": 583 | self._attr_extra_state_attributes = {} 584 | self._attr_extra_state_attributes.update( 585 | {"at": self.api.get_specific_today("max", date=True, vat=False)} 586 | ) 587 | elif self.entity_description.key == "tomorrow_min_vat": 588 | self._attr_extra_state_attributes = {} 589 | self._attr_extra_state_attributes.update( 590 | {"at": self.api.get_specific_tomorrow("min", date=True, vat=True)} 591 | ) 592 | elif self.entity_description.key == "tomorrow_min_ex_vat": 593 | self._attr_extra_state_attributes = {} 594 | self._attr_extra_state_attributes.update( 595 | {"at": self.api.get_specific_tomorrow("min", date=True, vat=False)} 596 | ) 597 | elif self.entity_description.key == "tomorrow_max_vat": 598 | self._attr_extra_state_attributes = {} 599 | self._attr_extra_state_attributes.update( 600 | {"at": self.api.get_specific_tomorrow("max", date=True, vat=True)} 601 | ) 602 | elif self.entity_description.key == "tomorrow_max_ex_vat": 603 | self._attr_extra_state_attributes = {} 604 | self._attr_extra_state_attributes.update( 605 | {"at": self.api.get_specific_tomorrow("max", date=True, vat=False)} 606 | ) 607 | elif ( 608 | self.entity_description.key == "forecasts_vat" 609 | or self.entity_description.key == "forecasts_ex_vat" 610 | ): 611 | self._attr_extra_state_attributes = {} 612 | price_set: list = [] 613 | pset = {} 614 | for price in self.api.prices_forecasts: 615 | if "start" in pset: 616 | pset.update({"end": price["date"]}) 617 | price_set.append(pset) 618 | pset = {} 619 | 620 | pset.update( 621 | { 622 | "price": ( 623 | price["price"]["total"] 624 | if self.entity_description.key == "forecasts_vat" 625 | else price["price"]["value"] 626 | ), 627 | "start": price["date"], 628 | } 629 | ) 630 | pset.update({"end": get_next_midnight()}) 631 | price_set.append(pset) 632 | 633 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 634 | 635 | elif self.entity_description.key == "spotprice_vat": 636 | self._attr_extra_state_attributes = {} 637 | price_set: list = [] 638 | pset = {} 639 | for price in self.api.prices_today: 640 | if "start" in pset: 641 | pset.update({"end": price["date"]}) 642 | price_set.append(pset) 643 | pset = {} 644 | 645 | pset.update( 646 | { 647 | "price": price["details"]["electricity"]["total"], 648 | "start": price["date"], 649 | } 650 | ) 651 | pset.update({"end": get_next_midnight()}) 652 | price_set.append(pset) 653 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 654 | 655 | elif self.entity_description.key == "spotprice_ex_vat": 656 | self._attr_extra_state_attributes = {} 657 | price_set: list = [] 658 | pset = {} 659 | for price in self.api.prices_today: 660 | if "start" in pset: 661 | pset.update({"end": price["date"]}) 662 | price_set.append(pset) 663 | pset = {} 664 | 665 | pset.update( 666 | { 667 | "price": price["details"]["electricity"]["value"], 668 | "start": price["date"], 669 | } 670 | ) 671 | pset.update({"end": get_next_midnight()}) 672 | price_set.append(pset) 673 | self._attr_extra_state_attributes.update({ATTR_PRICES: price_set}) 674 | 675 | async def handle_update(self) -> None: 676 | """Handle data update.""" 677 | try: 678 | self._attr_native_value = self.entity_description.value_fn( # type: ignore 679 | self._hass.data[DOMAIN][self._config.entry_id] 680 | ) 681 | 682 | LOGGER.debug( 683 | "Setting value for '%s' to: %s", 684 | self.entity_id, 685 | self._attr_native_value, 686 | ) 687 | await self.handle_attributes() 688 | self._attr_available = True 689 | except TooManyRequests: 690 | if self._attr_available: 691 | LOGGER.warning( 692 | "You made too many requests to the API and have been banned for 15 minutes." 693 | ) 694 | self._attr_available = False 695 | except InvalidAPIResponse: 696 | if self._attr_available: 697 | LOGGER.error("The Stromligning API made an invalid response.") 698 | self._attr_available = False 699 | 700 | async def async_added_to_hass(self): 701 | await self.handle_update() 702 | return await super().async_added_to_hass() 703 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------