├── config ├── custom_components └── configuration.yaml ├── assets ├── icon.png ├── logo.png ├── icon.orig.png ├── icon@2x.png ├── logo.orig.png └── logo@2x.png ├── screenshots ├── accumulated.png ├── historical.png ├── configuration-1.png └── configuration-2.png ├── hacs.json ├── .github ├── workflows │ ├── hassfest.yml │ ├── hacs.yml │ └── codeql-analysis.yml └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── pyproject.toml ├── custom_components └── ideenergy │ ├── translations │ └── en.json │ ├── manifest.json │ ├── strings.json │ ├── const.py │ ├── entity.py │ ├── config_flow.py │ ├── __init__.py │ ├── updates.py │ ├── fixes.py │ ├── datacoordinator.py │ ├── barrier.py │ └── sensor.py ├── .pre-commit-config.yaml ├── .gitignore ├── FAQ.md ├── README.es.md ├── README.md └── LICENSE /config/custom_components: -------------------------------------------------------------------------------- 1 | ../custom_components/ -------------------------------------------------------------------------------- /assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/assets/icon.png -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/assets/logo.png -------------------------------------------------------------------------------- /assets/icon.orig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/assets/icon.orig.png -------------------------------------------------------------------------------- /assets/icon@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/assets/icon@2x.png -------------------------------------------------------------------------------- /assets/logo.orig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/assets/logo.orig.png -------------------------------------------------------------------------------- /assets/logo@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/assets/logo@2x.png -------------------------------------------------------------------------------- /screenshots/accumulated.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/screenshots/accumulated.png -------------------------------------------------------------------------------- /screenshots/historical.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/screenshots/historical.png -------------------------------------------------------------------------------- /screenshots/configuration-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/screenshots/configuration-1.png -------------------------------------------------------------------------------- /screenshots/configuration-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldotlopez/ha-ideenergy/HEAD/screenshots/configuration-2.png -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "i-DE Energy Monitor", 3 | "render_readme": true, 4 | "content_in_root": false, 5 | "homeassistant": "2023.6.0" 6 | } 7 | -------------------------------------------------------------------------------- /.github/workflows/hassfest.yml: -------------------------------------------------------------------------------- 1 | name: Validate with hassfest 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: '0 0 * * *' 8 | 9 | jobs: 10 | validate: 11 | runs-on: "ubuntu-latest" 12 | steps: 13 | - uses: "actions/checkout@v2" 14 | - uses: "home-assistant/actions/hassfest@master" 15 | -------------------------------------------------------------------------------- /config/configuration.yaml: -------------------------------------------------------------------------------- 1 | default_config: 2 | 3 | logger: 4 | default: warning 5 | logs: 6 | ideenergy: warning 7 | custom_components.ideenergy.datacoordinator: debug 8 | custom_components.ideenergy.sensor: debug 9 | custom_components.ideenergy.updates: debug 10 | custom_components.ideenergy.fixes: debug 11 | homeassistant_historical_sensor: debug 12 | -------------------------------------------------------------------------------- /.github/workflows/hacs.yml: -------------------------------------------------------------------------------- 1 | name: Validate with HACS 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: "0 0 * * *" 8 | 9 | jobs: 10 | hacs: 11 | name: HACS Action 12 | runs-on: "ubuntu-latest" 13 | steps: 14 | - uses: "actions/checkout@v2" 15 | - name: HACS Action 16 | uses: "hacs/action@main" 17 | with: 18 | category: "integration" 19 | ignore: "brands" 20 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "ha-ideenergy" 3 | version = "2025.2.0" 4 | requires-python = ">=3.13" 5 | 6 | [tool.black] 7 | target-version = ['py313'] 8 | 9 | [tool.isort] 10 | profile = "black" 11 | 12 | [tool.mypy] 13 | files = ["custom_components/ideenergy"] 14 | 15 | [tool.pyupgrade] 16 | addopts = "--py313-plus" 17 | 18 | [dependency-groups] 19 | dev = [ 20 | "homeassistant>=2025.2.0", 21 | "ipdb>=0.13.13", 22 | "ipython>=8.32.0", 23 | "pre-commit>=4.1.0", 24 | "sqlalchemy>=2.0.37", 25 | ] 26 | -------------------------------------------------------------------------------- /custom_components/ideenergy/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "abort": { 4 | "already_configured": "Device is already configured" 5 | }, 6 | "error": { 7 | "cannot_connect": "Failed to connect", 8 | "invalid_auth": "Invalid authentication", 9 | "unknown": "Unexpected error" 10 | }, 11 | "step": { 12 | "user": { 13 | "data": { 14 | "name": "Name", 15 | "password": "Password", 16 | "username": "Username" 17 | } 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /custom_components/ideenergy/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "ideenergy", 3 | "name": "i-DE Energy Monitor", 4 | "codeowners": [ 5 | "@ldotlopez" 6 | ], 7 | "config_flow": true, 8 | "dependencies": [ 9 | "recorder" 10 | ], 11 | "documentation": "https://github.com/ldotlopez/ha-ideenergy", 12 | "integration_type": "device", 13 | "iot_class": "cloud_polling", 14 | "issue_tracker": "https://github.com/ldotlopez/ha-ideenergy/issues", 15 | "requirements": [ 16 | "ideenergy>=2.0.0rc1", 17 | "homeassistant-historical-sensor==2.0.0" 18 | ], 19 | "version": "2025.2.0" 20 | } 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /custom_components/ideenergy/strings.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "step": { 4 | "user": { 5 | "data": { 6 | "name": "[%key:common::config_flow::data::name%]", 7 | "username": "[%key:common::config_flow::data::username%]", 8 | "password": "[%key:common::config_flow::data::password%]" 9 | } 10 | }, 11 | "contract": { 12 | "data": { 13 | "contract": "[%key:common::config_flow::data::contract%]" 14 | } 15 | } 16 | }, 17 | "error": { 18 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", 19 | "unknown": "[%key:common::config_flow::error::unknown%]" 20 | }, 21 | "abort": { 22 | "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v2.3.0 4 | hooks: 5 | - id: end-of-file-fixer 6 | # exclude: '\.json$' 7 | - id: trailing-whitespace 8 | args: ['--markdown-linebreak-ext=md'] 9 | - id: check-json 10 | - id: pretty-format-json 11 | args: ['--autofix', '--no-sort-keys'] 12 | - id: check-toml 13 | # - id: check-yaml 14 | - id: debug-statements 15 | 16 | - repo: https://github.com/asottile/pyupgrade 17 | rev: v3.9.0 18 | hooks: 19 | - id: pyupgrade 20 | args: ['--py311-plus'] 21 | 22 | - repo: https://github.com/pycqa/isort 23 | rev: 5.12.0 24 | hooks: 25 | - id: isort 26 | args: ['--profile', 'black'] 27 | 28 | - repo: https://github.com/psf/black 29 | rev: 23.7.0 30 | hooks: 31 | - id: black 32 | -------------------------------------------------------------------------------- /custom_components/ideenergy/const.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2022 Luis López 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software 15 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 16 | # USA. 17 | 18 | 19 | from datetime import timedelta 20 | 21 | DOMAIN = "ideenergy" 22 | 23 | CONF_CONTRACT = "contract" 24 | 25 | MEASURE_MAX_AGE = 60 * 50 # Fifty minutes 26 | MAX_RETRIES = 3 27 | MIN_SCAN_INTERVAL = 60 28 | UPDATE_WINDOW_START_MINUTE = 50 29 | UPDATE_WINDOW_END_MINUTE = 59 30 | API_USER_SESSION_TIMEOUT = 60 31 | 32 | 33 | DATA_ATTR_MEASURE_ACCUMULATED = "measure_accumulated" 34 | DATA_ATTR_MEASURE_INSTANT = "measure_instant" 35 | DATA_ATTR_HISTORICAL_CONSUMPTION = "historical_consumption" 36 | DATA_ATTR_HISTORICAL_GENERATION = "historical_generation" 37 | DATA_ATTR_HISTORICAL_POWER_DEMAND = "historical_power_demand" 38 | 39 | HISTORICAL_PERIOD_LENGHT = timedelta(days=7) 40 | CONFIG_ENTRY_VERSION = 3 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | Before filling a bug please provide as much as information as possible. 11 | Not all information is required but the more the better. 12 | 13 | Stick to English if bug is about code, Spanish is OK if bug is about configuration. 14 | 15 | 16 | **Describe the bug** 17 | A clear and concise description of what the bug is. 18 | 19 | **To Reproduce** 20 | Steps to reproduce the behavior: 21 | 1. Go to '...' 22 | 2. Click on '....' 23 | 3. Scroll down to '....' 24 | 4. See error 25 | 26 | **Environment** 27 | - HomeAssistant version [e.g. 2023.2.1] 28 | - ideenergy integration version [e.g 1.0.0, main] 29 | - Instalation method [HassOS, docker, pip, pipenv] 30 | - i-de.es advanced user [yes / no] 31 | - Did I read the [FAQ](https://github.com/ldotlopez/ha-ideenergy/blob/main/FAQ.md)? (You should): no 32 | - Did I enable debug before posting any log as it's required? (see Logs section below): no 33 | 34 | _You **must** say "yes" to the FAQ and debug questions_ 35 | 36 | **Expected behavior** 37 | A clear and concise description of what you expected to happen. 38 | 39 | **Logs** 40 | - Enable debug level for `ideenergy` and `custom_components.ideenergy`. See [HomeAssistant docs](https://www.home-assistant.io/integrations/logger) 41 | - Paste or reference (via gist or pastebin) relevant info. 42 | 43 | **Screenshots** 44 | If applicable, add screenshots to help explain your problem. 45 | 46 | **Additional context** 47 | Add any other context about the problem here. 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | ### Python ### 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | cover/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | .pybuilder/ 78 | target/ 79 | 80 | 81 | ### macOS ### 82 | # General 83 | .DS_Store 84 | .AppleDouble 85 | .LSOverride 86 | 87 | # Icon must end with two \r 88 | Icon 89 | 90 | 91 | # Thumbnails 92 | ._* 93 | 94 | # Files that might appear in the root of a volume 95 | .DocumentRevisions-V100 96 | .fseventsd 97 | .Spotlight-V100 98 | .TemporaryItems 99 | .Trashes 100 | .VolumeIcon.icns 101 | .com.apple.timemachine.donotpresent 102 | 103 | # Directories potentially created on remote AFP share 104 | .AppleDB 105 | .AppleDesktop 106 | Network Trash Folder 107 | Temporary Items 108 | .apdisk 109 | 110 | ### homeassistant integration ### 111 | config/ 112 | !config/configuration.yaml 113 | !config/custom_components 114 | Pipfile.lock 115 | *.swp 116 | *.sublime-* 117 | *.env 118 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ main ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ main ] 20 | schedule: 21 | - cron: '33 0 * * 0' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'python' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://git.io/codeql-language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v2 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v2 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 52 | 53 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 54 | # If this step fails, then you should remove it and run the build manually (see below) 55 | - name: Autobuild 56 | uses: github/codeql-action/autobuild@v1 57 | 58 | # ℹ️ Command-line programs to run using the OS shell. 59 | # 📚 https://git.io/JvXDl 60 | 61 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 62 | # and modify them (or add more) to build your code if your project 63 | # uses a compiled language 64 | 65 | #- run: | 66 | # make bootstrap 67 | # make release 68 | 69 | - name: Perform CodeQL Analysis 70 | uses: github/codeql-action/analyze@v2 71 | -------------------------------------------------------------------------------- /FAQ.md: -------------------------------------------------------------------------------- 1 | # FAQ 2 | 3 | ## Q. Why "X" doesn't work 4 | 5 | A. Most features in this integration are experimental. If it's not listed as supported it's **not** supported. Double-check this. 6 | 7 | 8 | ## Q. Accumulated (or instant) consumption sensor is in an unknown state or doesn't show any data. 9 | 10 | 11 | A. Due to connectivity issues or i-DE server issues, you may not always obtain readings as expected. Keep in mind that sometimes a delay on the reading may occurr. 12 | 13 | Those two sensors read data directly from your service point. The i-de API for this data is **very** unreliable, > 50% of the calls fail. We try out best to circumvent this situation but we can't do magic. 14 | 15 | Also, due to connectivity issues or i-DE server issues, you may not always obtain readings as expected. 16 | 17 | Give it some time, two or three days, before filing a bug. 18 | 19 | 20 | ## Q. Why accumulated (or instant) consumption sensors are only updated once at hour? Can be this interval shorter? 21 | 22 | These sensors need to read the service point directly. 23 | 24 | The i-de.es service point API is not very reliable, we try up to three calls before giving up in each update window (interval 50-59 of each hour). 25 | 26 | On the other hand, the i-de.es platform blocks users if the service point is queried your user if he queries the service point too often. In our experience, no more than 5-6 calls in 10 minutes. 27 | 28 | The policy of updating the sensors only once an hour is given by the sum of these two situations. 29 | 30 | ## Q. Accumulated (or instant) consumption sensor shows 0 increment at some intervals. 31 | 32 | A. Readings from this sensors only returns integer values. If from the last reading your meter indicates a variance minor then 1 kWh, the integration will not reflect any variance and that will only be recorded once the variance from the previous reading is greater then 1. 33 | 34 | 35 | ## Q. Historical sensors (consumption and generation) doesn't have a value 36 | 37 | A. They are not supposed to. Historical sensors are a hack, HomeAssistant is not supposed to have historical sensors. 38 | 39 | Historical sensors can't provide the current state, Home Assistant will show "undefined" state forever, it's OK and intentional. To view historical data you have to go [History](https://my.home-assistant.io/redirect/history/) → Select any historical sensor → Go back some days. 40 | 41 | Keep in mind that historical data has a ~24h delay. 42 | 43 | Until 1.1.0 those sensors doen't generate statistic data. You need this data to them as an energy source in the energy panel. 44 | 45 | Before 1.1.0 you have to use the "Accumulated consumption" sensor as a source for the energy panel. 46 | 47 | ## Q. I have a problem with multiple contracts: I got banned/Doesn't work 48 | 49 | We recommend disabling the "Accumulated" and "Instant" sensors if you have multiple contracts. 50 | 51 | Due to some issues with the API and rate limit it's very possible that i-de bans you have a few hours of running this integration. 52 | 53 | **Important**: Having multiple contracts it's different of having **configured** multiple contracts. You can have multiple contracts but have only one configured in Home Assistant, or you can have multiple contracts added in HomeAssistant but only one (or none) with mentioned sensors enabled. 54 | 55 | If you have multiple contracts I recommend you to only enable historical sensors. 56 | -------------------------------------------------------------------------------- /custom_components/ideenergy/entity.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2022 Luis López 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software 15 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 16 | # USA. 17 | 18 | 19 | # TODO 20 | # Maybe we need to mark some function as callback but I'm not sure whose. 21 | # from homeassistant.core import callback 22 | 23 | import logging 24 | 25 | from homeassistant.components import recorder 26 | from homeassistant.helpers.entity import DeviceInfo 27 | from homeassistant.helpers.update_coordinator import CoordinatorEntity 28 | from homeassistant.util import slugify 29 | from homeassistant_historical_sensor.recorderutil import ( 30 | delete_entity_invalid_states, 31 | hass_recorder_session, 32 | ) 33 | 34 | SensorType = type["IDeEntity"] 35 | 36 | 37 | _LOGGER = logging.getLogger(__name__) 38 | 39 | 40 | class IDeEntity(CoordinatorEntity): 41 | """The IDeSensor class provides: 42 | __init__ 43 | __repr__ 44 | name 45 | unique_id 46 | device_info 47 | entity_registry_enabled_default 48 | """ 49 | 50 | I_DE_ENTITY_NAME = "" 51 | I_DE_DATA_SETS = [] # type: ignore[var-annotated] 52 | 53 | def __init__(self, *args, config_entry, device_info, **kwargs): 54 | super().__init__(*args, **kwargs) 55 | 56 | self._attr_has_entity_name = True 57 | self._attr_name = self.I_DE_ENTITY_NAME 58 | 59 | self._attr_unique_id = _build_entity_unique_id( 60 | device_info, self.I_DE_ENTITY_NAME 61 | ) 62 | self._attr_entity_id = _build_entity_entity_id( 63 | self.I_DE_PLATFORM, device_info, self.I_DE_ENTITY_NAME 64 | ) 65 | 66 | self._attr_device_info = device_info 67 | self._attr_entity_registry_enabled_default = True 68 | self._attr_entity_registry_visible_default = True 69 | 70 | def __repr__(self): 71 | clsname = self.__class__.__name__ 72 | if hasattr(self, "coordinator"): 73 | api = self.coordinator.api.username 74 | else: 75 | api = self.api 76 | 77 | return f"<{clsname} {api.username}/{api._contract}>" 78 | 79 | async def async_added_to_hass(self) -> None: 80 | n_invalid_states = await self.async_delete_invalid_states() 81 | _LOGGER.debug(f"{self.entity_id}: cleaned {n_invalid_states} invalid states") 82 | 83 | await super().async_added_to_hass() 84 | 85 | self.coordinator.register_sensor(self) 86 | 87 | await self.coordinator.async_request_refresh() 88 | 89 | async def async_will_remove_from_hass(self) -> None: 90 | self.coordinator.unregister_sensor(self) 91 | await super().async_will_remove_from_hass() 92 | 93 | async def async_delete_invalid_states(self) -> int: 94 | if getattr(self, "hass", None) is None: 95 | raise TypeError(f"{self.entity_id} is not added to hass") 96 | 97 | def fn(): 98 | with hass_recorder_session(self.hass) as session: 99 | return delete_entity_invalid_states(session, self) 100 | 101 | return await recorder.get_instance(self.hass).async_add_executor_job(fn) 102 | 103 | 104 | def _build_entity_unique_id(device_info: DeviceInfo, entity_unique_name: str) -> str: 105 | cups = dict(device_info["identifiers"])["cups"] 106 | return slugify(f"{cups}-{entity_unique_name}", separator="-") 107 | 108 | 109 | def _build_entity_entity_id( 110 | platform: str, 111 | device_info: DeviceInfo, 112 | entity_unique_name: str, 113 | ) -> str: 114 | partial_id = _build_entity_unique_id(device_info, entity_unique_name) 115 | 116 | return f"{platform}.{partial_id}".lower() 117 | -------------------------------------------------------------------------------- /custom_components/ideenergy/config_flow.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2021 Luis López 3 | # 4 | # This program is free software; you can redistribute it and/or 5 | # modify it under the terms of the GNU General Public License 6 | # as published by the Free Software Foundation; either version 2 7 | # of the License, or (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program; if not, write to the Free Software 16 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 17 | # USA. 18 | 19 | 20 | import os 21 | from typing import Any 22 | 23 | import ideenergy 24 | import voluptuous as vol 25 | from homeassistant import config_entries 26 | from homeassistant.const import CONF_PASSWORD, CONF_USERNAME 27 | from homeassistant.core import callback # noqa: F401 28 | from homeassistant.data_entry_flow import FlowResult 29 | from homeassistant.helpers.aiohttp_client import async_create_clientsession 30 | 31 | from . import _LOGGER 32 | from .const import CONF_CONTRACT, CONFIG_ENTRY_VERSION, DOMAIN 33 | 34 | AUTH_SCHEMA = vol.Schema( 35 | { 36 | vol.Required(CONF_USERNAME, default=os.environ.get("HASS_I_DE_USERNAME")): str, 37 | vol.Required(CONF_PASSWORD, default=os.environ.get("HASS_I_DE_PASSWORD")): str, 38 | } 39 | ) 40 | 41 | 42 | class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): # type: ignore[call-arg] 43 | VERSION = CONFIG_ENTRY_VERSION 44 | 45 | def __init__(self, *args, **kwargs): 46 | super().__init__(*args, **kwargs) 47 | self.info = {} 48 | self.api = None 49 | 50 | # @staticmethod 51 | # @callback 52 | # def async_get_options_flow(config_entry): 53 | # return OptionsFlowHandler(config_entry) 54 | 55 | async def async_step_user( 56 | self, user_input: dict[str, Any] | None = None 57 | ) -> FlowResult: 58 | """Handle a flow initialized by the user.""" 59 | errors = {} 60 | 61 | if user_input is not None: 62 | # Not used correctly, check 63 | # https://developers.home-assistant.io/docs/config_entries_config_flow_handler/#unique-ids 64 | # 65 | # await self.async_set_unique_id(user_input[CONF_NAME]) 66 | # self._abort_if_unique_id_configured() 67 | 68 | username = user_input[CONF_USERNAME] 69 | password = user_input[CONF_PASSWORD] 70 | 71 | try: 72 | self.api = await create_api(self.hass, username, password) 73 | 74 | except ideenergy.ClientError: 75 | errors["base"] = "invalid_auth" 76 | 77 | except Exception: # pylint: disable=broad-except 78 | _LOGGER.exception("Unexpected exception") 79 | errors["base"] = "unknown" 80 | 81 | else: 82 | self.info.update( 83 | { 84 | CONF_USERNAME: username, 85 | CONF_PASSWORD: password, 86 | } 87 | ) 88 | return await self.async_step_contract() 89 | 90 | return self.async_show_form( 91 | step_id="user", 92 | data_schema=AUTH_SCHEMA, 93 | errors=errors, 94 | ) 95 | 96 | async def async_step_contract( 97 | self, user_input: dict[str, Any] | None = None 98 | ) -> FlowResult: 99 | contracts = await self.api.get_contracts() 100 | contracts = {f"{x['cups']} ({x['direccion']})": x for x in contracts} 101 | 102 | schema = vol.Schema({vol.Required(CONF_CONTRACT): vol.In(contracts.keys())}) 103 | 104 | if not user_input: 105 | return self.async_show_form(step_id="contract", data_schema=schema) 106 | 107 | contract = contracts[user_input["contract"]] 108 | self.info.update( 109 | { 110 | CONF_CONTRACT: contract["codContrato"], 111 | } 112 | ) 113 | 114 | title = "CUPS " + contract["cups"] 115 | return self.async_create_entry(title=title, data=self.info) 116 | 117 | 118 | # class OptionsFlowHandler(config_entries.OptionsFlow): 119 | # def __init__(self, config_entry): 120 | # """Initialize options flow.""" 121 | # self.config_entry = config_entry 122 | # 123 | # async def async_step_init(self, user_input=None): 124 | # if user_input is not None: 125 | # return self.async_create_entry(title="", data=user_input) 126 | # 127 | # OPTIONS_SCHEMA = vol.Schema({}) 128 | # 129 | # return self.async_show_form(step_id="init", data_schema=OPTIONS_SCHEMA) 130 | 131 | 132 | async def create_api(hass, username, password): 133 | sess = async_create_clientsession(hass) 134 | client = ideenergy.Client(sess, username, password) 135 | 136 | await client.login() 137 | return client 138 | -------------------------------------------------------------------------------- /README.es.md: -------------------------------------------------------------------------------- 1 | # i-DE (Iberdrola Distribución) Custom Integration for Home Assistant 2 | 3 | 4 | [![hacs_badge](https://img.shields.io/badge/HACS-Custom-orange.svg)](https://github.com/custom-components/hacs) 5 | [![hassfest validation](https://github.com/ldotlopez/ha-ideenergy/workflows/Validate%20with%20hassfest/badge.svg)](https://github.com/ldotlopez/ha-ideenergy/actions/workflows/hassfest.yml) 6 | [![HACS validation](https://github.com/ldotlopez/ha-ideenergy/workflows/Validate%20with%20HACS/badge.svg)](https://github.com/ldotlopez/ha-ideenergy/actions/workflows/hacs.yml) 7 | 8 | 9 | ![GitHub Release (latest SemVer including pre-releases)](https://img.shields.io/github/v/release/ldotlopez/ha-ideenergy?include_prereleases) 10 | [![CodeQL](https://github.com/ldotlopez/ha-ideenergy/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/ldotlopez/ha-ideenergy/actions/workflows/codeql-analysis.yml) 11 | [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black) 12 | 13 | [ideenergy](https://github.com/ldotlopez/ideenergy) integration for [home-assistant](https://home-assistant.io/) 14 | 15 | Esta integración provee sensores para el distribuidor de energía español [i-DE](i-de.es). 16 | 17 | Require de un usuario **avanzado** en la página web del distribuidor. 18 | 19 | **⚠️ Asegurese de leer la [FAQ](https://github.com/ldotlopez/ha-ideenergy/blob/main/FAQ.md)' y las secciones 'advertencias' y 'dependencias'.** 20 | 21 | ## Características 22 | 23 | * Integración con el panel del energía de Home Assistant 24 | 25 | * Sensores de consumo instantaneo y acumulado. 26 | 27 | * Sensores históricos (consumulo y generación solar) con mayor precisión (sub-kWh). Estos datos no son tiempo real y normalmente llevan un retraso de entre 24 y 48 horas. 28 | 29 | * Soporte para varios contratos (puntos de servicio). 30 | 31 | * Configuración a través del [interfaz web de Home Assistant](https://developers.home-assistant.io/docs/config_entries_options_flow_handler) sin necesidad de editar ficheros YAML. 32 | 33 | * Algoritmo de actualización para leer el contador cerca del final de cada periodo horario (entre el minuto 50 y 59) y una mejor representación del consumo en el panel de energía de Home Assistant 34 | 35 | * Totalmente [asíncrono](https://developers.home-assistant.io/docs/asyncio_index) e integrado en Home Assistant. 36 | 37 | 38 | ## Dependencies 39 | 40 | Es necesario disponer de acceso al área de clientes de i-DE. 41 | Puedes registrarte en el siguiente link: [Área Clientes | I-DE - Grupo Iberdrola](https://www.i-de.es/consumidores/web/guest/login). 42 | 43 | Además es necesario disponer del perfil de "Usuario avanzado". Si no se dispone de él hay que rellenar un formulario del [Perfil de cliente](https://www.i-de.es/consumidores/web/home/personal-area/userData). 44 | 45 | ### Usando [HACS](https://hacs.xyz/) (recomendado) 46 | 47 | 1. Copia la dirección de este repositorio: [https://github.com/ldotlopez/ha-ideenergy](https://github.com/ldotlopez/ha-ideenergy/) 48 | 49 | 2. Añade este repositorio en HACS como "repositorio manual": 50 | 51 | - En el campo "Repositorio" pega la URL anterior. 52 | - En el campo "Categoría" elige "Integración" 53 | - Pulsa el botón "Descargar" y elige la última versión. 54 | 55 | ![Custom repository](https://user-images.githubusercontent.com/59612788/171965822-4a89c14e-9eb2-4134-8de2-1d3f380663e4.png) 56 | 57 | 3. Reinicia Home Assistant 58 | 59 | 4. Configura la integración 60 | 61 | - (Opción A) Pulsa el botón "Añadir integración" → [![Open your Home Assistant instance and start setting up a new integration.](https://my.home-assistant.io/badges/config_flow_start.svg)](https://my.home-assistant.io/redirect/config_flow_start/?domain=ideenergy) 62 | 63 | - (Opción B) Navega a "Ajustes" → "Dispositivos y servicios" y pulsa "Añadir integración". Elige "i-DE.es sensores de energía". 64 | ![image](https://user-images.githubusercontent.com/59612788/171966005-e58f6b88-a952-4033-82c6-b1d4ea665873.png) 65 | 66 | 5. Sigue los pasos del asistente: Proporciona tus credenciales de acceso para el área de cliente de "i-DE", después elige el contrato qu deseas monitorizar. Si necesitas añadir más contratos repite los pasos anteriores para cada uno de ellos. 67 | 68 | ## Instalación 69 | 70 | A través de custom_components o [HACS](https://hacs.xyz/) 71 | 72 | 1. Descarga o clona este repositorio: [https://github.com/ldotlopez/ha-ideenergy](https://github.com/ldotlopez/ha-ideenergy) 73 | 74 | 2. Copia la carpeta `custom_components/ideenergy` en tu carpeta `custom_components` de tu instalación de Home Assistant. 75 | 76 | 3. Reinicia Home Assistant 77 | 4. Configura la integración 78 | 79 | - (Opción A) Pulsa el botón "Añadir integración" → [![Open your Home Assistant instance and start setting up a new integration.](https://my.home-assistant.io/badges/config_flow_start.svg)](https://my.home-assistant.io/redirect/config_flow_start/?domain=ideenergy) 80 | 81 | - (Opción B) Navega a "Ajustes" → "Dispositivos y servicios" y pulsa "Añadir integración". Elige "i-DE.es sensores de energía". 82 | ![image](https://user-images.githubusercontent.com/59612788/171966005-e58f6b88-a952-4033-82c6-b1d4ea665873.png) 83 | 84 | 5. Sigue los pasos del asistente: Proporciona tus credenciales de acceso para el área de cliente de "i-DE", después elige el contrato qu deseas monitorizar. Si necesitas añadir más contratos repite los pasos anteriores para cada uno de ellos. 85 | 86 | ## Capturas 87 | 88 | *Sensor de energía acumulada* 89 | 90 | ![snapshot](screenshots/accumulated.png) 91 | 92 | *Sensor de histórico de energía* 93 | 94 | ![snapshot](screenshots/historical.png) 95 | 96 | *Asistente de configuración* 97 | 98 | ![snapshot](screenshots/configuration-1.png) 99 | ![snapshot](screenshots/configuration-2.png) 100 | 101 | 102 | 103 | ## Advertencias 104 | Esta integración provee un sensor 'histórico' que incorpora datos del pasado en la base de datos de Home Assistant. Por su propia seguridad este sensor no está habilitado y debe activarse manualmente. 105 | 106 | ☠️ El sensor histórico está basado en un **hack extremadamente experimental** y puede romper y/o corromper su base de datos y/o estadísticas. **Use lo bajo su propio riesgo**. 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # i-DE (Iberdrola Distribución) Custom Integration for Home Assistant 2 | 3 | 4 | [![hacs_badge](https://img.shields.io/badge/HACS-Custom-orange.svg)](https://github.com/custom-components/hacs) 5 | [![hassfest validation](https://github.com/ldotlopez/ha-ideenergy/workflows/Validate%20with%20hassfest/badge.svg)](https://github.com/ldotlopez/ha-ideenergy/actions/workflows/hassfest.yml) 6 | [![HACS validation](https://github.com/ldotlopez/ha-ideenergy/workflows/Validate%20with%20HACS/badge.svg)](https://github.com/ldotlopez/ha-ideenergy/actions/workflows/hacs.yml) 7 | 8 | 9 | ![GitHub Release (latest SemVer including pre-releases)](https://img.shields.io/github/v/release/ldotlopez/ha-ideenergy?include_prereleases) 10 | [![CodeQL](https://github.com/ldotlopez/ha-ideenergy/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/ldotlopez/ha-ideenergy/actions/workflows/codeql-analysis.yml) 11 | [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black) 12 | 13 | [ideenergy](https://github.com/ldotlopez/ideenergy) integration for [home-assistant](https://home-assistant.io/) 14 | 15 | i-DE (Iberdrola Distribución) Custom Integration for Home Assistant, providing sensors for Spanish Energy Distributor [i-DE](https://i-de.es). 16 | 17 | This integration requires an **advanced** user profile on i-DE website. 18 | 19 | **⚠️ Make sure to read the '[FAQ](https://github.com/ldotlopez/ha-ideenergy/blob/main/FAQ.md)', 'Dependencies' and 'Warning' sections** 20 | 21 | 22 | ## Features 23 | 24 | * Integration with the Home Assistant Energy Panel. 25 | 26 | * Accumulated and Instant consumption sensors. 27 | 28 | * Historical sensors (both consumption and solar generation) with better (sub-kWh) precision. This data is not realtime and usually has a 24-hour to 48-hour offset. 29 | 30 | * Support for multiple contracts (service points). 31 | 32 | * Configuration through [Home Assistant Interface](https://developers.home-assistant.io/docs/config_entries_options_flow_handler) without the need to edit YAML files. 33 | 34 | * Update algorithm to read the meter near the end of each hourly period (between minute 50 and 59) 35 | with a better representation of consumption in the Home Assistant energy panel. 36 | 37 | * Fully [asynchronous](https://developers.home-assistant.io/docs/asyncio_index) and integrated with HomeAssistant. 38 | 39 | 40 | ## Dependencies 41 | 42 | You must have an i-DE username and access to the Clients' website. You may register here: [Área Clientes | I-DE - Grupo Iberdrola](https://www.i-de.es/consumidores/web/guest/login). 43 | 44 | It also necessary to have an "Advanced User" profile. Should you not have one already, you need to fill the request for from your [Profile Area](https://www.i-de.es/consumidores/web/home/personal-area/userData). 45 | 46 | 47 | ## Installation 48 | 49 | ### Using [HACS](https://hacs.xyz/) (recommended) 50 | 51 | 1. Copy this repository URL: [https://github.com/ldotlopez/ha-ideenergy](https://github.com/ldotlopez/ha-ideenergy/) 52 | 53 | 2. In the HACS section, add this repository as a custom one: 54 | 55 | 56 | - On the "repositorysitory" field put the URL copied before 57 | - On the "Category" select "Integration" 58 | - Click the "Download" button and download latest version. 59 | 60 | ![Custom repositorysitory](https://user-images.githubusercontent.com/59612788/171965822-4a89c14e-9eb2-4134-8de2-1d3f380663e4.png) 61 | 62 | 3. Restart HA 63 | 64 | 4. Configure the integration 65 | 66 | - (Option A) Click the "Add integration" button → [![Open your Home Assistant instance and start setting up a new integration.](https://my.home-assistant.io/badges/config_flow_start.svg)](https://my.home-assistant.io/redirect/config_flow_start/?domain=ideenergy) 67 | 68 | - (Option B) Go to "Settings" "Devices & Services" and click "+ ADD INTEGRATION" and select "i-de.es energy sensors". 69 | ![image](https://user-images.githubusercontent.com/59612788/171966005-e58f6b88-a952-4033-82c6-b1d4ea665873.png) 70 | 71 | 5. Follow the configuration steps: provide your credentials for access to i-DE and select the contract that you want to monitor. (Should you need to add more contracts, just follow the previous step as many times as needed). 72 | 73 | 74 | ### Manually 75 | 76 | 1. Download/clone this repository: [https://github.com/ldotlopez/ha-ideenergy](https://github.com/ldotlopez/ha-ideenergy/) 77 | 78 | 2. Copy the `custom_components/ideenergy` folder into your custom_components folder into your HA installation 79 | 80 | 3. Restart HA 81 | 82 | 4. Configure the integration 83 | 84 | - (Option A) Click on this button → [![Open your Home Assistant instance and start setting up a new integration.](https://my.home-assistant.io/badges/config_flow_start.svg)](https://my.home-assistant.io/redirect/config_flow_start/?domain=ideenergy) 85 | - (Option B) Go to "Settings" → "Devices & Services" and click "+ ADD INTEGRATION" and select "i-de.es energy sensors". 86 | ![image](https://user-images.githubusercontent.com/59612788/171966005-e58f6b88-a952-4033-82c6-b1d4ea665873.png) 87 | 88 | 5. Follow the configuration steps: provide your credentials for access to i-DE and select the contract that you want to monitor. (Should you need to add more contracts, just follow the previous step as many times as needed). 89 | 90 | ## Snapshots 91 | 92 | *Accumulated energy sensor* 93 | 94 | ![snapshot](screenshots/accumulated.png) 95 | 96 | *Historical energy sensor* 97 | 98 | ![snapshot](screenshots/historical.png) 99 | 100 | *Configuration wizard* 101 | 102 | ![snapshot](screenshots/configuration-1.png) 103 | ![snapshot](screenshots/configuration-2.png) 104 | 105 | ## Warnings 106 | This extension provides a 'historical' sensor to incorporate past data into your Home Assistant database. For safety reasons, the sensor is disabled by default and must be enabled manually. 107 | 108 | ☠️ The historical sensor is based on a **highly experimental hack** and could corrupt your database and/or statistics. **Use with extreme caution and at your own risk**. 109 | 110 | ## License 111 | 112 | This project is licensed under the GNU General Public License v3.0 License - see the LICENSE file for details 113 | 114 | 115 | ## Disclaimer 116 | 117 | THIS PROJECT IS NOT IN ANY WAY ASSOCIATED WITH OR RELATED TO THE IBERDROLA GROUP COMPANIES OR ANY OTHER. The information here and online is for educational and resource purposes only and therefore the developers do not endorse or condone any inappropriate use of it, and take no legal responsibility for the functionality or security of your devices. 118 | -------------------------------------------------------------------------------- /custom_components/ideenergy/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2022 Luis López 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software 15 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 16 | # USA. 17 | 18 | 19 | import asyncio 20 | import logging 21 | import math 22 | from datetime import timedelta 23 | 24 | import ideenergy 25 | from homeassistant.config_entries import ConfigEntry 26 | from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform 27 | from homeassistant.core import HomeAssistant 28 | from homeassistant.exceptions import ConfigEntryNotReady 29 | from homeassistant.helpers.aiohttp_client import async_get_clientsession 30 | from homeassistant.helpers.entity import DeviceInfo 31 | 32 | from .barrier import TimeDeltaBarrier, TimeWindowBarrier # NoopBarrier, 33 | from .const import ( 34 | API_USER_SESSION_TIMEOUT, 35 | CONF_CONTRACT, 36 | DOMAIN, 37 | MAX_RETRIES, 38 | MEASURE_MAX_AGE, 39 | MIN_SCAN_INTERVAL, 40 | UPDATE_WINDOW_END_MINUTE, 41 | UPDATE_WINDOW_START_MINUTE, 42 | ) 43 | from .datacoordinator import DataSetType, IDeCoordinator 44 | from .updates import update_integration 45 | 46 | PLATFORMS: list[str] = [Platform.SENSOR] 47 | 48 | _LOGGER = logging.getLogger(__name__) 49 | 50 | 51 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 52 | api = IDeEnergyAPI(hass, entry) 53 | 54 | try: 55 | contract_details = await api.get_contract_details() 56 | except ideenergy.client.ClientError as e: 57 | _LOGGER.debug(f"Unable to initialize integration: {e}") 58 | return False 59 | 60 | device_info = IDeEnergyDeviceInfo(contract_details) 61 | 62 | coordinator = IDeCoordinator( 63 | hass=hass, 64 | api=api, 65 | barriers={ 66 | DataSetType.MEASURE: TimeWindowBarrier( 67 | allowed_window_minutes=( 68 | UPDATE_WINDOW_START_MINUTE, 69 | UPDATE_WINDOW_END_MINUTE, 70 | ), 71 | max_retries=MAX_RETRIES, 72 | max_age=timedelta(seconds=MEASURE_MAX_AGE), 73 | ), 74 | DataSetType.HISTORICAL_CONSUMPTION: TimeDeltaBarrier( 75 | delta=timedelta(hours=6) 76 | ), 77 | DataSetType.HISTORICAL_GENERATION: TimeDeltaBarrier( 78 | delta=timedelta(hours=6) 79 | ), 80 | DataSetType.HISTORICAL_POWER_DEMAND: TimeDeltaBarrier( 81 | delta=timedelta(hours=36) 82 | ), 83 | }, 84 | # Use default update_interval and relay on barriers for now 85 | # MEASURE barrier should deny if last attempt (success or not) is too recent to 86 | # prevent api smashing or subsequent baning 87 | update_interval=_calculate_datacoordinator_update_interval(), 88 | # update_interval=timedelta(seconds=30), 89 | ) 90 | 91 | # Don't refresh coordinator yet since there isn't any sensor registered 92 | # await coordinator.async_refresh() 93 | 94 | if not coordinator.last_update_success: 95 | raise ConfigEntryNotReady 96 | 97 | hass.data[DOMAIN] = hass.data.get(DOMAIN, {}) 98 | hass.data[DOMAIN][entry.entry_id] = (coordinator, device_info) 99 | 100 | for platform in PLATFORMS: 101 | if entry.options.get(platform, True): 102 | coordinator.platforms.append(platform) 103 | await hass.config_entries.async_forward_entry_setups(entry,coordinator.platforms) 104 | 105 | entry.async_on_unload(entry.add_update_listener(async_reload_entry)) 106 | 107 | return True 108 | 109 | 110 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 111 | coordinator, _ = hass.data[DOMAIN][entry.entry_id] 112 | unloaded = all( 113 | await asyncio.gather( 114 | *[ 115 | hass.config_entries.async_forward_entry_unload(entry, platform) 116 | for platform in PLATFORMS 117 | if platform in coordinator.platforms 118 | ] 119 | ) 120 | ) 121 | if unloaded: 122 | hass.data[DOMAIN].pop(entry.entry_id) 123 | 124 | return unloaded 125 | 126 | 127 | async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: 128 | await async_unload_entry(hass, entry) 129 | await async_setup_entry(hass, entry) 130 | 131 | 132 | def _calculate_datacoordinator_update_interval() -> timedelta: 133 | # 134 | # Calculate SCAN_INTERVAL to allow two updates within the update window 135 | # 136 | update_window_width = ( 137 | UPDATE_WINDOW_END_MINUTE * 60 - UPDATE_WINDOW_START_MINUTE * 60 138 | ) 139 | update_interval = math.floor(update_window_width / 2) 140 | update_interval = max([MIN_SCAN_INTERVAL, update_interval]) 141 | 142 | return timedelta(seconds=update_interval) 143 | 144 | 145 | async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry): 146 | api = IDeEnergyAPI(hass, entry) 147 | 148 | try: 149 | contract_details = await api.get_contract_details() 150 | except ideenergy.client.ClientError as e: 151 | _LOGGER.debug(f"Unable to initialize integration: {e}") 152 | return False 153 | 154 | update_integration(hass, entry, IDeEnergyDeviceInfo(contract_details)) 155 | return True 156 | 157 | 158 | def IDeEnergyDeviceInfo(contract_details): 159 | return DeviceInfo( 160 | identifiers={ 161 | ("cups", contract_details["cups"]), 162 | }, 163 | name=contract_details["cups"], 164 | manufacturer=contract_details["listContador"][0]["tipMarca"], 165 | ) 166 | 167 | 168 | def IDeEnergyAPI(hass: HomeAssistant, entry: ConfigEntry): 169 | return ideenergy.Client( 170 | session=async_get_clientsession(hass), 171 | username=entry.data[CONF_USERNAME], 172 | password=entry.data[CONF_PASSWORD], 173 | contract=entry.data[CONF_CONTRACT], 174 | user_session_timeout=API_USER_SESSION_TIMEOUT, 175 | ) 176 | -------------------------------------------------------------------------------- /custom_components/ideenergy/updates.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2022 Luis López 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software 15 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 16 | # USA. 17 | 18 | 19 | import logging 20 | 21 | from homeassistant.config_entries import ConfigEntry 22 | from homeassistant.core import HomeAssistant 23 | from homeassistant.helpers import device_registry, entity_registry 24 | from homeassistant.helpers.entity import DeviceInfo 25 | from homeassistant.util import slugify 26 | 27 | from custom_components.ideenergy.const import DOMAIN 28 | 29 | from .entity import IDeEntity 30 | from .entity import _build_entity_unique_id as _build_entity_unique_id_v3 31 | from .sensor import AccumulatedConsumption, HistoricalConsumption 32 | 33 | _LOGGER = logging.getLogger(__name__) 34 | 35 | SensorType = type[IDeEntity] 36 | 37 | 38 | def update_integration( 39 | hass: HomeAssistant, config_entry: ConfigEntry, device_info: DeviceInfo 40 | ) -> None: 41 | if config_entry.version < 2: 42 | _update_entity_registry_v1(hass, config_entry, device_info) 43 | _update_device_registry_v1(hass, config_entry, device_info) 44 | _update_config_entry_v1(hass, config_entry) 45 | 46 | _LOGGER.debug("Update to version 2 completed") 47 | 48 | if config_entry.version < 3: 49 | _update_config_v2(hass, config_entry, device_info) 50 | 51 | _LOGGER.debug("Update to version 3 completed") 52 | 53 | 54 | def _update_config_v2( 55 | hass: HomeAssistant, config_entry: ConfigEntry, device_info: DeviceInfo 56 | ) -> None: 57 | dr = device_registry.async_get(hass) 58 | er = entity_registry.async_get(hass) 59 | 60 | device = dr.async_get_device(device_info["identifiers"]) 61 | entities = {id: e for id, e in er.entities.items() if e.device_id == device.id} 62 | 63 | for _, entity in entities.items(): 64 | old_unique_id = entity.unique_id 65 | new_unique_id = _build_entity_unique_id_v3( 66 | device_info, entity.name or entity.original_name 67 | ) 68 | 69 | er.async_update_entity( 70 | entity.entity_id, 71 | new_unique_id=new_unique_id, 72 | ) 73 | _LOGGER.debug(f"Updated entity '{entity.entity_id}'") 74 | _LOGGER.debug(f" [-] unique_id '{old_unique_id}'") 75 | _LOGGER.debug(f" [+] unique_id '{new_unique_id}'") 76 | 77 | config_entry.version = 3 78 | 79 | hass.config_entries.async_update_entry(config_entry) 80 | _LOGGER.debug(f"ConfigEntry updated to version '{config_entry.version}'") 81 | 82 | 83 | def _build_entity_unique_id_v2( 84 | config_entry: ConfigEntry, 85 | device_info: DeviceInfo, 86 | SensorClass: SensorType, 87 | ) -> str: 88 | cups = dict(device_info["identifiers"])["cups"] 89 | 90 | return slugify(SensorClass.I_DE_ENTITY_NAME).replace("_", "-") 91 | 92 | 93 | def _build_entity_entity_id_v2( 94 | config_entry: ConfigEntry, 95 | device_info: DeviceInfo, 96 | SensorClass: SensorType, 97 | ) -> str: 98 | cups = dict(device_info["identifiers"])["cups"] 99 | base_id = slugify(f"{DOMAIN}" + f"_{cups}" + f"_{SensorClass.I_DE_ENTITY_NAME}") 100 | 101 | return f"{SensorClass.I_DE_PLATFORM}.{base_id}".lower() 102 | 103 | 104 | # 105 | # Don't modify anything below this line unless it's critical 106 | # 107 | 108 | 109 | def _update_config_entry_v1(hass: HomeAssistant, config_entry: ConfigEntry): 110 | new_data = dict(config_entry.data) 111 | new_data.pop("name") 112 | 113 | config_entry.version = 2 114 | 115 | hass.config_entries.async_update_entry(config_entry, data=new_data) 116 | _LOGGER.debug(f"ConfigEntry updated to version '{config_entry.version}'") 117 | 118 | 119 | def _update_device_registry_v1( 120 | hass: HomeAssistant, 121 | config_entry: ConfigEntry, 122 | device_info: DeviceInfo, 123 | ): 124 | dr = device_registry.async_get(hass) 125 | for dev in dr.devices.values(): 126 | if config_entry.entry_id not in dev.config_entries: 127 | continue 128 | 129 | if dev.identifiers == device_info["identifiers"]: 130 | continue 131 | 132 | old_ids = dev.identifiers 133 | new_ids = device_info["identifiers"] 134 | 135 | dr.async_update_device(dev.id, new_identifiers=new_ids) 136 | _LOGGER.debug(f"DeviceEntry '{dev.id}' updated ({old_ids} → {new_ids})") 137 | 138 | _LOGGER.debug(f"Updated device '{dev.id}'") 139 | _LOGGER.debug(f" [-] identifiers '{old_ids}'") 140 | _LOGGER.debug(f" [+] identifiers '{new_ids}'") 141 | 142 | 143 | def _update_entity_registry_v1( 144 | hass: HomeAssistant, 145 | config_entry: ConfigEntry, 146 | device_info: DeviceInfo, 147 | ): 148 | er = entity_registry.async_get(hass) 149 | migrate = ( 150 | ("accumulated", AccumulatedConsumption), 151 | ("historical", HistoricalConsumption), 152 | ) 153 | 154 | for old_sensor_type, new_sensor_cls in migrate: 155 | entity_id = er.async_get_entity_id( 156 | "sensor", 157 | "ideenergy", 158 | _build_entity_unique_id_v1(config_entry, old_sensor_type), 159 | ) 160 | if not entity_id: 161 | continue 162 | 163 | entity = er.async_get(entity_id) 164 | if not entity: 165 | continue 166 | 167 | old_unique_id = entity.unique_id 168 | new_unique_id = _build_entity_unique_id_v2( 169 | config_entry, device_info, new_sensor_cls 170 | ) 171 | 172 | new_entity_id = _build_entity_entity_id_v2( 173 | config_entry, device_info, new_sensor_cls 174 | ) 175 | 176 | old_name = getattr(entity, "name") 177 | new_name = new_sensor_cls.I_DE_ENTITY_NAME 178 | 179 | er.async_update_entity( 180 | entity.entity_id, 181 | new_unique_id=new_unique_id, 182 | # new_entity_id=new_entity_id, 183 | original_name=new_name, 184 | ) 185 | 186 | _LOGGER.debug(f"Updated entity '{entity_id}'") 187 | _LOGGER.debug(f" [-] unique_id '{old_unique_id}'") 188 | _LOGGER.debug(f" [-] name '{old_name}'") 189 | _LOGGER.debug(f" [+] unique_id '{new_unique_id}'") 190 | _LOGGER.debug(f" [+] name '{new_name}'") 191 | 192 | 193 | def _build_entity_unique_id_v1(config_entry: ConfigEntry, sensor_type: str): 194 | # "unique_id": "dc5088dfcf71e4a1096539c61d057299-accumulated", 195 | return f"{config_entry.entry_id}-{sensor_type}" 196 | -------------------------------------------------------------------------------- /custom_components/ideenergy/fixes.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2022 Luis López 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software 15 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 16 | # USA. 17 | 18 | 19 | import logging 20 | 21 | import sqlalchemy as sa 22 | from homeassistant.components import recorder 23 | from homeassistant.components.recorder import db_schema, statistics 24 | from homeassistant.core import HomeAssistant, dt_util 25 | from homeassistant_historical_sensor import recorderutil 26 | 27 | _LOGGER = logging.getLogger(__name__) 28 | 29 | 30 | async def async_fix_statistics( 31 | hass: HomeAssistant, statistic_metadata: statistics.StatisticMetaData 32 | ) -> None: 33 | def timestamp_as_local(timestamp): 34 | return dt_util.as_local(dt_util.utc_from_timestamp(timestamp)) 35 | 36 | def fn(): 37 | fixes_applied = False 38 | 39 | statistic_id = statistic_metadata["statistic_id"] 40 | statistic_metadata_has_mean = statistic_metadata.get("has_mean", False) 41 | statistic_metadata_has_sum = statistic_metadata.get("has_sum", False) 42 | 43 | with recorderutil.hass_recorder_session(hass) as session: 44 | # 45 | # Check and fix current metadata 46 | # 47 | 48 | current_metadata = session.execute( 49 | sa.select(db_schema.StatisticsMeta).where( 50 | db_schema.StatisticsMeta.statistic_id == statistic_id 51 | ) 52 | ).scalar() 53 | 54 | if current_metadata is None: 55 | _LOGGER.debug(f"{statistic_id}: no statistics found, nothing to fix") 56 | return 57 | 58 | statistics_base_stmt = sa.select(db_schema.Statistics).where( 59 | db_schema.Statistics.metadata_id == current_metadata.id 60 | ) 61 | 62 | metadata_needs_fixes = ( 63 | current_metadata.has_mean != statistic_metadata_has_mean 64 | ) or (current_metadata.has_sum != statistic_metadata_has_sum) 65 | 66 | if metadata_needs_fixes: 67 | _LOGGER.debug( 68 | f"{statistic_id}: statistic metadata is outdated." 69 | f" has_mean:{current_metadata.has_mean}→{statistic_metadata_has_mean}" 70 | f" has_sum:{current_metadata.has_sum}→{statistic_metadata_has_sum}" 71 | ) 72 | current_metadata.has_mean = statistic_metadata_has_mean 73 | current_metadata.has_sum = statistic_metadata_has_sum 74 | session.add(current_metadata) 75 | session.commit() 76 | fixes_applied = True 77 | 78 | # 79 | # Check for broken points and decreasings 80 | # 81 | broken_point = None 82 | 83 | prev_sum = 0 84 | statistics_iter_stmt = statistics_base_stmt.order_by( 85 | db_schema.Statistics.start_ts.asc() 86 | ) 87 | 88 | for statistic in session.execute(statistics_iter_stmt).scalars(): 89 | is_broken = False 90 | local_start_dt = timestamp_as_local(statistic.start_ts) 91 | 92 | # Check for NULL mean 93 | if statistic_metadata_has_mean and statistic.mean is None: 94 | is_broken = True 95 | _LOGGER.debug( 96 | f"{statistic_id}: mean value at {local_start_dt} is NULL" 97 | ) 98 | 99 | # Check for NULL sum 100 | if statistic_metadata_has_sum and statistic.sum is None: 101 | is_broken = True 102 | _LOGGER.debug( 103 | f"{statistic_id}: sum value at {local_start_dt} is NULL" 104 | ) 105 | 106 | # Check for decreasing values in sum 107 | if statistic_metadata_has_sum and statistic.sum: 108 | if statistic.sum < prev_sum: 109 | is_broken = True 110 | _LOGGER.debug( 111 | f"{statistic_id}: " 112 | + f"decreasing sum at {local_start_dt} " 113 | + f"{statistic.sum} < {prev_sum} ({statistic!r})" 114 | ) 115 | else: 116 | prev_sum = statistic.sum 117 | 118 | # Found anything broken? 119 | if is_broken: 120 | broken_point = statistic.start_ts 121 | break 122 | 123 | # 124 | # Check for broken points (search only for NULLs) 125 | # 126 | 127 | # clauses_for_additional_or_ = [db_schema.Statistics.state == None] 128 | # if statistic_metadata_has_mean: 129 | # clauses_for_additional_or_.append(db_schema.Statistics.mean == None) 130 | # if statistic_metadata_has_sum: 131 | # clauses_for_additional_or_.append(db_schema.Statistics.sum == None) 132 | 133 | # find_broken_point_stmt = ( 134 | # sa.select(sa.func.min(db_schema.Statistics.start_ts)) 135 | # .where(db_schema.Statistics.metadata_id == current_metadata.id) 136 | # .where(sa.or_(*clauses_for_additional_or_)) 137 | # ) 138 | 139 | # broken_point = session.execute(find_broken_point_stmt).scalar() 140 | 141 | # 142 | # Delete everything after broken point 143 | # 144 | if broken_point: 145 | invalid_statistics_stmt = statistics_base_stmt.where( 146 | db_schema.Statistics.start_ts >= broken_point 147 | ) 148 | invalid_statistics = ( 149 | session.execute(invalid_statistics_stmt).scalars().fetchall() 150 | ) 151 | 152 | for x in invalid_statistics: 153 | session.delete(x) 154 | 155 | session.commit() 156 | fixes_applied = True 157 | 158 | _LOGGER.debug( 159 | f"{statistic_id}: " 160 | f"found broken point at {timestamp_as_local(broken_point)}," 161 | f" deleted {len(invalid_statistics)} statistics" 162 | ) 163 | 164 | # 165 | # Delete additional statistics 166 | # 167 | 168 | clauses_for_additional_or_ = [db_schema.Statistics.state == None] 169 | 170 | if statistic_metadata_has_mean: 171 | clauses_for_additional_or_.append(db_schema.Statistics.mean == None) 172 | 173 | if statistic_metadata_has_sum: 174 | clauses_for_additional_or_.append(db_schema.Statistics.sum == None) 175 | 176 | invalid_statistics_stmt = statistics_base_stmt.where( 177 | sa.or_(*clauses_for_additional_or_) 178 | ) 179 | 180 | invalid_statistics = ( 181 | session.execute(invalid_statistics_stmt).scalars().fetchall() 182 | ) 183 | 184 | if invalid_statistics: 185 | for o in invalid_statistics: 186 | session.delete(o) 187 | session.commit() 188 | fixes_applied = True 189 | 190 | _LOGGER.debug( 191 | f"{statistic_id}: " 192 | f"deleted {len(invalid_statistics)} statistics with invalid attributes" 193 | ) 194 | 195 | if not fixes_applied: 196 | _LOGGER.debug(f"{statistic_id}: no problems found") 197 | 198 | # 199 | # Recalculate 200 | # 201 | 202 | # if not broken_point and not force_recalculate: 203 | # return 204 | 205 | # if broken_point: 206 | # _LOGGER.debug( 207 | # f"{statistic_id}: found broken statistics since" 208 | # f" {timestamp_as_local(broken_point.start_ts)}," 209 | # f" recalculating everything from there" 210 | # ) 211 | 212 | # 213 | # Recalculate all stats 214 | # 215 | 216 | # accumulated = 0 217 | # for statistic in session.execute( 218 | # sa.select(db_schema.Statistics) 219 | # .where(db_schema.Statistics.metadata_id == statistic_id) 220 | # .order_by(db_schema.Statistics.start_ts.asc) 221 | # ): 222 | # accumulated = accumulated + statistic.state 223 | 224 | # # fmt: off 225 | # statistic.mean = statistic.state if statistic_metadata_has_mean else None 226 | # statistic.sum = accumulated if statistic_metadata_has_sum else None 227 | # statistic.min = None 228 | # statistic.max = None 229 | # # fmt: on 230 | 231 | # session.add(statistic) 232 | # _LOGGER.debug( 233 | # f"{statistic_id}: " 234 | # f"update {statistic.id} {timestamp_as_local(statistic.start_ts)} " 235 | # f"value={statistic.value}\tsum={statistic.sum}" 236 | # ) 237 | # session.commit() 238 | 239 | return await recorder.get_instance(hass).async_add_executor_job(fn) 240 | -------------------------------------------------------------------------------- /custom_components/ideenergy/datacoordinator.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2022 Luis López 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software 15 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 16 | # USA. 17 | 18 | 19 | import enum 20 | import logging 21 | from datetime import datetime, timedelta, timezone 22 | from typing import Any, TypedDict 23 | 24 | import ideenergy 25 | from homeassistant.core import dt_util 26 | from homeassistant.helpers.update_coordinator import DataUpdateCoordinator 27 | 28 | from .barrier import Barrier, BarrierDeniedError 29 | from .const import ( 30 | DATA_ATTR_HISTORICAL_CONSUMPTION, 31 | DATA_ATTR_HISTORICAL_GENERATION, 32 | DATA_ATTR_HISTORICAL_POWER_DEMAND, 33 | DATA_ATTR_MEASURE_ACCUMULATED, 34 | DATA_ATTR_MEASURE_INSTANT, 35 | HISTORICAL_PERIOD_LENGHT, 36 | ) 37 | from .entity import IDeEntity 38 | 39 | 40 | class DataSetType(enum.IntFlag): 41 | NONE = 0 42 | MEASURE = 1 << 0 43 | HISTORICAL_CONSUMPTION = 1 << 1 44 | HISTORICAL_GENERATION = 1 << 2 45 | HISTORICAL_POWER_DEMAND = 1 << 3 46 | 47 | ALL = 0b1111 48 | 49 | 50 | _LOGGER = logging.getLogger(__name__) 51 | 52 | # _DEFAULT_COORDINATOR_DATA: dict[str, Any] = { 53 | # DATA_ATTR_MEASURE_ACCUMULATED: None, 54 | # DATA_ATTR_MEASURE_INSTANT: None, 55 | # DATA_ATTR_HISTORICAL_CONSUMPTION: { 56 | # "accumulated": None, 57 | # "accumulated-co2": None, 58 | # "historical": [], 59 | # }, 60 | # DATA_ATTR_HISTORICAL_GENERATION: { 61 | # "accumulated": None, 62 | # "accumulated-co2": None, 63 | # "historical": [], 64 | # }, 65 | # DATA_ATTR_HISTORICAL_POWER_DEMAND: [], 66 | # } 67 | 68 | 69 | class CoordinatorData(TypedDict): 70 | DATA_ATTR_MEASURE_ACCUMULATED: int | None 71 | DATA_ATTR_MEASURE_INSTANT: float | None 72 | DATA_ATTR_HISTORICAL_CONSUMPTION: ideenergy.HistoricalConsumption | None 73 | DATA_ATTR_HISTORICAL_GENERATION: ideenergy.HistoricalGeneration | None 74 | DATA_ATTR_HISTORICAL_POWER_DEMAND: ideenergy.HistoricalPowerDemand | None 75 | 76 | 77 | class IDeCoordinator(DataUpdateCoordinator): 78 | def __init__( 79 | self, 80 | hass, 81 | api, 82 | barriers: dict[DataSetType, Barrier], 83 | update_interval: timedelta = timedelta(seconds=30), 84 | ): 85 | name = ( 86 | f"{api.username}/{api._contract} coordinator" if api else "i-de coordinator" 87 | ) 88 | super().__init__(hass, _LOGGER, name=name, update_interval=update_interval) 89 | self.data: CoordinatorData = { # type: ignore[assignment] 90 | k: None 91 | for k in [ 92 | DATA_ATTR_MEASURE_ACCUMULATED, 93 | DATA_ATTR_MEASURE_INSTANT, 94 | DATA_ATTR_HISTORICAL_CONSUMPTION, 95 | DATA_ATTR_HISTORICAL_GENERATION, 96 | DATA_ATTR_HISTORICAL_POWER_DEMAND, 97 | ] 98 | } 99 | 100 | self.api = api 101 | self.barriers = barriers 102 | 103 | # FIXME: platforms from HomeAssistant should have types 104 | self.platforms: list[str] = [] 105 | 106 | self.sensors: list[IDeEntity] = [] 107 | 108 | async def _async_update_data(self): 109 | """Fetch data from API endpoint. 110 | 111 | This is the place to pre-process the data to lookup tables 112 | so entities can quickly look up their data. 113 | 114 | See: https://developers.home-assistant.io/docs/integration_fetching_data/ 115 | """ 116 | 117 | # Raising 'asyncio.TimeoutError' or 'aiohttp.ClientError' are already 118 | # handled by the data update coordinator. 119 | 120 | # Raising ConfigEntryAuthFailed will cancel future updates 121 | # and start a config flow with SOURCE_REAUTH (async_step_reauth) 122 | 123 | # Raise UpdateFailed is something were wrong 124 | 125 | ds = DataSetType.NONE 126 | for sensor in self.sensors: 127 | for s_ds in sensor.I_DE_DATA_SETS: 128 | ds = ds | s_ds 129 | 130 | dsstr = ds.name.replace("|", ", ") 131 | _LOGGER.debug(f"Request update for datasets: {dsstr}") 132 | 133 | updated_data = await self._async_update_data_raw(datasets=ds) 134 | 135 | data = self.data | updated_data 136 | return data 137 | 138 | async def _async_update_data_raw( 139 | self, datasets: DataSetType = DataSetType.ALL, now: datetime | None = None 140 | ) -> dict[str, Any]: 141 | now = now or dt_util.utcnow() 142 | if now.tzinfo != timezone.utc: 143 | raise ValueError("now is missing tzinfo field") 144 | 145 | requested = (x for x in DataSetType) 146 | requested = (x for x in requested if x is not DataSetType.ALL) 147 | requested = (x for x in requested if x & datasets) 148 | requested = list(requested) # type: ignore[assignment] 149 | 150 | data = {} 151 | 152 | for dataset in requested: 153 | # Barrier checks and handle exceptions 154 | try: 155 | self.barriers[dataset].check() 156 | 157 | except KeyError: 158 | _LOGGER.debug(f"update ignored for {dataset.name}: no barrier defined") 159 | continue 160 | 161 | except BarrierDeniedError as deny: 162 | _LOGGER.debug(f"update denied for {dataset.name}: {deny.reason}") 163 | continue 164 | 165 | _LOGGER.debug(f"update allowed for {dataset.name}") 166 | 167 | # API calls and handle exceptions 168 | try: 169 | if dataset is DataSetType.MEASURE: 170 | data.update(await self.get_direct_reading_data()) 171 | 172 | elif dataset is DataSetType.HISTORICAL_CONSUMPTION: 173 | data.update(await self.get_historical_consumption_data()) 174 | 175 | elif dataset is DataSetType.HISTORICAL_GENERATION: 176 | data.update(await self.get_historical_generation_data()) 177 | 178 | elif dataset is DataSetType.HISTORICAL_POWER_DEMAND: 179 | data.update(await self.get_historical_power_demand_data()) 180 | 181 | else: 182 | _LOGGER.debug( 183 | f"update ignored for {dataset.name}: not implemented yet" 184 | ) 185 | continue 186 | 187 | except UnicodeDecodeError: 188 | _LOGGER.debug( 189 | f"update error for {dataset.name}: invalid encoding. File a bug" 190 | ) 191 | continue 192 | 193 | except ideenergy.RequestFailedError as e: 194 | _LOGGER.debug( 195 | f"update error for {dataset.name}: " 196 | + f"{e.response.reason} ({e.response.status})" 197 | ) 198 | continue 199 | 200 | except ideenergy.CommandError as e: 201 | _LOGGER.debug( 202 | f"update error for {dataset.name}: command error from API ({e!r})" 203 | ) 204 | continue 205 | 206 | except Exception as e: 207 | _LOGGER.debug( 208 | f"update error for {dataset.name}: " 209 | + f"**FIXME** handle {dataset.name} raised exception: {e!r}" 210 | ) 211 | continue 212 | 213 | self.barriers[dataset].success() 214 | 215 | _LOGGER.debug(f"update successful for {dataset.name}") 216 | 217 | # delay = random.randint(DELAY_MIN_SECONDS * 10, DELAY_MAX_SECONDS * 10) / 10 218 | # _LOGGER.debug(f" → Random delay: {delay} seconds") 219 | # await asyncio.sleep(delay) 220 | 221 | return data 222 | 223 | def register_sensor(self, sensor: IDeEntity) -> None: 224 | self.sensors.append(sensor) 225 | _LOGGER.debug(f"Registered sensor '{sensor.__class__.__name__}'") 226 | 227 | def unregister_sensor(self, sensor: IDeEntity) -> None: 228 | self.sensors.remove(sensor) 229 | _LOGGER.debug(f"Unregistered sensor '{sensor.__class__.__name__}'") 230 | 231 | def update_internal_data(self, data: dict[str, Any]): 232 | self.data = self.data | data # type: ignore[assignment] 233 | 234 | async def get_direct_reading_data(self) -> dict[str, int | float]: 235 | data = await self.api.get_measure() 236 | 237 | return { 238 | DATA_ATTR_MEASURE_ACCUMULATED: data.accumulate, 239 | DATA_ATTR_MEASURE_INSTANT: data.instant, 240 | } 241 | 242 | async def get_historical_consumption_data(self) -> Any: 243 | end = datetime.today() 244 | start = end - HISTORICAL_PERIOD_LENGHT 245 | data = await self.api.get_historical_consumption(start=start, end=end) 246 | 247 | return {DATA_ATTR_HISTORICAL_CONSUMPTION: data} 248 | 249 | async def get_historical_generation_data(self) -> Any: 250 | end = datetime.today() 251 | start = end - HISTORICAL_PERIOD_LENGHT 252 | data = await self.api.get_historical_generation(start=start, end=end) 253 | 254 | return {DATA_ATTR_HISTORICAL_GENERATION: data} 255 | 256 | async def get_historical_power_demand_data(self) -> Any: 257 | data = await self.api.get_historical_power_demand() 258 | 259 | return {DATA_ATTR_HISTORICAL_POWER_DEMAND: data} 260 | -------------------------------------------------------------------------------- /custom_components/ideenergy/barrier.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2022 Luis López 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software 15 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 16 | # USA. 17 | 18 | 19 | import enum 20 | import functools 21 | import logging 22 | from abc import abstractmethod 23 | from datetime import datetime, timedelta, timezone 24 | from typing import Any 25 | 26 | from homeassistant.core import dt_util 27 | 28 | _LOGGER = logging.getLogger(__name__) 29 | 30 | 31 | ATTR_DELAY_INTERVAL = "delay_interval" 32 | ATTR_MAX_AGE = "max_age" 33 | ATTR_MAX_RETRIES = "max_retries" 34 | ATTR_UPDATE_WINDOW_INTERVAL = "update_window_interval" 35 | ATTR_COOLDOWN = "cooldown" 36 | ATTR_FORCED = "forced" 37 | ATTR_LAST_SUCCESS = "last_success" 38 | ATTR_STATE = "state" 39 | ATTR_RETRY = "retry" 40 | ATTR_ALLOWED_WINDOW_MINUTES = "allowed_window_minutes" 41 | 42 | DEFAULT_MAX_RETRIES = 3 43 | 44 | 45 | def check_tzinfo( 46 | param: str | int, 47 | default_tzinfo: timezone = timezone.utc, 48 | optional: bool = False, 49 | ): 50 | def decorator(fn): 51 | @functools.wraps(fn) 52 | def wrapper(*args, **kwargs): 53 | if isinstance(param, int): 54 | dt = args[param] 55 | elif isinstance(param, str): 56 | dt = kwargs.get(param) 57 | else: 58 | raise TypeError("Invalid argument for decorator") 59 | 60 | if dt is None: 61 | if optional: 62 | return fn(*args, **kwargs) 63 | else: 64 | raise TypeError(f"{param} is missing") 65 | 66 | if not isinstance(dt, datetime): 67 | raise TypeError(f"{param} must be a datetime object") 68 | 69 | if dt.tzinfo is None and default_tzinfo is None: 70 | raise ValueError(f"{param} lacks tzinfo") 71 | 72 | if default_tzinfo is not None: 73 | dt = dt.replace(tzinfo=default_tzinfo) 74 | 75 | if isinstance(param, int): 76 | args[param] = dt 77 | if isinstance(param, str): 78 | kwargs[param] = dt 79 | 80 | return fn(*args, **kwargs) 81 | 82 | return wrapper 83 | 84 | return decorator 85 | 86 | 87 | class Barrier: 88 | @abstractmethod 89 | def check(self, **kwargs: Any) -> None: 90 | raise NotImplementedError() 91 | 92 | @abstractmethod 93 | def success(self, **kwargs: Any) -> None: 94 | raise NotImplementedError() 95 | 96 | @abstractmethod 97 | def fail(self, **kwargs: Any) -> None: 98 | raise NotImplementedError() 99 | 100 | @abstractmethod 101 | def dump(self) -> dict[str, Any]: 102 | return {} 103 | 104 | 105 | class BarrierException(Exception): 106 | pass 107 | 108 | 109 | class BarrierDeniedError(BarrierException): 110 | def __init__(self, code: Any, reason: str): 111 | self.reason = reason 112 | self.code = code 113 | 114 | 115 | class TimeDeltaBarrier(Barrier): 116 | @check_tzinfo("last_success", optional=True) 117 | def __init__( 118 | self, 119 | delta: timedelta, 120 | last_success: datetime | None = None, 121 | ): 122 | self._delta = delta 123 | self._last_success = last_success or dt_util.utc_from_timestamp(0) 124 | 125 | @check_tzinfo("now", optional=True) 126 | def check(self, now: datetime | None = None) -> None: 127 | now = now or self.utcnow() 128 | 129 | diff = now - self._last_success 130 | if diff < self._delta: 131 | raise BarrierDeniedError( 132 | code=TimeDeltaBarrierDenyError.NO_MAX_AGE, 133 | reason=f"no max_age reached ({diff} <= {self._delta})", 134 | ) 135 | 136 | @check_tzinfo("now", optional=True) 137 | def success(self, now: datetime | None = None) -> None: 138 | now = now or self.utcnow() 139 | self._last_success = now 140 | 141 | @check_tzinfo("now", optional=True) 142 | def fail(self, now: datetime | None = None) -> None: 143 | pass 144 | 145 | def utcnow(self) -> datetime: 146 | return dt_util.utcnow() 147 | 148 | @property 149 | def delta(self) -> timedelta: 150 | return self._delta 151 | 152 | @property 153 | def last_success(self) -> datetime: 154 | return self._last_success 155 | 156 | def dump(self) -> dict[str, Any]: 157 | return {ATTR_MAX_AGE: self.delta, ATTR_LAST_SUCCESS: self.last_success} 158 | 159 | 160 | class TimeDeltaBarrierDenyError(enum.Enum): 161 | NO_MAX_AGE = enum.auto() 162 | 163 | 164 | class RetryableBarrier: 165 | def __init__(self, max_retries: int = DEFAULT_MAX_RETRIES): 166 | self._max_retries = max_retries 167 | 168 | @property 169 | def attributes(self) -> dict[str, Any]: 170 | return {ATTR_MAX_RETRIES: self._max_retries} 171 | 172 | @property 173 | def max_retries(self) -> int: 174 | return self._max_retries 175 | 176 | 177 | class TimeWindowBarrier(Barrier): 178 | def __init__( 179 | self, 180 | allowed_window_minutes: tuple[int, int], 181 | max_retries: int, 182 | max_age: timedelta, 183 | ): 184 | self._max_age = max_age 185 | self._allowed_window_minutes = allowed_window_minutes 186 | self._max_retries = max_retries 187 | 188 | zero_dt = dt_util.utc_from_timestamp(0) 189 | 190 | # state 191 | self._force_next = False 192 | self._failures = 0 193 | self._last_success = zero_dt 194 | self._cooldown = zero_dt 195 | 196 | def utcnow(self) -> datetime: 197 | return dt_util.utcnow() 198 | 199 | def dump(self) -> dict[str, Any]: 200 | ret = { 201 | # Configuration 202 | ATTR_MAX_AGE: self._max_age, 203 | ATTR_MAX_RETRIES: self._max_retries, 204 | ATTR_ALLOWED_WINDOW_MINUTES: self._allowed_window_minutes, 205 | # Internal state 206 | ATTR_COOLDOWN: self._cooldown, 207 | ATTR_FORCED: self._force_next, 208 | ATTR_LAST_SUCCESS: self._last_success, 209 | ATTR_RETRY: self._failures, 210 | } 211 | 212 | return ret 213 | 214 | @check_tzinfo("now", optional=True) 215 | def check(self, now: datetime | None = None) -> None: 216 | """ 217 | Checks (in order), important for testing 218 | - forced 219 | - cooldown 220 | - retrying 221 | - update window 222 | - no delta 223 | """ 224 | now = now or self.utcnow() 225 | 226 | update_window_is_open = ( 227 | self._allowed_window_minutes[0] 228 | <= dt_util.as_local(now).minute 229 | <= self._allowed_window_minutes[1] 230 | ) 231 | last_success_age = (now - self._last_success).total_seconds() 232 | min_age = ( 233 | self._allowed_window_minutes[1] - self._allowed_window_minutes[0] 234 | ) * 60 235 | 236 | # Check if cooldown has been reached 237 | if self._failures >= self._max_retries and now >= self._cooldown: 238 | _LOGGER.debug("cooldown barrier reached, resetting failures") 239 | self._failures = 0 240 | 241 | if self._force_next: 242 | _LOGGER.debug("forced flag is set") 243 | return 244 | 245 | if now < self._cooldown: 246 | cooldown_until = dt_util.as_local(self._cooldown) 247 | raise BarrierDeniedError( 248 | code=TimeWindowBarrierDenyError.COOLDOWN, 249 | reason=f"barrier is in cooldown state until {cooldown_until}", 250 | ) 251 | 252 | if self._failures > 0 and self._failures < self._max_retries: 253 | _LOGGER.debug("barrier is in retrying state") 254 | return 255 | 256 | if not update_window_is_open: 257 | raise BarrierDeniedError( 258 | code=TimeWindowBarrierDenyError.UPDATE_WINDOW_CLOSED, 259 | reason="update window is closed", 260 | ) 261 | 262 | if last_success_age <= min_age: 263 | reason = ( 264 | "last success is too recent " 265 | f"({last_success_age} seconds, min: {min_age} seconds)" 266 | ) 267 | raise BarrierDeniedError( 268 | code=TimeWindowBarrierDenyError.NO_DELTA, reason=reason 269 | ) 270 | 271 | def force_next(self) -> None: 272 | self._force_next = True 273 | 274 | @check_tzinfo("now", optional=True) 275 | def success(self, now: datetime | None = None) -> None: 276 | now = now or self.utcnow() 277 | 278 | self._force_next = False 279 | self._failures = 0 280 | self._last_success = now 281 | 282 | _LOGGER.debug("success registered") 283 | 284 | @check_tzinfo("now", optional=True) 285 | def fail(self, now: datetime | None = None) -> None: 286 | now = now or self.utcnow() 287 | 288 | self._failures = self._failures + 1 289 | _LOGGER.debug(f"fail registered ({self._failures}/{self._max_retries})") 290 | 291 | if self._failures >= self._max_retries: 292 | self._force_next = False 293 | self._cooldown = now + (self._max_age / 2) 294 | 295 | cooldown_until = dt_util.as_local(self._cooldown) 296 | _LOGGER.debug( 297 | f"max failures reached, setup cooldown barrier until {cooldown_until}" 298 | ) 299 | 300 | 301 | class TimeWindowBarrierDenyError(enum.Enum): 302 | UPDATE_WINDOW_CLOSED = enum.auto() 303 | COOLDOWN = enum.auto() 304 | NO_DELTA = enum.auto() 305 | 306 | 307 | class NoopBarrier(Barrier): 308 | def check(self, **kwargs) -> None: 309 | pass 310 | 311 | def success(self): 312 | pass 313 | 314 | def fail(self): 315 | pass 316 | 317 | def dump(self) -> dict[str, Any]: 318 | return {} 319 | -------------------------------------------------------------------------------- /custom_components/ideenergy/sensor.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2022 Luis López 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software 15 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 16 | # USA. 17 | 18 | 19 | # TODO 20 | # Maybe we need to mark some function as callback but I'm not sure whose. 21 | # from homeassistant.core import callback 22 | 23 | 24 | # Check sensor.SensorEntityDescription 25 | # https://github.com/home-assistant/core/blob/dev/homeassistant/components/sensor/__init__.py 26 | 27 | 28 | import itertools 29 | import logging 30 | from collections.abc import Callable 31 | from datetime import datetime, timedelta 32 | from typing import Any 33 | 34 | from homeassistant.components import recorder 35 | from homeassistant.components.recorder import statistics 36 | from homeassistant.components.recorder.models import StatisticData, StatisticMetaData 37 | from homeassistant.components.sensor import ( 38 | SensorDeviceClass, 39 | SensorEntity, 40 | SensorStateClass, 41 | ) 42 | from homeassistant.config_entries import ConfigEntry 43 | from homeassistant.const import ( 44 | STATE_UNAVAILABLE, 45 | STATE_UNKNOWN, 46 | UnitOfEnergy, 47 | UnitOfPower, 48 | ) 49 | from homeassistant.core import HomeAssistant, callback, dt_util 50 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 51 | from homeassistant.helpers.restore_state import RestoreEntity 52 | from homeassistant.helpers.typing import DiscoveryInfoType 53 | from homeassistant.util import dt as dtutil 54 | from homeassistant_historical_sensor import HistoricalSensor, HistoricalState 55 | from ideenergy.types import PeriodValue 56 | 57 | from .const import DOMAIN 58 | from .datacoordinator import ( 59 | DATA_ATTR_HISTORICAL_CONSUMPTION, 60 | DATA_ATTR_HISTORICAL_GENERATION, 61 | DATA_ATTR_HISTORICAL_POWER_DEMAND, 62 | DATA_ATTR_MEASURE_ACCUMULATED, 63 | DATA_ATTR_MEASURE_INSTANT, 64 | DataSetType, 65 | ) 66 | from .entity import IDeEntity 67 | from .fixes import async_fix_statistics 68 | 69 | PLATFORM = "sensor" 70 | 71 | MAINLAND_SPAIN_ZONEINFO = dtutil.zoneinfo.ZoneInfo("Europe/Madrid") 72 | _LOGGER = logging.getLogger(__name__) 73 | 74 | 75 | # The IDeSensor class provides: 76 | # __init__ 77 | # __repr__ 78 | # name 79 | # unique_id 80 | # device_info 81 | # entity_registry_enabled_default 82 | # The CoordinatorEntity class provides: 83 | # should_poll 84 | # async_update 85 | # async_added_to_hass 86 | # available 87 | 88 | 89 | class HistoricalSensorMixin(HistoricalSensor): 90 | @callback 91 | def _handle_coordinator_update(self) -> None: 92 | self.hass.add_job(self.async_write_ha_historical_states()) 93 | 94 | def async_update_historical(self) -> None: 95 | pass 96 | 97 | 98 | class StatisticsMixin(HistoricalSensor): 99 | @property 100 | def statistic_id(self): 101 | return self.entity_id 102 | 103 | def get_statistic_metadata(self) -> StatisticMetaData: 104 | meta = super().get_statistic_metadata() | {"has_sum": True} 105 | 106 | return meta 107 | 108 | async def async_added_to_hass(self): 109 | await super().async_added_to_hass() 110 | 111 | # 112 | # In 2.0 branch we f**ked statistiscs. 113 | # Don't set state_class attributes for historical sensors! 114 | # 115 | # FIXME: Remove in future 3.0 series. 116 | # 117 | await async_fix_statistics(self.hass, self.get_statistic_metadata()) 118 | 119 | async def async_calculate_statistic_data( 120 | self, hist_states: list[HistoricalState], *, latest: dict | None 121 | ) -> list[StatisticData]: 122 | # 123 | # Filter out invalid states 124 | # 125 | 126 | n_original_hist_states = len(hist_states) 127 | hist_states = [x for x in hist_states if x.state not in (0, None)] 128 | if len(hist_states) != n_original_hist_states: 129 | _LOGGER.warning( 130 | f"{self.statistic_id}: " 131 | + "found some weird values in historical statistics" 132 | ) 133 | 134 | # 135 | # Group historical states by hour block 136 | # 137 | 138 | def hour_block_for_hist_state(hist_state: HistoricalState) -> datetime: 139 | # XX:00:00 states belongs to previous hour block 140 | if hist_state.dt.minute == 0 and hist_state.dt.second == 0: 141 | dt = hist_state.dt - timedelta(hours=1) 142 | return dt.replace(minute=0, second=0, microsecond=0) 143 | 144 | else: 145 | return hist_state.dt.replace(minute=0, second=0, microsecond=0) 146 | 147 | # 148 | # Ignore supplied 'lastest' and fetch again from recorder 149 | # FIXME: integrate into homeassistant_historical_sensor and remove 150 | # 151 | 152 | def get_last_statistics(): 153 | ret = statistics.get_last_statistics( 154 | self.hass, 155 | 1, 156 | self.statistic_id, 157 | convert_units=True, 158 | types={"sum"}, 159 | ) 160 | 161 | # ret can be none or {} 162 | if not ret: 163 | return None 164 | 165 | try: 166 | return ret[self.statistic_id][0] 167 | 168 | except KeyError: 169 | # No stats found 170 | return None 171 | 172 | except IndexError: 173 | # What? 174 | _LOGGER.error( 175 | f"{self.statatistic_id}: " 176 | + "[bug] found last statistics key but doesn't have any value! " 177 | + f"({ret!r})" 178 | ) 179 | raise 180 | 181 | latest = await recorder.get_instance(self.hass).async_add_executor_job( 182 | get_last_statistics 183 | ) 184 | 185 | # 186 | # Get last sum sum from latest 187 | # 188 | def extract_last_sum(latest) -> float: 189 | return float(latest["sum"]) if latest else 0 190 | 191 | try: 192 | total_accumulated = extract_last_sum(latest) 193 | except (KeyError, ValueError): 194 | _LOGGER.error( 195 | f"{self.statistic_id}: [bug] statistics broken (lastest={latest!r})" 196 | ) 197 | return [] 198 | 199 | start_point_local_dt = dt_util.as_local( 200 | dt_util.utc_from_timestamp(latest.get("start", 0) if latest else 0) 201 | ) 202 | 203 | _LOGGER.debug( 204 | f"{self.statistic_id}: " 205 | + f"calculating statistics using {total_accumulated} as base accumulated " 206 | + f"(registed at {start_point_local_dt})" 207 | ) 208 | 209 | # 210 | # Calculate statistic data 211 | # 212 | 213 | ret = [] 214 | 215 | for dt, collection_it in itertools.groupby( 216 | hist_states, key=hour_block_for_hist_state 217 | ): 218 | collection = list(collection_it) 219 | 220 | # hour_mean = statistics.mean([x.state for x in collection]) 221 | hour_accumulated = sum([x.state for x in collection]) 222 | total_accumulated = total_accumulated + hour_accumulated 223 | 224 | ret.append( 225 | StatisticData( 226 | start=dt, 227 | state=hour_accumulated, 228 | # mean=hour_mean, 229 | sum=total_accumulated, 230 | ) 231 | ) 232 | 233 | return ret 234 | 235 | 236 | class AccumulatedConsumption(RestoreEntity, IDeEntity, SensorEntity): 237 | I_DE_PLATFORM = PLATFORM 238 | I_DE_ENTITY_NAME = "Accumulated Consumption" 239 | I_DE_DATA_SETS = [DataSetType.MEASURE] 240 | 241 | def __init__(self, *args, **kwargs): 242 | super().__init__(*args, **kwargs) 243 | self._attr_device_class = SensorDeviceClass.ENERGY 244 | self._attr_native_unit_of_measurement = UnitOfEnergy.KILO_WATT_HOUR 245 | 246 | # TOTAL vs TOTAL_INCREASING: 247 | # 248 | # It's recommended to use state class total without last_reset whenever 249 | # possible, state class total_increasing or total with last_reset should only be 250 | # used when state class total without last_reset does not work for the sensor. 251 | # https://developers.home-assistant.io/docs/core/entity/sensor/#how-to-choose-state_class-and-last_reset 252 | 253 | # The sensor's value never resets, e.g. a lifetime total energy consumption or 254 | # production: state_class total, last_reset not set or set to None 255 | 256 | self._attr_state_class = SensorStateClass.TOTAL 257 | 258 | @property 259 | def state(self): 260 | return self.coordinator.data[DATA_ATTR_MEASURE_ACCUMULATED] 261 | 262 | @callback 263 | def _handle_coordinator_update(self) -> None: 264 | self.async_write_ha_state() 265 | 266 | async def async_added_to_hass(self) -> None: 267 | await super().async_added_to_hass() 268 | 269 | saved_data = await async_get_last_state_safe(self, float) 270 | self.coordinator.update_internal_data( 271 | {DATA_ATTR_MEASURE_ACCUMULATED: saved_data} 272 | ) 273 | 274 | 275 | class InstantPowerDemand(RestoreEntity, IDeEntity, SensorEntity): 276 | I_DE_PLATFORM = PLATFORM 277 | I_DE_ENTITY_NAME = "Instant Power Demand" 278 | I_DE_DATA_SETS = [DataSetType.MEASURE] 279 | 280 | def __init__(self, *args, **kwargs): 281 | super().__init__(*args, **kwargs) 282 | self._attr_device_class = SensorDeviceClass.POWER 283 | self._attr_state_class = SensorStateClass.MEASUREMENT 284 | self._attr_native_unit_of_measurement = UnitOfPower.WATT 285 | 286 | @property 287 | def state(self): 288 | return self.coordinator.data[DATA_ATTR_MEASURE_INSTANT] 289 | 290 | @callback 291 | def _handle_coordinator_update(self) -> None: 292 | self.async_write_ha_state() 293 | 294 | async def async_added_to_hass(self) -> None: 295 | await super().async_added_to_hass() 296 | 297 | saved_data = await async_get_last_state_safe(self, float) 298 | self.coordinator.update_internal_data({DATA_ATTR_MEASURE_INSTANT: saved_data}) 299 | 300 | 301 | class HistoricalConsumption( 302 | StatisticsMixin, HistoricalSensorMixin, IDeEntity, SensorEntity 303 | ): 304 | I_DE_PLATFORM = PLATFORM 305 | I_DE_ENTITY_NAME = "Historical Consumption" 306 | I_DE_DATA_SETS = [DataSetType.HISTORICAL_CONSUMPTION] 307 | 308 | def __init__(self, *args, **kwargs): 309 | super().__init__(*args, **kwargs) 310 | 311 | self._attr_device_class = SensorDeviceClass.ENERGY 312 | self._attr_native_unit_of_measurement = UnitOfEnergy.KILO_WATT_HOUR 313 | self._attr_entity_registry_enabled_default = False 314 | self._attr_state = None 315 | 316 | # The sensor's state is reset with every state update, for example a sensor 317 | # updating every minute with the energy consumption during the past minute: 318 | # state class total, last_reset updated every state change. 319 | # 320 | # (*) last_reset is set in states by historical_states_from_historical_api_data 321 | # (*) set only in internal statistics model 322 | # 323 | # DON'T set for HistoricalSensors, you will mess your statistics. 324 | # Keep as reference. 325 | # 326 | # self._attr_state_class = SensorStateClass.TOTAL 327 | 328 | @property 329 | def historical_states(self): 330 | if (data := self.coordinator.data[DATA_ATTR_HISTORICAL_CONSUMPTION]) is None: 331 | # FIXME: This should be None, fix ha-historical-sensor 332 | return [] 333 | 334 | ret = historical_states_from_period_values(data.periods) 335 | return ret 336 | 337 | 338 | class HistoricalGeneration( 339 | StatisticsMixin, HistoricalSensorMixin, IDeEntity, SensorEntity 340 | ): 341 | I_DE_PLATFORM = PLATFORM 342 | I_DE_ENTITY_NAME = "Historical Generation" 343 | I_DE_DATA_SETS = [DataSetType.HISTORICAL_GENERATION] 344 | 345 | def __init__(self, *args, **kwargs): 346 | super().__init__(*args, **kwargs) 347 | self._attr_device_class = SensorDeviceClass.ENERGY 348 | self._attr_native_unit_of_measurement = UnitOfEnergy.KILO_WATT_HOUR 349 | self._attr_entity_registry_enabled_default = False 350 | self._attr_state = None 351 | 352 | # The sensor's state is reset with every state update, for example a sensor 353 | # updating every minute with the energy consumption during the past minute: 354 | # state class total, last_reset updated every state change. 355 | # 356 | # (*) last_reset is set in states by historical_states_from_historical_api_data 357 | # (*) set only in internal statistics model 358 | # 359 | # DON'T set for HistoricalSensors, you will mess your statistics. 360 | # 361 | # Keep as reference. 362 | # 363 | # self._attr_state_class = SensorStateClass.TOTAL 364 | 365 | @property 366 | def historical_states(self): 367 | if (data := self.coordinator.data[DATA_ATTR_HISTORICAL_GENERATION]) is None: 368 | # FIXME: This should be None, fix ha-historical-sensor 369 | return [] 370 | 371 | ret = historical_states_from_period_values(data.periods) 372 | return ret 373 | 374 | 375 | class HistoricalPowerDemand(HistoricalSensorMixin, IDeEntity, SensorEntity): 376 | I_DE_PLATFORM = PLATFORM 377 | I_DE_ENTITY_NAME = "Historical Power Demand" 378 | I_DE_DATA_SETS = [DataSetType.HISTORICAL_POWER_DEMAND] 379 | 380 | def __init__(self, *args, **kwargs): 381 | super().__init__(*args, **kwargs) 382 | self._attr_device_class = SensorDeviceClass.POWER 383 | self._attr_native_unit_of_measurement = UnitOfPower.WATT 384 | self._attr_entity_registry_enabled_default = False 385 | self._attr_state = None 386 | 387 | @property 388 | def historical_states(self): 389 | if (data := self.coordinator.data[DATA_ATTR_HISTORICAL_POWER_DEMAND]) is None: 390 | # FIXME: This should be None, fix ha-historical-sensor 391 | return [] 392 | 393 | def demand_at_instant_as_historical_state(item): 394 | return HistoricalState( 395 | state=item.value / 1000, 396 | dt=item.dt.replace(tzinfo=MAINLAND_SPAIN_ZONEINFO), 397 | ) 398 | 399 | ret = [demand_at_instant_as_historical_state(x) for x in data.demands] 400 | return ret 401 | 402 | 403 | async def async_setup_entry( 404 | hass: HomeAssistant, 405 | config_entry: ConfigEntry, 406 | async_add_devices: AddEntitiesCallback, 407 | discovery_info: DiscoveryInfoType | None = None, # noqa DiscoveryInfoType | None 408 | ): 409 | coordinator, device_info = hass.data[DOMAIN][config_entry.entry_id] 410 | 411 | sensors = [ 412 | AccumulatedConsumption( 413 | config_entry=config_entry, device_info=device_info, coordinator=coordinator 414 | ), 415 | InstantPowerDemand( 416 | config_entry=config_entry, device_info=device_info, coordinator=coordinator 417 | ), 418 | HistoricalConsumption( 419 | config_entry=config_entry, device_info=device_info, coordinator=coordinator 420 | ), 421 | HistoricalGeneration( 422 | config_entry=config_entry, device_info=device_info, coordinator=coordinator 423 | ), 424 | HistoricalPowerDemand( 425 | config_entry=config_entry, device_info=device_info, coordinator=coordinator 426 | ), 427 | ] 428 | async_add_devices(sensors) 429 | 430 | 431 | def historical_states_from_historical_api_data( 432 | data: list[dict] | None = None, 433 | ) -> list[HistoricalState]: 434 | def _convert_item(item): 435 | # FIXME: What about canary islands? 436 | dt = item["end"].replace(tzinfo=MAINLAND_SPAIN_ZONEINFO) 437 | last_reset = item["start"].replace(tzinfo=MAINLAND_SPAIN_ZONEINFO) 438 | 439 | return HistoricalState( 440 | state=item["value"] / 1000, 441 | dt=dt, 442 | attributes={"last_reset": last_reset}, 443 | ) 444 | 445 | return [_convert_item(item) for item in data or []] 446 | 447 | 448 | def historical_states_from_period_values( 449 | period_values: list[PeriodValue], 450 | ) -> list[HistoricalState]: 451 | def fn(): 452 | for item in period_values: 453 | # FIXME: What about canary islands? 454 | dt = item.end.replace(tzinfo=MAINLAND_SPAIN_ZONEINFO) 455 | last_reset = item.start.replace(tzinfo=MAINLAND_SPAIN_ZONEINFO) 456 | 457 | yield HistoricalState( 458 | state=item.value / 1000, 459 | dt=dt, 460 | attributes={"last_reset": last_reset}, 461 | ) 462 | 463 | return list(fn()) 464 | 465 | 466 | async def async_get_last_state_safe( 467 | entity: RestoreEntity, convert_fn: Callable[[Any], Any] 468 | ) -> Any: 469 | # Try to load previous state using RestoreEntity 470 | # 471 | # self.async_get_last_state().last_update is tricky and can't be trusted in our 472 | # scenario. last_updated can be the last time HA exited because state is saved 473 | # at exit with last_updated=exit_time, not last_updated=sensor_last_update 474 | # 475 | # It's easier to just load the value and schedule an update with 476 | # schedule_update_ha_state() (which is meant for push sensors but...) 477 | 478 | state = await entity.async_get_last_state() 479 | if state is None: 480 | _LOGGER.debug(f"{entity.entity_id}: restore state failed (no state)") 481 | return None 482 | 483 | if state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]: 484 | _LOGGER.debug(f"{entity.entity_id}: restore state failed ({state.state})") 485 | return None 486 | 487 | try: 488 | return convert_fn(state.state) 489 | 490 | except (TypeError, ValueError): 491 | sttype = type(state.state) 492 | _LOGGER.debug( 493 | f"{entity.entity_id}: restore state failed " 494 | + f"(incompatible. type='{sttype}', value='{state.state!r}')" 495 | ) 496 | return None 497 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------