├── .devcontainer.json
├── .gitattributes
├── .github
├── ISSUE_TEMPLATE
│ ├── bug.yml
│ ├── config.yml
│ └── enhancement.yml
├── dependabot.yml
├── release-drafter.yml
└── workflows
│ ├── lint.yml
│ ├── release-drafter.yml
│ ├── release.yml
│ └── validate.yml
├── .gitignore
├── .ruff.toml
├── .vscode
├── launch.json
├── settings.json
└── tasks.json
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── config
└── configuration.yaml
├── custom_components
└── e3dc_rscp
│ ├── __init__.py
│ ├── binary_sensor.py
│ ├── button.py
│ ├── config_flow.py
│ ├── const.py
│ ├── coordinator.py
│ ├── diagnostics.py
│ ├── e3dc_proxy.py
│ ├── manifest.json
│ ├── number.py
│ ├── sensor.py
│ ├── services.py
│ ├── services.yaml
│ ├── strings.json
│ ├── switch.py
│ └── translations
│ └── en.json
├── hacs.json
├── requirements.txt
└── scripts
├── develop
├── lint
└── setup
/.devcontainer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "torbennehmer/hacs-e3dc",
3 | "image": "mcr.microsoft.com/devcontainers/python:3.13",
4 | "postCreateCommand": "scripts/setup",
5 | "forwardPorts": [
6 | 8124
7 | ],
8 | "portsAttributes": {
9 | "8124": {
10 | "label": "Home Assistant",
11 | "onAutoForward": "notify"
12 | }
13 | },
14 | "customizations": {
15 | "vscode": {
16 | "extensions": [
17 | "DavidAnson.vscode-markdownlint",
18 | "github.vscode-pull-request-github",
19 | "ms-python.black-formatter",
20 | "ms-python.python",
21 | "ms-python.vscode-pylance",
22 | "ryanluker.vscode-coverage-gutters",
23 | "stkb.rewrap",
24 | "visualstudioexptteam.vscodeintellicode",
25 | "yzhang.markdown-all-in-one"
26 | ],
27 | "settings": {
28 | "editor.formatOnPaste": false,
29 | "editor.formatOnSave": true,
30 | "editor.formatOnType": true,
31 | "editor.tabSize": 4,
32 | "files.eol": "\n",
33 | "files.trimTrailingWhitespace": true,
34 | "markdown.extension.toc.levels": "2..6",
35 | "python.analysis.autoSearchPaths": false,
36 | "python.editor.codeActionsOnSave": {
37 | "source.organizeImports": true
38 | },
39 | "python.editor.defaultFormatter": "ms-python.black-formatter",
40 | "python.editor.formatOnSave": true,
41 | "python.formatting.blackPath": "/usr/local/py-utils/bin/black",
42 | "python.formatting.provider": "black",
43 | "python.pythonPath": "/usr/bin/python3",
44 | "terminal.integrated.defaultProfile.linux": "zsh",
45 | "terminal.integrated.profiles.linux": {
46 | "zsh": {
47 | "path": "/usr/bin/zsh"
48 | }
49 | },
50 | "yaml.customTags": [
51 | "!input scalar",
52 | "!secret scalar",
53 | "!include_dir_named scalar",
54 | "!include_dir_list scalar",
55 | "!include_dir_merge_list scalar",
56 | "!include_dir_merge_named scalar"
57 | ]
58 | }
59 | }
60 | },
61 | "remoteUser": "vscode",
62 | "features": {
63 | "ghcr.io/devcontainers/features/rust:1": {}
64 | }
65 | }
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto eol=lf
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug.yml:
--------------------------------------------------------------------------------
1 | ---
2 | name: "Bug report"
3 | description: "Report a bug with the integration"
4 | labels: "bug"
5 | body:
6 | - type: markdown
7 | attributes:
8 | value: Before you open a new issue, search through the existing issues to see if others have had the same problem.
9 | - type: textarea
10 | attributes:
11 | label: "System Health details"
12 | description: "Paste the data from the System Health card in Home Assistant (https://www.home-assistant.io//more-info/system-health#github-issues)"
13 | validations:
14 | required: true
15 | - type: checkboxes
16 | attributes:
17 | label: Checklist
18 | options:
19 | - label: I have enabled debug logging for my installation.
20 | required: true
21 | - label: I have filled out the issue template to the best of my ability.
22 | required: true
23 | - label: This issue only contains 1 issue (if you have multiple issues, open one issue for each issue).
24 | required: true
25 | - label: This issue is not a duplicate issue of currently [previous issues](https://github.com/torbennehmer/hacs-e3dc/issues?q=is%3Aissue+label%3A%22Bug%22+)..
26 | required: true
27 | - type: textarea
28 | attributes:
29 | label: "Describe the issue"
30 | description: "A clear and concise description of what the issue is."
31 | validations:
32 | required: true
33 | - type: textarea
34 | attributes:
35 | label: Reproduction steps
36 | description: "Without steps to reproduce, it will be hard to fix, it is very important that you fill out this part, issues without it will be closed"
37 | value: |
38 | 1.
39 | 2.
40 | 3.
41 | ...
42 | validations:
43 | required: true
44 | - type: textarea
45 | attributes:
46 | label: "Debug logs"
47 | description: "To enable debug logs check this https://www.home-assistant.io/integrations/logger/, this **needs** to include _everything_ from startup of Home Assistant to the point where you encounter the issue."
48 | render: text
49 | validations:
50 | required: true
51 | - type: textarea
52 | attributes:
53 | label: "Diagnostics dump"
54 | description: "Drag the diagnostics dump file here - please check for things you might want to redact before posting, see also https://www.home-assistant.io/integrations/diagnostics/ for info"
55 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/enhancement.yml:
--------------------------------------------------------------------------------
1 | ---
2 | name: "enhancement"
3 | description: "Suggest an idea for this project"
4 | labels: "enhancement"
5 | body:
6 | - type: markdown
7 | attributes:
8 | value: Before you open a new feature request, search through the existing feature requests to see if others have had the same idea.
9 | - type: checkboxes
10 | attributes:
11 | label: Checklist
12 | options:
13 | - label: I have filled out the template to the best of my ability.
14 | required: true
15 | - label: This only contains 1 feature request (if you have multiple feature requests, open one feature request for each feature request).
16 | required: true
17 | - label: This issue is not a duplicate feature request of [previous feature requests](https://github.com/torbennehmer/hacs-e3dc/issues?q=is%3Aissue+label%3A%22Feature+Request%22+).
18 | required: true
19 |
20 | - type: textarea
21 | attributes:
22 | label: "Is your feature request related to a problem? Please describe."
23 | description: "A clear and concise description of what the problem is."
24 | placeholder: "I'm always frustrated when [...]"
25 | validations:
26 | required: true
27 |
28 | - type: textarea
29 | attributes:
30 | label: "Describe the solution you'd like"
31 | description: "A clear and concise description of what you want to happen."
32 | validations:
33 | required: true
34 |
35 | - type: textarea
36 | attributes:
37 | label: "Describe alternatives you've considered"
38 | description: "A clear and concise description of any alternative solutions or features you've considered."
39 | validations:
40 | required: true
41 |
42 | - type: textarea
43 | attributes:
44 | label: "Additional context"
45 | description: "Add any other context or screenshots about the feature request here."
46 | validations:
47 | required: false
48 |
49 | - type: textarea
50 | attributes:
51 | label: "Diagnostics dump"
52 | description: "Drag the diagnostics dump file here - please check for things you might want to redact before posting, see also https://www.home-assistant.io/integrations/diagnostics/ for info"
53 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
2 | version: 2
3 | updates:
4 | - package-ecosystem: "github-actions"
5 | directory: "/"
6 | schedule:
7 | interval: "monthly"
8 | labels:
9 | - "dependencies"
10 | assignees:
11 | - "torbennehmer"
12 |
13 | - package-ecosystem: "pip"
14 | directory: "/"
15 | schedule:
16 | interval: "monthly"
17 | labels:
18 | - "dependencies"
19 | assignees:
20 | - "torbennehmer"
21 | ignore:
22 | # Dependabot should not update Home Assistant as that should match the homeassistant key in hacs.json
23 | - dependency-name: "homeassistant"
--------------------------------------------------------------------------------
/.github/release-drafter.yml:
--------------------------------------------------------------------------------
1 | # https://github.com/release-drafter/release-drafter
2 |
3 | categories:
4 | - title: ":boom: Breaking Changes"
5 | label: "breaking"
6 |
7 | - title: ":fire: Removals and Deprecations"
8 | label: "removal"
9 |
10 | - title: ":rocket: Features"
11 | label: "enhancement"
12 |
13 | - title: ":beetle: Fixes"
14 | label: "bug"
15 |
16 | - title: ":racehorse: Performance"
17 | label: "performance"
18 |
19 | - title: ":hammer: Refactoring"
20 | label: "refactoring"
21 |
22 | - title: ":package: Build Process"
23 | labels:
24 | - "dependencies"
25 | - "build"
26 | - "ci"
27 |
28 | - title: "Miscellaneous changes"
29 | labels:
30 | - "documentation"
31 | - "testing"
32 |
33 | template: |
34 | ## Changes
35 |
36 | $CHANGES
37 |
--------------------------------------------------------------------------------
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: "Lint"
2 |
3 | on:
4 | push:
5 | branches:
6 | - "main"
7 | pull_request:
8 | branches:
9 | - "main"
10 |
11 | jobs:
12 | ruff:
13 | name: "Ruff"
14 | runs-on: "ubuntu-latest"
15 | steps:
16 | - name: "Checkout the repository"
17 | uses: "actions/checkout@v4.2.2"
18 |
19 | - name: "Set up Python"
20 | uses: actions/setup-python@v5.3.0
21 | with:
22 | python-version: "3.12"
23 | cache: "pip"
24 |
25 | - name: "Install requirements"
26 | run: python3 -m pip install -r requirements.txt
27 |
28 | - name: "Run"
29 | run: python3 -m ruff check .
30 |
--------------------------------------------------------------------------------
/.github/workflows/release-drafter.yml:
--------------------------------------------------------------------------------
1 | name: Draft a release note
2 | on:
3 | workflow_dispatch:
4 | push:
5 | branches:
6 | - main
7 | # pull_request event is required only for autolabeler
8 | pull_request:
9 | types: [opened, reopened, synchronize]
10 | # pull_request_target event is required for autolabeler to support PRs from forks
11 | pull_request_target:
12 | types: [opened, reopened, synchronize]
13 |
14 | permissions:
15 | contents: read
16 |
17 | jobs:
18 | draft_release:
19 | name: Release Drafter
20 | runs-on: ubuntu-latest
21 |
22 | permissions:
23 | # write permission is required to create a github release
24 | contents: write
25 | # write permission is required for autolabeler
26 | # otherwise, read permission is required at least
27 | pull-requests: write
28 |
29 | steps:
30 | - name: Run release-drafter
31 | uses: release-drafter/release-drafter@v6.0.0
32 | env:
33 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
34 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: "Release"
2 |
3 | on:
4 | release:
5 | types:
6 | - "published"
7 |
8 | permissions: {}
9 |
10 | jobs:
11 | release:
12 | name: "Release"
13 | runs-on: "ubuntu-latest"
14 | permissions:
15 | contents: write
16 | steps:
17 | - name: "Checkout the repository"
18 | uses: "actions/checkout@v4.2.2"
19 |
20 | - name: "Adjust version number"
21 | shell: "bash"
22 | run: |
23 | yq -i -o json '.version="${{ github.event.release.tag_name }}"' \
24 | "${{ github.workspace }}/custom_components/e3dc_rscp/manifest.json"
25 |
26 | - name: "ZIP the integration directory"
27 | shell: "bash"
28 | run: |
29 | cd "${{ github.workspace }}/custom_components/e3dc_rscp"
30 | zip hacs-e3dc_rscp.zip -r ./
31 |
32 | - name: "Upload the ZIP file to the release"
33 | uses: softprops/action-gh-release@v2.2.0
34 | with:
35 | files: ${{ github.workspace }}/custom_components/e3dc_rscp/hacs-e3dc_rscp.zip
36 |
--------------------------------------------------------------------------------
/.github/workflows/validate.yml:
--------------------------------------------------------------------------------
1 | name: "Validate"
2 |
3 | on:
4 | workflow_dispatch:
5 | schedule:
6 | - cron: "0 0 * * *"
7 | push:
8 | branches:
9 | - "main"
10 | pull_request:
11 | branches:
12 | - "main"
13 |
14 | jobs:
15 | hassfest: # https://developers.home-assistant.io/blog/2020/04/16/hassfest
16 | name: "Hassfest Validation"
17 | runs-on: "ubuntu-latest"
18 | steps:
19 | - name: "Checkout the repository"
20 | uses: "actions/checkout@v4.2.2"
21 |
22 | - name: "Run hassfest validation"
23 | uses: "home-assistant/actions/hassfest@master"
24 |
25 | hacs: # https://github.com/hacs/action
26 | name: "HACS Validation"
27 | runs-on: "ubuntu-latest"
28 | steps:
29 | - name: "Checkout the repository"
30 | uses: "actions/checkout@v4.2.2"
31 |
32 | - name: "Run HACS validation"
33 | uses: "hacs/action@main"
34 | with:
35 | category: "integration"
36 | # Remove this 'ignore' key when you have added brand images for your integration to https://github.com/home-assistant/brands
37 | ignore: "brands"
38 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
162 | # Home Assistant configuration
163 | config/*
164 | !config/configuration.yaml
--------------------------------------------------------------------------------
/.ruff.toml:
--------------------------------------------------------------------------------
1 | # The contents of this file is based on https://github.com/home-assistant/core/blob/dev/pyproject.toml
2 |
3 | target-version = "py311"
4 |
5 | select = [
6 | "B007", # Loop control variable {name} not used within loop body
7 | "B014", # Exception handler with duplicate exception
8 | "C", # complexity
9 | "D", # docstrings
10 | "E", # pycodestyle
11 | "F", # pyflakes/autoflake
12 | "ICN001", # import concentions; {name} should be imported as {asname}
13 | "PGH004", # Use specific rule codes when using noqa
14 | "PLC0414", # Useless import alias. Import alias does not rename original package.
15 | "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
16 | "SIM117", # Merge with-statements that use the same scope
17 | "SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys()
18 | "SIM201", # Use {left} != {right} instead of not {left} == {right}
19 | "SIM212", # Use {a} if {a} else {b} instead of {b} if not {a} else {a}
20 | "SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'.
21 | "SIM401", # Use get from dict with default instead of an if block
22 | "T20", # flake8-print
23 | "TRY004", # Prefer TypeError exception for invalid type
24 | "RUF006", # Store a reference to the return value of asyncio.create_task
25 | "UP", # pyupgrade
26 | "W", # pycodestyle
27 | ]
28 |
29 | ignore = [
30 | "D202", # No blank lines allowed after function docstring
31 | "D203", # 1 blank line required before class docstring
32 | "D213", # Multi-line docstring summary should start at the second line
33 | "D404", # First word of the docstring should not be This
34 | "D406", # Section name should end with a newline
35 | "D407", # Section name underlining
36 | "D411", # Missing blank line before section
37 | "E501", # line too long
38 | "E731", # do not assign a lambda expression, use a def
39 | "UP006", # replaces keep-runtime-typing = true
40 | "UP007", # replaces keep-runtime-typing = true
41 | ]
42 |
43 | [flake8-pytest-style]
44 | fixture-parentheses = false
45 |
46 | [mccabe]
47 | max-complexity = 25
48 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": "Home Assistant",
9 | "type": "python",
10 | "request": "launch",
11 | "module": "homeassistant",
12 | "justMyCode": false,
13 | "args": [
14 | "--debug",
15 | "-c",
16 | "config"
17 | ]
18 | },
19 | {
20 | "name": "Home Assistant (skip pip)",
21 | "type": "python",
22 | "request": "launch",
23 | "module": "homeassistant",
24 | "justMyCode": false,
25 | "args": [
26 | "--debug",
27 | "-c",
28 | "config",
29 | "--skip-pip"
30 | ]
31 | },
32 | {
33 | // For this to work against HA Docker, link the following directories (be aware, use the right version)
34 | // /usr/src/homeassistant/homeassistant -> /home/vscode/.local/lib/python3.11/site-packages/homeassistant
35 | // /config/custom_components -> /workspaces/hacs-e3dc/custom_components/
36 | "name": "Python: Attach to Atlantis",
37 | "type": "python",
38 | "request": "attach",
39 | "connect": {
40 | "host": "10.128.20.10",
41 | "port": 5678
42 | }
43 | }
44 | ]
45 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | // Please keep this file in sync with settings in .devcontainer.json
3 | "[python]": {
4 | "editor.defaultFormatter": "ms-python.black-formatter"
5 | },
6 | "python.formatting.provider": "black",
7 | "files.associations": {
8 | "*.yaml": "home-assistant"
9 | }
10 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "Run Home Assistant on port 8124",
6 | "type": "shell",
7 | "command": "scripts/develop",
8 | "problemMatcher": []
9 | }
10 | ]
11 | }
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contribution guidelines
2 |
3 | Contributing to this project should be as easy and transparent as possible,
4 | whether it's:
5 |
6 | - Reporting a bug
7 | - Discussing the current state of the code
8 | - Submitting a fix
9 | - Proposing new features
10 |
11 | ## Github is used for everything
12 |
13 | Github is used to host code, to track issues and feature requests, as well as
14 | accept pull requests.
15 |
16 | Pull requests are the best way to propose changes to the codebase.
17 |
18 | 1. Fork the repo and create your branch from `main`.
19 | 2. If you've changed something, update the documentation.
20 | 3. Make sure your code lints (using `scripts/lint`).
21 | 4. Test you contribution.
22 | 5. Issue that pull request!
23 |
24 | ## Any contributions you make will be under the GPL v3 license
25 |
26 | In short, when you submit code changes, your submissions are understood to be
27 | under the same [GPL v3 license](license) that covers the project. Feel free to
28 | contact the maintainers if that's a concern.
29 |
30 | ## Report bugs using Github's [issues](../../issues)
31 |
32 | GitHub issues are used to track public bugs. Report a bug by [opening a new
33 | issue](../../issues/new/choose); it's that easy!
34 |
35 | ## Write bug reports with detail, background, and sample code
36 |
37 | **Great Bug Reports** tend to have:
38 |
39 | - A quick summary and/or background
40 | - Steps to reproduce
41 | - Be specific!
42 | - Give sample code if you can.
43 | - What you expected would happen
44 | - What actually happens
45 | - Notes (possibly including why you think this might be happening, or stuff you
46 | tried that didn't work)
47 |
48 | People *love* thorough bug reports. I'm not even kidding.
49 |
50 | ## Use a Consistent Coding Style
51 |
52 | Use [black](https://github.com/ambv/black) to make sure the code follows the
53 | style.
54 |
55 | ## Test your code modification
56 |
57 | This custom component is based on [integration_blueprint
58 | template](https://github.com/ludeeus/integration_blueprint).
59 |
60 | It comes with development environment in a container, easy to launch if you use
61 | Visual Studio Code. With this container you will have a stand alone Home
62 | Assistant instance running and already configured with the included
63 | [`configuration.yaml`](./config/configuration.yaml) file.
64 |
65 | Be aware, that the devcontainer will publish to port 8124 to avoid clashes with
66 | other HA environments.
67 |
68 | ## License
69 |
70 | By contributing, you agree that your contributions will be licensed under its
71 | [GPL v3 license](license).
72 |
73 | ***
74 |
75 | [license]: https://github.com/torbennehmer/hacs-e3dc/blob/main/LICENSE
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Homeassistant E3DC Integration - Git Version
2 |
3 | [![hacs][hacs-shield]][hacs]
4 | [![GitHub Release][releases-shield]][releases]
5 | [![GitHub Prerelease][prereleases-shield]][releases]
6 |
7 | ![Project Maintenance][maintainer]
8 | [![GitHub Activity][commits-shield]][commits]
9 | [![License][license-shield]](LICENSE)
10 |
11 |
12 |
13 | [![Community Forum][forum-shield]][forum]
14 |
15 | This integration will interface with the E3DC Storage systems supprting the RCSP
16 | protocol. It is based on [python-e3dc](https://github.com/fsantini/python-e3dc).
17 | This repository delivers the latest features via HACS. You can use it for
18 | testing until I can get the integration accepted to HA core (no timeline for
19 | that, sorry).
20 |
21 | If you encounter problems, please file an issue at the integrations issue
22 | tracker. If possible, add a diagnostics dump always. This is important also for
23 | enhancements if they target new data or information to be retrieved from the
24 | unit to see what it has to offer. Always check that dump if you want to further
25 | redact information in it. The MACs and the units serial number are redacted
26 | already, but check for yourself! If you find information in the dump that you
27 | consider private, please file a bug request so that I can update the anonymizing
28 | code.
29 |
30 | - [Disclaimer](#disclaimer)
31 | - [Installation](#installation)
32 | - [HACS Installation](#hacs-installation)
33 | - [Manual Installation](#manual-installation)
34 | - [Configuration](#configuration)
35 | - [RSCP configuration](#rscp-configuration)
36 | - [Probable causes of connection problems](#probable-causes-of-connection-problems)
37 | - [Password limitations](#password-limitations)
38 | - [Network restriction](#network-restriction)
39 | - [Unsupported features configuration schemes](#unsupported-features-configuration-schemes)
40 | - [Actions](#actions)
41 | - [Set power limits](#set-power-limits)
42 | - [Clear current power limits](#clear-current-power-limits)
43 | - [Initate manual battery charging](#initate-manual-battery-charging)
44 | - [Set maximum wallbox charging current](#set-maximum-wallbox-charging-current)
45 | - [Upstream source](#upstream-source)
46 |
47 | ## Disclaimer
48 |
49 | This integration is provided without any warranty or support by E3DC
50 | (unfortunately). I do not take responsibility for any problems it may cause in
51 | all cases. Use it at your own risk.
52 |
53 | ## Installation
54 |
55 | The recommend way to install this extension is using HACS. If you want more
56 | control, use the manual installation method.
57 |
58 | ### HACS Installation
59 |
60 | 1. Go to *HACS -> Integrations*
61 | 1. Click the Triple-Dot menu on the top right and select *Custom Repositories*
62 | 1. Set `https://github.com/torbennehmer/hacs-e3dc.git` as repository name for
63 | the category *Integrations*
64 | 1. Open the repository (it will be displayed by default), select *Download* and
65 | confirm it
66 | 1. Restart Home Assistant
67 | 1. In the HA UI go to *Configuration -> Integrations* click "+" and search for
68 | "E3DC Remote Storage Control Protocol (Git)"
69 |
70 | ### Manual Installation
71 |
72 | 1. Using the tool of choice open the directory (folder) for your HA
73 | configuration (where you find `configuration.yaml`).
74 | 1. If you do not have a `custom_components` directory (folder) there, you need
75 | to create it.
76 | 1. In the `custom_components` directory (folder) create a new folder called
77 | `e3dc_rscp`.
78 | 1. Download *all* the files from the `custom_components/e3dc_rscp/` directory
79 | (folder) in this repository.
80 | 1. Place the files you downloaded in the new directory (folder) you created.
81 | 1. Restart Home Assistant
82 | 1. In the HA UI go to *Configuration -> Integrations* click "+" and search for
83 | "E3DC Remote Storage Control Protocol (Git)"
84 |
85 | ## Configuration
86 |
87 | Once you add the integration, you'll be asked to authenticate yourself for a
88 | local connection to your E3DC.
89 |
90 | - **Username:** Your E3DC portal user name
91 | - **Password:** Your E3DC portal password
92 | - **Hostname:** The Hostname or IP address of the E3/DC system
93 | - **RSCP Password:** This is the encryption key used in RSCP communications. You
94 | have to set on the device under *Main Page -> Personalize -> User profile ->
95 | RSCP password.*
96 |
97 | ### RSCP configuration
98 |
99 | Right now, the integration will use the default configuration provided by
100 | pye3dc. Additional PVIs, powermeters, wallboxes or batteries not covered yet by an option
101 | flow. You can find details about these options at the [pye3dc
102 | readme](https://github.com/fsantini/python-e3dc#configuration). I will plan to
103 | add options to configure this in the long run. Please file an issue if you need
104 | changes here, as I will need ral life examples to get these things running.
105 |
106 | ### Probable causes of connection problems
107 |
108 | Based from my current experience, there may be a various problems when
109 | connecting to an E3DC unit. Please be aware that it is not an exthaustive list,
110 | also different E3DC types may behave slightly differently. I'll try to collect
111 | the information I can deduce here and - if possible - forward them to the pye3dc
112 | base lib where sensible.
113 |
114 | #### Password limitations
115 |
116 | According to bug reports, the usable characters of an RSCP key seem to be
117 | limited. A user had problems when using a dot as a key element. If you get
118 | strange authentication problems, try to start with a simple alphanumeric ASCII
119 | based RSCP key, this is known to work in all cases.
120 |
121 | #### Network restriction
122 |
123 | E3DC units seem to listen only for connections on the same TCP/IP subnet. Access
124 | from the outside must be proxied by a host on the local net. Connections from
125 | other IP addresses will be blocked, even if, for example, you connect through an
126 | VPN coming from other private networks.
127 |
128 | A temporary solution, e.g. for testing, could be a simple SSH forward. However,
129 | if you need a permanent solution, I would recommend using a [Traefik Reverse
130 | Proxy](https://traefik.io/traefik/) on the E3DC net to act as an intermediate.
131 | It will allow for a more detailed security setup.
132 |
133 | A sample setup for Traefik might look like this (without any warranty), I use
134 | this for my VPN setup:
135 |
136 | ```yaml
137 | # Static config
138 | entryPoints:
139 | e3dc.rscp:
140 | # External Port reachable through Traefik
141 | address: "10.11.12.10:5033/tcp"
142 |
143 | # Dynamic config
144 | tcp:
145 | routers:
146 | e3dc.rscp:
147 | entrypoints:
148 | - e3dc.rscp
149 | service: e3dc.rscp
150 | rule: "ClientIP(`10.0.0.0/8`)"
151 | services:
152 | e3dc.rscp:
153 | loadbalancer:
154 | servers:
155 | # E3DC Target IP
156 | - address: "10.11.12.15:5033"
157 | ```
158 |
159 | ### Unsupported features configuration schemes
160 |
161 | Currently, the following features of pye3dc are not supported:
162 |
163 | - Web Connections
164 | - Local connections when offline, using the backup user.
165 |
166 | ## Actions
167 |
168 | The integration currently provides these actions to initiate more complex
169 | commands to the E3DC unit:
170 |
171 | ### Set power limits
172 |
173 | Use the action `set_power_limits` to limit the maximum charging or discharging
174 | rates of the battery system. Both values can be controlled individually, each
175 | call replaces the settings made by the last. It will not allow you to change the
176 | system defined minimum discharge rate at the moment, as I am not sure if this is
177 | actually a sensible thing to do.
178 |
179 | ### Clear current power limits
180 |
181 | `clear_power_limits` will drop any active power limit. It will not emit an error
182 | if none has been set. Prefer this to use `set_power_limits` and setting the
183 | values to the system defined maximum.
184 |
185 | ### Initate manual battery charging
186 |
187 | The action `manual_charge` will start charging the specified amount of energy
188 | into the battery, taking it from the grid if neccessary. The idea behind this is
189 | to take advantage of dynamic electricity providers like Tibber. Charge your
190 | battery when electricity is cheap even if you have no solar power available, for
191 | example in windy winter nights/days.
192 |
193 | **Read the following before using this functionality on your own risk:**
194 |
195 | - Calls to this operation are rate-limited, your E3DC probaby will not accept
196 | more than one call every few hours. One unit reported to me had a wait time of
197 | two hours, apparently. The website mentions that this operation can only be
198 | called once a day and limits the charge amount to 3 kWh. This, again, is
199 | unconfirmed, so your milage may vary.
200 | - Important from a monetary point of view: You will have losses from two AC/DC
201 | conversions (load and unload), as opposed to one when charging from the PV. A
202 | single conversion will probably cost you 10-15% in stored power. So, charging
203 | 10 kWh from the Grid will approximate only 7-8 kWh when using it. Also, the
204 | wear on the battery should be considered. Following that, you'll want
205 | significant savings, not just a few cents.
206 | - Check if your local laws and regulations do allow you to charge your battery
207 | from the grid for consuming power later in the first place.
208 | - Check the impact on any warranty from E3DC you may have.
209 |
210 | To stress this once more: Use this feature at your own risk.
211 |
212 | ### Set maximum wallbox charging current
213 |
214 | The action `set_wallbox_charging_current` will set the maximum charging current
215 | of the given Wallbox in Amps. 16A is typical for a 11kW Wallbox, 32A is typical
216 | for a 22kW Wallbox.
217 |
218 | **Read the following before using this functionality on your own risk:**
219 |
220 | - If values cannot be set, this may be due to the hard limits for your fuses
221 | configured during the installation of the Wallbox. Only a E3DC service
222 | technican can and should change these limits.
223 | - In case your fuse settings are wrong (too low) and you set the charging
224 | current too high, you may blow your fuse or even damage your Wallbox.
225 | - Check your local laws and regulations whether setting the Wallbox to a higher
226 | charging current requires approvals from your grid operator.
227 |
228 | ## Upstream source
229 |
230 | The extension is based on [Python E3DC
231 | library](https://github.com/fsantini/python-e3dc) from @fsantini. The general
232 | considerations mentioned in his project do apply to this integration.
233 |
234 | ***
235 |
236 |
240 | [commits-shield]: https://img.shields.io/github/commit-activity/y/torbennehmer/hacs-e3dc?style=for-the-badge&logo=git
241 | [commits]: https://github.com/torbennehmer/hacs-e3dc/commits/main
242 |
246 | [forum-shield]: https://img.shields.io/badge/Community%20Forum-Home%20Assistant-blue?style=for-the-badge&logo=homeassistant
247 | [forum]: https://community.home-assistant.io/t/e3dc-remote-storage-control-protocol-rscp/595280
248 | [hacs]: https://github.com/hacs/integration
249 | [hacs-shield]: https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=for-the-badge&logo=homeassistantcommunitystore
250 | [license-shield]: https://img.shields.io/github/license/torbennehmer/hacs-e3dc?style=for-the-badge&color=blue&logo=gnu
251 | [maintainer]: https://img.shields.io/badge/Maintainer-Torben%20Nehmer-blue?style=for-the-badge&logo=github
252 | [prereleases-shield]: https://img.shields.io/github/v/release/torbennehmer/hacs-e3dc?include_prereleases&style=for-the-badge&logo=git
253 | [releases-shield]: https://img.shields.io/github/v/release/torbennehmer/hacs-e3dc?style=for-the-badge&logo=homeassistantcommunitystore
254 | [releases]: https://github.com/torbennehmer/hacs-e3dc/releases
255 |
--------------------------------------------------------------------------------
/config/configuration.yaml:
--------------------------------------------------------------------------------
1 | # https://www.home-assistant.io/integrations/default_config/
2 | default_config:
3 |
4 | http:
5 | server_port: 8124
6 |
7 | # https://www.home-assistant.io/integrations/logger/
8 | logger:
9 | default: info
10 | logs:
11 | custom_components.e3dc_rscp: debug
12 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/__init__.py:
--------------------------------------------------------------------------------
1 | """The E3DC Remote Storage Control Protocol integration."""
2 |
3 | # Open tasks from integration quality checklist:
4 | # 1. Handles internet unavailable. Log a warning once when unavailable,
5 | # log once when reconnected.
6 | # -> Needs special care, as auth credentials change when E3DC is offline,
7 | # haven't tested this yet, so we work only as long as we're connected.
8 | # 2. Handles device/service unavailable. Log a warning once when unavailable,
9 | # log once when reconnected.
10 | # -> Similar to previous point, right now, we'll run into connection errors,
11 | # we need an update to the E3DC lib to catch this safely, working on that one.
12 | # 3. Set available property to False if appropriate
13 | # -> once 2 is done, update the entity's available state appropriately.
14 |
15 | from __future__ import annotations
16 |
17 | from homeassistant.config_entries import ConfigEntry
18 | from homeassistant.core import HomeAssistant
19 | from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
20 |
21 | from .const import DOMAIN, PLATFORMS
22 | from .coordinator import E3DCCoordinator
23 | from .services import async_setup_services
24 |
25 |
26 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
27 | """Set up E3DC Remote Storage Control Protocol from a config entry."""
28 |
29 | coordinator: E3DCCoordinator = E3DCCoordinator(hass, entry)
30 | try:
31 | await coordinator.async_connect()
32 | await coordinator.async_config_entry_first_refresh()
33 | except ConfigEntryAuthFailed:
34 | raise
35 | except Exception as ex:
36 | raise ConfigEntryNotReady(f"Configuration not yet ready: {ex}") from ex
37 |
38 | hass.data.setdefault(DOMAIN, {})
39 | hass.data[DOMAIN][entry.unique_id] = coordinator
40 | await coordinator.async_identify_wallboxes(hass)
41 | await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
42 | await async_setup_services(hass)
43 |
44 | return True
45 |
46 |
47 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
48 | """Unload the config entry."""
49 | if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
50 | hass.data[DOMAIN].pop(entry.unique_id)
51 |
52 | return unload_ok
53 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/binary_sensor.py:
--------------------------------------------------------------------------------
1 | """E3DC Binary Sensors."""
2 |
3 | from dataclasses import dataclass
4 | import logging
5 | from typing import Final
6 |
7 | from homeassistant.components.binary_sensor import (
8 | BinarySensorDeviceClass,
9 | BinarySensorEntity,
10 | BinarySensorEntityDescription,
11 | )
12 | from homeassistant.config_entries import ConfigEntry
13 | from homeassistant.const import EntityCategory
14 | from homeassistant.core import HomeAssistant
15 | from homeassistant.helpers.entity import DeviceInfo
16 | from homeassistant.helpers.entity_platform import AddEntitiesCallback
17 | from homeassistant.helpers.update_coordinator import CoordinatorEntity
18 |
19 | from .const import DOMAIN
20 | from .coordinator import E3DCCoordinator
21 |
22 | _LOGGER = logging.getLogger(__name__)
23 |
24 |
25 | @dataclass(slots=True, frozen=True)
26 | class E3DCBinarySensorEntityDescription(BinarySensorEntityDescription):
27 | """Derived helper for more advanced entity configs."""
28 |
29 | on_icon: str | None = None
30 | off_icon: str | None = None
31 |
32 |
33 | SENSOR_DESCRIPTIONS: Final[tuple[E3DCBinarySensorEntityDescription, ...]] = (
34 | # DIAGNOSTIC SENSORS
35 | E3DCBinarySensorEntityDescription(
36 | key="system-additional-source-available",
37 | translation_key="system-additional-source-available",
38 | entity_category=EntityCategory.DIAGNOSTIC,
39 | device_class=BinarySensorDeviceClass.CONNECTIVITY,
40 | on_icon="mdi:power-plug-outline",
41 | off_icon="mdi:power-plug-off-outline",
42 | ),
43 | # DEVICE SENSORS
44 | E3DCBinarySensorEntityDescription(
45 | key="pset-limit-enabled",
46 | translation_key="pset-limit-enabled",
47 | device_class=BinarySensorDeviceClass.RUNNING,
48 | on_icon="mdi:signal",
49 | off_icon="mdi:signal-off",
50 | ),
51 | E3DCBinarySensorEntityDescription(
52 | key="manual-charge-active",
53 | translation_key="manual-charge-active",
54 | device_class=BinarySensorDeviceClass.RUNNING,
55 | on_icon="mdi:electric-switch-closed",
56 | off_icon="mdi:electric-switch",
57 | ),
58 | )
59 |
60 |
61 | async def async_setup_entry(
62 | hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
63 | ) -> None:
64 | """Prepare the Platform."""
65 | assert isinstance(entry.unique_id, str)
66 | coordinator: E3DCCoordinator = hass.data[DOMAIN][entry.unique_id]
67 | entities: list[E3DCBinarySensor] = [
68 | E3DCBinarySensor(coordinator, description, entry.unique_id)
69 | for description in SENSOR_DESCRIPTIONS
70 | ]
71 |
72 | for wallbox in coordinator.wallboxes:
73 | # Get the UID & Key for the given wallbox
74 | unique_id = list(wallbox["deviceInfo"]["identifiers"])[0][1]
75 | wallbox_key = wallbox["key"]
76 |
77 | wallbox_sun_mode_description = E3DCBinarySensorEntityDescription(
78 | key=f"{wallbox_key}-sun-mode",
79 | translation_key="wallbox-sun-mode",
80 | on_icon="mdi:weather-sunny",
81 | off_icon="mdi:weather-sunny-off",
82 | device_class=None,
83 | )
84 | entities.append(
85 | E3DCBinarySensor(
86 | coordinator,
87 | wallbox_sun_mode_description,
88 | unique_id,
89 | wallbox["deviceInfo"],
90 | )
91 | )
92 |
93 | wallbox_plug_lock_description = E3DCBinarySensorEntityDescription(
94 | key=f"{wallbox_key}-plug-lock",
95 | translation_key="wallbox-plug-lock",
96 | on_icon="mdi:lock-open",
97 | off_icon="mdi:lock",
98 | device_class=BinarySensorDeviceClass.LOCK,
99 | entity_registry_enabled_default=False, # Disabled per default as only Wallbox easy connect provides this state
100 | )
101 | entities.append(
102 | E3DCBinarySensor(
103 | coordinator,
104 | wallbox_plug_lock_description,
105 | unique_id,
106 | wallbox["deviceInfo"],
107 | )
108 | )
109 |
110 | wallbox_plug_description = E3DCBinarySensorEntityDescription(
111 | key=f"{wallbox_key}-plug",
112 | translation_key="wallbox-plug",
113 | on_icon="mdi:power-plug",
114 | off_icon="mdi:power-plug-off",
115 | device_class=BinarySensorDeviceClass.PLUG,
116 | )
117 | entities.append(
118 | E3DCBinarySensor(
119 | coordinator, wallbox_plug_description, unique_id, wallbox["deviceInfo"]
120 | )
121 | )
122 |
123 | wallbox_schuko_description = E3DCBinarySensorEntityDescription(
124 | key=f"{wallbox_key}-schuko",
125 | translation_key="wallbox-schuko",
126 | on_icon="mdi:power-plug-outline",
127 | off_icon="mdi:power-plug-off-outline",
128 | device_class=BinarySensorDeviceClass.POWER,
129 | entity_registry_enabled_default=False, # Disabled per default as only Wallbox multi connect I provides this feature
130 | )
131 | entities.append(
132 | E3DCBinarySensor(
133 | coordinator,
134 | wallbox_schuko_description,
135 | unique_id,
136 | wallbox["deviceInfo"],
137 | )
138 | )
139 |
140 | wallbox_charging_description = E3DCBinarySensorEntityDescription(
141 | key=f"{wallbox_key}-charging",
142 | translation_key="wallbox-charging",
143 | on_icon="mdi:car-electric",
144 | off_icon="mdi:car-electric-outline",
145 | device_class=BinarySensorDeviceClass.BATTERY_CHARGING,
146 | )
147 | entities.append(
148 | E3DCBinarySensor(
149 | coordinator,
150 | wallbox_charging_description,
151 | unique_id,
152 | wallbox["deviceInfo"],
153 | )
154 | )
155 |
156 | wallbox_charging_canceled_description = E3DCBinarySensorEntityDescription(
157 | key=f"{wallbox_key}-charging-canceled",
158 | translation_key="wallbox-charging-canceled",
159 | on_icon="mdi:cancel",
160 | off_icon="mdi:check-circle-outline",
161 | device_class=None,
162 | )
163 | entities.append(
164 | E3DCBinarySensor(
165 | coordinator,
166 | wallbox_charging_canceled_description,
167 | unique_id,
168 | wallbox["deviceInfo"],
169 | )
170 | )
171 |
172 | wallbox_battery_to_car_description = E3DCBinarySensorEntityDescription(
173 | key=f"{wallbox_key}-battery-to-car",
174 | translation_key="wallbox-battery-to-car",
175 | on_icon="mdi:battery-charging",
176 | off_icon="mdi:battery-off",
177 | device_class=None,
178 | entity_registry_enabled_default=False,
179 | )
180 | entities.append(
181 | E3DCBinarySensor(
182 | coordinator,
183 | wallbox_battery_to_car_description,
184 | unique_id,
185 | wallbox["deviceInfo"],
186 | )
187 | )
188 |
189 | wallbox_key_state_description = E3DCBinarySensorEntityDescription(
190 | key=f"{wallbox_key}-key-state",
191 | translation_key="wallbox-key-state",
192 | on_icon="mdi:key-variant",
193 | off_icon="mdi:key-remove",
194 | device_class=BinarySensorDeviceClass.LOCK,
195 | entity_registry_enabled_default=False,
196 | )
197 | entities.append(
198 | E3DCBinarySensor(
199 | coordinator,
200 | wallbox_key_state_description,
201 | unique_id,
202 | wallbox["deviceInfo"],
203 | )
204 | )
205 |
206 | async_add_entities(entities)
207 |
208 |
209 | class E3DCBinarySensor(CoordinatorEntity, BinarySensorEntity):
210 | """Custom E3DC Binary Sensor implementation."""
211 |
212 | _attr_has_entity_name: bool = True
213 |
214 | def __init__(
215 | self,
216 | coordinator: E3DCCoordinator,
217 | description: E3DCBinarySensorEntityDescription,
218 | uid: str,
219 | device_info: DeviceInfo | None = None,
220 | ) -> None:
221 | """Initialize the Sensor."""
222 | super().__init__(coordinator)
223 | self.coordinator: E3DCCoordinator = coordinator
224 | self.entity_description: E3DCBinarySensorEntityDescription = description
225 | self._attr_unique_id = f"{uid}_{description.key}"
226 | self._custom_icons: bool = (
227 | self.entity_description.on_icon is not None
228 | and self.entity_description.off_icon is not None
229 | )
230 | if device_info is not None:
231 | self._deviceInfo = device_info
232 | else:
233 | self._deviceInfo = self.coordinator.device_info()
234 |
235 | @property
236 | def is_on(self) -> bool | None:
237 | """Return the actual sensor state."""
238 | return self.coordinator.data.get(self.entity_description.key)
239 |
240 | @property
241 | def icon(self) -> str | None:
242 | """Return customized icons, if applicable."""
243 | return (
244 | self.entity_description.on_icon
245 | if self.is_on
246 | else self.entity_description.off_icon
247 | )
248 |
249 | @property
250 | def device_info(self) -> DeviceInfo:
251 | """Return the device information."""
252 | return self._deviceInfo
253 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/button.py:
--------------------------------------------------------------------------------
1 | """E3DC Button platform."""
2 |
3 | from collections.abc import Callable, Coroutine
4 | from dataclasses import dataclass
5 | import logging
6 | from typing import Any, Final
7 |
8 | from homeassistant.components.button import (
9 | ButtonEntity,
10 | ButtonEntityDescription,
11 | )
12 | from homeassistant.config_entries import ConfigEntry
13 | from homeassistant.core import HomeAssistant
14 | from homeassistant.helpers.entity import DeviceInfo
15 | from homeassistant.helpers.entity_platform import AddEntitiesCallback
16 | from homeassistant.helpers.update_coordinator import CoordinatorEntity
17 |
18 | from .const import DOMAIN
19 | from .coordinator import E3DCCoordinator
20 |
21 | _LOGGER = logging.getLogger(__name__)
22 |
23 |
24 | @dataclass(slots=True, frozen=True)
25 | class E3DCButtonEntityDescription(ButtonEntityDescription):
26 | """Derived helper for advanced configs."""
27 |
28 | icon: str | None = None
29 | async_press_action: (
30 | Callable[[E3DCCoordinator], Coroutine[Any, Any, bool]] | None
31 | ) = None
32 |
33 |
34 | BUTTONS: Final[tuple[E3DCButtonEntityDescription, ...]] = () # None yet
35 |
36 |
37 | async def async_setup_entry(
38 | hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
39 | ) -> None:
40 | """Initialize Button Platform."""
41 | assert isinstance(entry.unique_id, str)
42 | coordinator: E3DCCoordinator = hass.data[DOMAIN][entry.unique_id]
43 |
44 | entities: list[E3DCButton] = [
45 | E3DCButton(coordinator, description, entry.unique_id) for description in BUTTONS
46 | ]
47 |
48 | for wallbox in coordinator.wallboxes:
49 | # Get the UID & Key for the given wallbox
50 | unique_id = list(wallbox["deviceInfo"]["identifiers"])[0][1]
51 | wallbox_key = wallbox["key"]
52 |
53 | wallbox_toggle_wallbox_phases_description = E3DCButtonEntityDescription(
54 | key=f"{wallbox_key}-toggle-wallbox-phases",
55 | translation_key="wallbox-toggle-wallbox-phases",
56 | icon="mdi:sine-wave",
57 | async_press_action=lambda coordinator, index=wallbox[
58 | "index"
59 | ]: coordinator.async_toggle_wallbox_phases(index),
60 | )
61 | entities.append(
62 | E3DCButton(
63 | coordinator,
64 | wallbox_toggle_wallbox_phases_description,
65 | unique_id,
66 | wallbox["deviceInfo"],
67 | )
68 | )
69 |
70 | wallbox_toggle_wallbox_charging_description = E3DCButtonEntityDescription(
71 | key=f"{wallbox_key}-toggle-wallbox-charging",
72 | translation_key="wallbox-toggle-wallbox-charging",
73 | icon="mdi:car-electric",
74 | async_press_action=lambda coordinator, index=wallbox[
75 | "index"
76 | ]: coordinator.async_toggle_wallbox_charging(index),
77 | )
78 | entities.append(
79 | E3DCButton(
80 | coordinator,
81 | wallbox_toggle_wallbox_charging_description,
82 | unique_id,
83 | wallbox["deviceInfo"],
84 | )
85 | )
86 |
87 | async_add_entities(entities)
88 |
89 |
90 | class E3DCButton(CoordinatorEntity, ButtonEntity):
91 | """Custom E3DC Button Implementation."""
92 |
93 | _attr_has_entity_name = True
94 |
95 | def __init__(
96 | self,
97 | coordinator: E3DCCoordinator,
98 | description: E3DCButtonEntityDescription,
99 | uid: str,
100 | device_info: DeviceInfo | None = None,
101 | ) -> None:
102 | """Initialize the Button."""
103 | super().__init__(coordinator)
104 | self.coordinator: E3DCCoordinator = coordinator
105 | self.entity_description: E3DCButtonEntityDescription = description
106 | self._attr_unique_id = f"{uid}_{description.key}"
107 | self._has_custom_icons: bool = self.entity_description.icon is not None
108 | if device_info is not None:
109 | self._deviceInfo = device_info
110 | else:
111 | self._deviceInfo = self.coordinator.device_info()
112 |
113 | @property
114 | def icon(self) -> str | None:
115 | """Return icon reference."""
116 | if self._has_custom_icons:
117 | return self.entity_description.icon
118 |
119 | return self._attr_icon
120 |
121 | async def async_press(self, **kwargs: Any) -> None:
122 | """Press the button asynchronnously."""
123 | if self.entity_description.async_press_action is not None:
124 | await self.entity_description.async_press_action(self.coordinator)
125 |
126 | @property
127 | def device_info(self) -> DeviceInfo:
128 | """Return the device information."""
129 | return self._deviceInfo
130 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/config_flow.py:
--------------------------------------------------------------------------------
1 | """Config flow for E3DC Remote Storage Control Protocol integration."""
2 | from __future__ import annotations
3 |
4 | from collections.abc import Mapping
5 | import logging
6 | from typing import Any
7 |
8 | import voluptuous as vol
9 |
10 | from homeassistant import config_entries
11 | from homeassistant.const import (
12 | CONF_API_VERSION,
13 | CONF_HOST,
14 | CONF_PASSWORD,
15 | CONF_USERNAME,
16 | )
17 | from homeassistant.data_entry_flow import FlowResult
18 | from homeassistant.exceptions import HomeAssistantError, ConfigEntryAuthFailed
19 | from homeassistant.helpers.selector import (
20 | TextSelector,
21 | TextSelectorConfig,
22 | TextSelectorType,
23 | )
24 |
25 | from .const import (
26 | CONF_RSCPKEY,
27 | CONF_VERSION,
28 | DOMAIN,
29 | ERROR_AUTH_INVALID,
30 | ERROR_CANNOT_CONNECT,
31 | )
32 | from .e3dc_proxy import E3DCProxy
33 |
34 | _LOGGER = logging.getLogger(__name__)
35 |
36 | STEP_USER_DATA_SCHEMA = vol.Schema(
37 | {
38 | vol.Required(CONF_HOST): str,
39 | vol.Required(CONF_USERNAME): str,
40 | vol.Required(CONF_PASSWORD): str,
41 | vol.Required(CONF_RSCPKEY): TextSelector(
42 | TextSelectorConfig(type=TextSelectorType.PASSWORD)
43 | ),
44 | }
45 | )
46 |
47 |
48 | class E3DCConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
49 | """Handle a config flow for E3DC Remote Storage Control Protocol."""
50 |
51 | def __init__(self) -> None:
52 | """Initialize config flow."""
53 | self._entry: config_entries.ConfigEntry | None = None
54 | self._host: str | None = None
55 | self._username: str | None = None
56 | self._password: str | None = None
57 | self._rscpkey: str | None = None
58 | self._proxy: E3DCProxy = None
59 |
60 | def _async_check_login(self) -> None:
61 | assert isinstance(self._username, str)
62 | assert isinstance(self._password, str)
63 | assert isinstance(self._host, str)
64 | assert isinstance(self._rscpkey, str)
65 |
66 | self._proxy = E3DCProxy(self.hass, {
67 | CONF_HOST: self._host,
68 | CONF_USERNAME: self._username,
69 | CONF_PASSWORD: self._password,
70 | CONF_RSCPKEY: self._rscpkey
71 | })
72 | self._proxy.connect()
73 |
74 | async def validate_input(self) -> str | None:
75 | """Validate the user input allows us to connect."""
76 | try:
77 | await self.hass.async_add_executor_job(self._async_check_login)
78 | except ConfigEntryAuthFailed:
79 | return ERROR_AUTH_INVALID
80 | except HomeAssistantError:
81 | return ERROR_CANNOT_CONNECT
82 | return None
83 |
84 | async def async_step_user(
85 | self, user_input: dict[str, Any] | None = None
86 | ) -> FlowResult:
87 | """Handle the initial step."""
88 | errors: dict[str, str] = {}
89 |
90 | if user_input is None:
91 | return self._show_setup_form_init(errors)
92 |
93 | self._host = user_input[CONF_HOST]
94 | self._username = user_input[CONF_USERNAME]
95 | self._password = user_input[CONF_PASSWORD]
96 | self._rscpkey = user_input[CONF_RSCPKEY]
97 |
98 | if error := await self.validate_input():
99 | return self._show_setup_form_init({"base": error})
100 |
101 | await self.async_set_unique_id(
102 | f"{self._proxy.e3dc.serialNumberPrefix}{self._proxy.e3dc.serialNumber}"
103 | )
104 | self._abort_if_unique_id_configured()
105 | final_data: dict[str, Any] = user_input
106 | final_data[CONF_API_VERSION] = CONF_VERSION
107 |
108 | return self.async_create_entry(
109 | title=f"E3DC {self._proxy.e3dc.model}", data=final_data
110 | )
111 |
112 | def _show_setup_form_init(self, errors: dict[str, str] | None = None) -> FlowResult:
113 | """Show the setup form to the user."""
114 | return self.async_show_form(
115 | step_id="user",
116 | data_schema=STEP_USER_DATA_SCHEMA,
117 | errors=errors or {},
118 | )
119 |
120 | async def async_step_reauth(self, entry_data: Mapping[str, Any]) -> FlowResult:
121 | """Handle flow upon API authentication errors."""
122 | self._entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
123 | self._host = entry_data[CONF_HOST]
124 | self._username = entry_data[CONF_USERNAME]
125 | self._password = entry_data[CONF_PASSWORD]
126 | self._rscpkey = entry_data[CONF_RSCPKEY]
127 | return await self.async_step_reauth_confirm()
128 |
129 | async def async_step_reauth_confirm(
130 | self, user_input: dict[str, Any] | None = None
131 | ) -> FlowResult:
132 | """Inform the user that a reauth is required."""
133 |
134 | if user_input is None:
135 | return self._show_setup_form_reauth_confirm()
136 |
137 | self._host = user_input[CONF_HOST]
138 | self._username = user_input[CONF_USERNAME]
139 | self._password = user_input[CONF_PASSWORD]
140 | self._rscpkey = user_input[CONF_RSCPKEY]
141 |
142 | if error := await self.validate_input():
143 | return self._show_setup_form_reauth_confirm({"base": error})
144 |
145 | assert isinstance(self._entry, config_entries.ConfigEntry)
146 | final_data: dict[str, Any] = user_input
147 | final_data[CONF_API_VERSION] = CONF_VERSION
148 | self.hass.config_entries.async_update_entry(
149 | self._entry,
150 | data=final_data,
151 | )
152 | await self.hass.config_entries.async_reload(self._entry.entry_id)
153 | return self.async_abort(reason="reauth_successful")
154 |
155 | def _show_setup_form_reauth_confirm(
156 | self, errors: dict[str, str] | None = None
157 | ) -> FlowResult:
158 | """Show the setup form to the user."""
159 | return self.async_show_form(
160 | step_id="reauth_confirm",
161 | data_schema=STEP_USER_DATA_SCHEMA,
162 | errors=errors or {},
163 | )
164 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/const.py:
--------------------------------------------------------------------------------
1 | """Constants for the E3DC Remote Storage Control Protocol integration."""
2 |
3 | from homeassistant.const import Platform
4 |
5 | CONF_RSCPKEY = "rscpkey"
6 | CONF_VERSION = 1
7 | DOMAIN = "e3dc_rscp"
8 | ERROR_AUTH_INVALID = "invalid_auth"
9 | ERROR_CANNOT_CONNECT = "cannot_connect"
10 | SERVICE_CLEAR_POWER_LIMITS = "clear_power_limits"
11 | SERVICE_SET_POWER_LIMITS = "set_power_limits"
12 | SERVICE_MANUAL_CHARGE = "manual_charge"
13 | SERVICE_SET_WALLBOX_MAX_CHARGE_CURRENT = "set_wallbox_max_charge_current"
14 | MAX_WALLBOXES_POSSIBLE = 8 # 8 is the maximum according to RSCP Specification
15 |
16 | PLATFORMS: list[Platform] = [
17 | Platform.BINARY_SENSOR,
18 | Platform.SENSOR,
19 | Platform.SWITCH,
20 | Platform.BUTTON,
21 | Platform.NUMBER
22 | ]
23 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/coordinator.py:
--------------------------------------------------------------------------------
1 | """Coordinator for E3DC integration."""
2 |
3 | from datetime import timedelta, datetime
4 | import logging
5 | from time import time
6 | from typing import Any, TypedDict
7 | import pytz
8 | import re
9 |
10 | from e3dc._rscpTags import PowermeterType
11 |
12 | from homeassistant.config_entries import ConfigEntry
13 | from homeassistant.core import HomeAssistant
14 | from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
15 | from homeassistant.util.dt import as_timestamp, start_of_local_day
16 | from homeassistant.helpers import device_registry as dr
17 | from homeassistant.helpers.entity import DeviceInfo
18 | from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
19 | from homeassistant.components.sensor import SensorStateClass
20 |
21 | from .const import DOMAIN, MAX_WALLBOXES_POSSIBLE
22 |
23 | from .e3dc_proxy import E3DCProxy
24 |
25 | _LOGGER = logging.getLogger(__name__)
26 | _STAT_REFRESH_INTERVAL = 60
27 |
28 |
29 | class E3DCWallbox(TypedDict):
30 | """E3DC Wallbox, keeps general information, attributes and identity data for an individual wallbox."""
31 |
32 | index: int
33 | key: str
34 | deviceInfo: DeviceInfo
35 | lowerCurrentLimit: int
36 | upperCurrentLimit: int
37 |
38 |
39 | class E3DCCoordinator(DataUpdateCoordinator[dict[str, Any]]):
40 | """E3DC Coordinator, fetches all relevant data and provides proxies for all service calls."""
41 |
42 | def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
43 | """Initialize E3DC Coordinator and connect."""
44 | assert isinstance(config_entry.unique_id, str)
45 | self.uid: str = config_entry.unique_id
46 | self.proxy = E3DCProxy(hass, config_entry)
47 | self._mydata: dict[str, Any] = {}
48 | self._sw_version: str = ""
49 | self._update_guard_powersettings: bool = False
50 | self._update_guard_wallboxsettings: bool = False
51 | self._wallboxes: list[E3DCWallbox] = []
52 | self._timezone_offset: int = 0
53 | self._next_stat_update: float = 0
54 |
55 | super().__init__(
56 | hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=10)
57 | )
58 |
59 | async def async_connect(self):
60 | """Establish connection to E3DC."""
61 |
62 | # TODO: Beautify this, make the code flow with the connects/disconnects more natural.
63 | # Have a call to autoconf, then connect with it.
64 | await self.hass.async_add_executor_job(self.proxy.connect)
65 | await self._async_connect_additional_powermeters()
66 |
67 | self._mydata["system-derate-percent"] = self.proxy.e3dc.deratePercent
68 | self._mydata["system-derate-power"] = self.proxy.e3dc.deratePower
69 | self._mydata["system-additional-source-available"] = (
70 | self.proxy.e3dc.externalSourceAvailable != 0
71 | )
72 | self._mydata["system-battery-installed-capacity"] = (
73 | self.proxy.e3dc.installedBatteryCapacity
74 | )
75 | self._mydata["system-battery-installed-peak"] = (
76 | self.proxy.e3dc.installedPeakPower
77 | )
78 | self._mydata["system-ac-maxpower"] = self.proxy.e3dc.maxAcPower
79 | self._mydata["system-battery-charge-max"] = self.proxy.e3dc.maxBatChargePower
80 | self._mydata["system-battery-discharge-max"] = (
81 | self.proxy.e3dc.maxBatDischargePower
82 | )
83 | self._mydata["system-mac"] = self.proxy.e3dc.macAddress
84 | self._mydata["model"] = self.proxy.e3dc.model
85 | self._mydata["system-battery-discharge-minimum-default"] = (
86 | self.proxy.e3dc.startDischargeDefault
87 | )
88 |
89 | # Idea: Maybe Port this to e3dc lib, it can query this in one go during startup.
90 | self._sw_version = await self.hass.async_add_executor_job(
91 | self.proxy.get_software_version
92 | )
93 |
94 | await self._load_timezone_settings()
95 |
96 | async def async_identify_wallboxes(self, hass: HomeAssistant):
97 | """Identify availability of Wallboxes if get_wallbox_identification_data() returns meaningful data."""
98 |
99 | for wallbox_index in range(0, MAX_WALLBOXES_POSSIBLE - 1):
100 | try:
101 | request_data: dict[str, Any] = await self.hass.async_add_executor_job(
102 | self.proxy.get_wallbox_identification_data, wallbox_index
103 | )
104 | except HomeAssistantError as ex:
105 | _LOGGER.warning(
106 | "Failed to load wallbox with index %s, not updating data: %s",
107 | wallbox_index,
108 | ex,
109 | )
110 | return
111 |
112 | if "macAddress" in request_data:
113 | _LOGGER.debug("Wallbox with index %s has been found", wallbox_index)
114 |
115 | unique_id = dr.format_mac(request_data["macAddress"])
116 | wallboxType = request_data["wallboxType"]
117 | model = f"Wallbox Type {wallboxType}"
118 |
119 | deviceInfo = DeviceInfo(
120 | identifiers={(DOMAIN, unique_id)},
121 | via_device=(DOMAIN, self.uid),
122 | manufacturer="E3DC",
123 | name=request_data["deviceName"],
124 | model=model,
125 | sw_version=request_data["firmwareVersion"],
126 | serial_number=request_data["wallboxSerial"],
127 | connections={
128 | (
129 | dr.CONNECTION_NETWORK_MAC,
130 | dr.format_mac(request_data["macAddress"]),
131 | )
132 | },
133 | configuration_url="https://my.e3dc.com/",
134 | )
135 |
136 | wallbox: E3DCWallbox = {
137 | "index": wallbox_index,
138 | "key": unique_id,
139 | "deviceInfo": deviceInfo,
140 | "lowerCurrentLimit": request_data["lowerCurrentLimit"],
141 | "upperCurrentLimit": request_data["upperCurrentLimit"],
142 | }
143 | self.wallboxes.append(wallbox)
144 | else:
145 | _LOGGER.debug("No Wallbox with index %s has been found", wallbox_index)
146 |
147 | # Getter for _wallboxes
148 | @property
149 | def wallboxes(self) -> list[E3DCWallbox]:
150 | """Get the list of wallboxes."""
151 | return self._wallboxes
152 |
153 | # Setter for individual wallbox values
154 | def setWallboxValue(self, index: int, key: str, value: Any) -> None:
155 | """Set the value for a specific key in a wallbox identified by its index."""
156 | for wallbox in self._wallboxes:
157 | if wallbox["index"] == index:
158 | wallbox[key] = value
159 | _LOGGER.debug(f"Set {key} to {value} for wallbox with index {index}")
160 | return
161 | raise ValueError(f"Wallbox with index {index} not found")
162 |
163 | # Getter for individual wallbox values
164 | def getWallboxValue(self, index: int, key: str) -> Any:
165 | """Get the value for a specific key in a wallbox identified by its index."""
166 | for wallbox in self._wallboxes:
167 | if wallbox["index"] == index:
168 | value = wallbox.get(key)
169 | if value is not None:
170 | _LOGGER.debug(
171 | f"Got {key} value {value} for wallbox with index {index}"
172 | )
173 | return value
174 | else:
175 | raise KeyError(f"Key {key} not found in wallbox with index {index}")
176 | raise ValueError(f"Wallbox with index {index} not found")
177 |
178 | async def _async_connect_additional_powermeters(self):
179 | """Identify the installed powermeters and reconnect to E3DC with this config."""
180 | # TODO: Restructure config so that we are indexed by powemeter ID.
181 | self.proxy.e3dc_config["powermeters"] = await self.hass.async_add_executor_job(
182 | self.proxy.get_powermeters
183 | )
184 |
185 | for powermeter in self.proxy.e3dc_config["powermeters"]:
186 | if powermeter["type"] == PowermeterType.PM_TYPE_ROOT.value:
187 | powermeter["name"] = "Root PM"
188 | powermeter["key"] = "root-pm"
189 | powermeter["total-state-class"] = SensorStateClass.TOTAL
190 | powermeter["negate-measure"] = False
191 |
192 | else:
193 | powermeter["name"] = (
194 | powermeter["typeName"]
195 | .replace("PM_TYPE_", "")
196 | .replace("_", " ")
197 | .capitalize()
198 | )
199 | powermeter["key"] = (
200 | powermeter["typeName"]
201 | .replace("PM_TYPE_", "")
202 | .replace("_", "-")
203 | .lower()
204 | + "-"
205 | + str(powermeter["index"])
206 | )
207 |
208 | match powermeter["type"]:
209 | case (
210 | PowermeterType.PM_TYPE_ADDITIONAL_PRODUCTION.value
211 | | PowermeterType.PM_TYPE_ADDITIONAL.value
212 | ):
213 | powermeter["total-state-class"] = (
214 | SensorStateClass.TOTAL_INCREASING
215 | )
216 | powermeter["negate-measure"] = True
217 |
218 | case PowermeterType.PM_TYPE_ADDITIONAL_CONSUMPTION.value:
219 | powermeter["total-state-class"] = (
220 | SensorStateClass.TOTAL_INCREASING
221 | )
222 | powermeter["negate-measure"] = False
223 |
224 | case _:
225 | powermeter["total-state-class"] = SensorStateClass.TOTAL
226 | powermeter["negate-measure"] = False
227 |
228 | await self.hass.async_add_executor_job(self.proxy.disconnect)
229 | await self.hass.async_add_executor_job(
230 | self.proxy.connect,
231 | self.proxy.e3dc_config,
232 | )
233 |
234 | async def _async_update_data(self) -> dict[str, Any]:
235 | """Update all data required by our entities in one go."""
236 |
237 | # Now we've to update all dynamic values in self._mydata,
238 | # connect did already retrieve all static values.
239 |
240 | _LOGGER.debug("Polling general status information")
241 | await self._load_and_process_poll()
242 |
243 | # TODO: Check if we need to replace this with a safe IPC sync
244 | if self._update_guard_powersettings is False:
245 | _LOGGER.debug("Poll power settings")
246 | await self._load_and_process_power_settings()
247 | else:
248 | _LOGGER.debug("Not polling powersettings, they are updating right now")
249 |
250 | _LOGGER.debug("Polling manual charge information")
251 | await self._load_and_process_manual_charge()
252 |
253 | if self._update_guard_wallboxsettings is False:
254 | _LOGGER.debug("Polling additional powermeters")
255 | await self._load_and_process_powermeters_data()
256 | else:
257 | _LOGGER.debug("Not polling wallbox, they are updating right now")
258 |
259 | if len(self.wallboxes) > 0:
260 | _LOGGER.debug("Polling wallbox")
261 | await self._load_and_process_wallbox_data()
262 |
263 | # Only poll power statstics once per minute. E3DC updates it only once per 15
264 | # minutes anyway, this should be a good compromise to get the metrics shortly
265 | # before the end of the day.
266 | if self._next_stat_update < time():
267 | _LOGGER.debug("Polling today's power metrics")
268 | await self._load_and_process_db_data_today()
269 | self._next_stat_update = time() + _STAT_REFRESH_INTERVAL
270 | # TODO: Reduce interval further, but take start_ts into account to get an
271 | # end of day reading of the metric.
272 | else:
273 | _LOGGER.debug("Skipping power metrics poll.")
274 |
275 | return self._mydata
276 |
277 | async def _load_and_process_power_settings(self):
278 | """Load and process power settings."""
279 | try:
280 | power_settings: dict[str, Any] = await self.hass.async_add_executor_job(
281 | self.proxy.get_power_settings
282 | )
283 | except HomeAssistantError as ex:
284 | _LOGGER.warning("Failed to load power settings, not updating data: %s", ex)
285 | return
286 |
287 | self._mydata["pset-limit-charge"] = power_settings["maxChargePower"]
288 | self._mydata["pset-limit-discharge"] = power_settings["maxDischargePower"]
289 | self._mydata["pset-limit-discharge-minimum"] = power_settings[
290 | "dischargeStartPower"
291 | ]
292 | self._mydata["pset-limit-enabled"] = power_settings["powerLimitsUsed"]
293 | self._mydata["pset-powersaving-enabled"] = power_settings["powerSaveEnabled"]
294 | self._mydata["pset-weatherregulationenabled"] = power_settings[
295 | "weatherRegulatedChargeEnabled"
296 | ]
297 |
298 | async def _load_and_process_poll(self):
299 | """Load and process standard poll data."""
300 | try:
301 | poll_data: dict[str, Any] = await self.hass.async_add_executor_job(
302 | self.proxy.poll
303 | )
304 | except HomeAssistantError as ex:
305 | _LOGGER.warning("Failed to poll, not updating data: %s", ex)
306 | return
307 |
308 | self._mydata["additional-production"] = poll_data["production"]["add"]
309 | self._mydata["autarky"] = poll_data["autarky"]
310 | self._mydata["battery-charge"] = max(0, poll_data["consumption"]["battery"])
311 | self._mydata["battery-discharge"] = (
312 | min(0, poll_data["consumption"]["battery"]) * -1
313 | )
314 | self._mydata["battery-netchange"] = poll_data["consumption"]["battery"]
315 | self._mydata["grid-consumption"] = max(0, poll_data["production"]["grid"])
316 | self._mydata["grid-netchange"] = poll_data["production"]["grid"]
317 | self._mydata["grid-production"] = min(0, poll_data["production"]["grid"]) * -1
318 | self._mydata["house-consumption"] = poll_data["consumption"]["house"]
319 | self._mydata["selfconsumption"] = poll_data["selfConsumption"]
320 | self._mydata["soc"] = poll_data["stateOfCharge"]
321 | self._mydata["solar-production"] = poll_data["production"]["solar"]
322 | self._mydata["wallbox-consumption"] = poll_data["consumption"]["wallbox"]
323 |
324 | async def _load_and_process_db_data_today(self) -> None:
325 | """Load and process retrieved db data settings."""
326 | try:
327 | db_data: dict[str, Any] = await self.hass.async_add_executor_job(
328 | self.proxy.get_db_data, self._get_db_data_day_timestamp(), 86400
329 | )
330 | except HomeAssistantError as ex:
331 | _LOGGER.warning("Failed to load daily stats, not updating data: %s", ex)
332 | return
333 |
334 | self._mydata["db-day-autarky"] = db_data["autarky"]
335 | self._mydata["db-day-battery-charge"] = db_data["bat_power_in"]
336 | self._mydata["db-day-battery-discharge"] = db_data["bat_power_out"]
337 | self._mydata["db-day-grid-consumption"] = db_data["grid_power_out"]
338 | self._mydata["db-day-grid-production"] = db_data["grid_power_in"]
339 | self._mydata["db-day-house-consumption"] = db_data["consumption"]
340 | self._mydata["db-day-selfconsumption"] = db_data["consumed_production"]
341 | self._mydata["db-day-solar-production"] = db_data["solarProduction"]
342 | self._mydata["db-day-startts"] = db_data["startTimestamp"]
343 |
344 | async def _load_and_process_manual_charge(self) -> None:
345 | """Loand and process manual charge status."""
346 | try:
347 | request_data: dict[str, Any] = await self.hass.async_add_executor_job(
348 | self.proxy.get_manual_charge
349 | )
350 | except HomeAssistantError as ex:
351 | _LOGGER.warning(
352 | "Failed to load manual charge state, not updating data: %s", ex
353 | )
354 | return
355 |
356 | self._mydata["manual-charge-active"] = request_data["active"]
357 | self._mydata["manual-charge-energy"] = request_data["energy"]
358 |
359 | async def _load_and_process_powermeters_data(self) -> None:
360 | """Load and process additional sources to existing data."""
361 | try:
362 | request_data: dict[str, Any] = await self.hass.async_add_executor_job(
363 | self.proxy.get_powermeters_data
364 | )
365 | except HomeAssistantError as ex:
366 | _LOGGER.warning("Failed to load powermeters, not updating data: %s", ex)
367 | return
368 |
369 | for key, value in request_data.items():
370 | self._mydata[key] = value
371 |
372 | async def _load_and_process_wallbox_data(self) -> None:
373 | """Load and process wallbox data to existing data."""
374 |
375 | for wallbox in self.wallboxes:
376 | try:
377 | request_data: dict[str, Any] = await self.hass.async_add_executor_job(
378 | self.proxy.get_wallbox_data, wallbox["index"]
379 | )
380 | except HomeAssistantError as ex:
381 | _LOGGER.warning("Failed to load wallboxes, not updating data: %s", ex)
382 | return
383 |
384 | for key, value in request_data.items():
385 | formatted_key = re.sub(
386 | r"(? int:
434 | """Get the local start-of-day timestamp for DB Query, needs some tweaking."""
435 | today: datetime = start_of_local_day()
436 | today_ts: int = int(as_timestamp(today))
437 | _LOGGER.debug(
438 | "Midnight is %s, DB query timestamp is %s, applied offset: %s",
439 | today,
440 | today_ts,
441 | self._timezone_offset,
442 | )
443 | # tz_hass: pytz.timezone = pytz.timezone("Europe/Berlin")
444 | # today: datetime = datetime.now(tz_hass).replace(hour=0, minute=0, second=0, microsecond=0)
445 | # today_ts: int = today.timestamp()
446 | # Move to local time, the Timestamp needed by the E3DC DB queries are
447 | # not in UTC as they should be.
448 | today_ts += self._timezone_offset
449 | return today_ts
450 |
451 | def device_info(self) -> DeviceInfo:
452 | """Return default device info structure."""
453 | return DeviceInfo(
454 | manufacturer="E3DC",
455 | model=self.proxy.e3dc.model,
456 | name=self.proxy.e3dc.model,
457 | serial_number=self.proxy.e3dc.serialNumber,
458 | connections={(dr.CONNECTION_NETWORK_MAC, self.proxy.e3dc.macAddress)},
459 | identifiers={(DOMAIN, self.uid)},
460 | sw_version=self._sw_version,
461 | configuration_url="https://my.e3dc.com/",
462 | )
463 |
464 | async def async_set_weather_regulated_charge(self, enabled: bool) -> bool:
465 | """Enable or disable weather regulated charging."""
466 | _LOGGER.debug("Updating weather regulated chargsing to %s", enabled)
467 |
468 | try:
469 | self._update_guard_powersettings = True
470 | await self.hass.async_add_executor_job(
471 | self.proxy.set_weather_regulated_charge, enabled
472 | )
473 | self._mydata["pset-weatherregulationenabled"] = enabled
474 | finally:
475 | self._update_guard_powersettings = False
476 |
477 | _LOGGER.debug("Successfully updated weather regulated charging to %s", enabled)
478 | return True
479 |
480 | async def async_set_powersave(self, enabled: bool) -> bool:
481 | """Enable or disable SmartPower powersaving."""
482 | _LOGGER.debug("Updating powersaving to %s", enabled)
483 |
484 | try:
485 | self._update_guard_powersettings = True
486 | await self.hass.async_add_executor_job(self.proxy.set_powersave, enabled)
487 | self._mydata["pset-powersaving-enabled"] = enabled
488 | finally:
489 | self._update_guard_powersettings = False
490 |
491 | _LOGGER.debug("Updated powersaving to %s", enabled)
492 | return True
493 |
494 | async def async_set_wallbox_sun_mode(
495 | self, enabled: bool, wallbox_index: int
496 | ) -> bool:
497 | """Enable or disable wallbox sun mode."""
498 | _LOGGER.debug("Updating wallbox sun mode to %s", enabled)
499 |
500 | try:
501 | self._update_guard_wallboxsettings = True
502 | await self.hass.async_add_executor_job(
503 | self.proxy.set_wallbox_sun_mode, enabled, wallbox_index
504 | )
505 | self._mydata["wallbox-sun-mode"] = enabled
506 | except Exception as ex:
507 | _LOGGER.error("Failed to set wallbox sun mode to %s: %s", enabled, ex)
508 | return False
509 | finally:
510 | self._update_guard_wallboxsettings = False
511 |
512 | _LOGGER.debug("Successfully updated wallbox sun mode to %s", enabled)
513 | return True
514 |
515 | async def async_set_wallbox_schuko(self, enabled: bool, wallbox_index: int) -> bool:
516 | """Enable or disable wallbox schuko."""
517 | _LOGGER.debug("Updating wallbox schuko to %s", enabled)
518 |
519 | try:
520 | self._update_guard_wallboxsettings = True
521 | await self.hass.async_add_executor_job(
522 | self.proxy.set_wallbox_schuko, enabled, wallbox_index
523 | )
524 | self._mydata["wallbox-schuko"] = enabled
525 | except Exception as ex:
526 | _LOGGER.error("Failed to set wallbox schuko to %s: %s", enabled, ex)
527 | return False
528 | finally:
529 | self._update_guard_wallboxsettings = False
530 |
531 | _LOGGER.debug("Successfully updated wallbox schuko to %s", enabled)
532 | return True
533 |
534 | async def async_toggle_wallbox_phases(self, wallbox_index: int) -> bool:
535 | """Toggle the Wallbox Phases between 1 and 3."""
536 | _LOGGER.debug("Toggling the Wallbox Phases")
537 |
538 | try:
539 | await self.hass.async_add_executor_job(
540 | self.proxy.toggle_wallbox_phases, wallbox_index
541 | )
542 | except Exception as ex:
543 | _LOGGER.error("Failed to toggle wallbox phases: %s", ex)
544 | return False
545 |
546 | _LOGGER.debug("Successfully toggled wallbox phases")
547 | return True
548 |
549 | async def async_toggle_wallbox_charging(self, wallbox_index: int) -> bool:
550 | """Toggle the Wallbox charging state."""
551 | _LOGGER.debug("Toggling the Wallbox charging state")
552 |
553 | try:
554 | await self.hass.async_add_executor_job(
555 | self.proxy.toggle_wallbox_charging, wallbox_index
556 | )
557 | except Exception as ex:
558 | _LOGGER.error("Failed to toggle wallbox charging state: %s", ex)
559 | return False
560 |
561 | _LOGGER.debug("Successfully toggled wallbox charging state")
562 | return True
563 |
564 | async def async_clear_power_limits(self) -> None:
565 | """Clear any active power limit."""
566 |
567 | _LOGGER.debug("Clearing any active power limit.")
568 |
569 | # Call RSCP service.
570 | # no update guard necessary, as we're called from a service, not an entity
571 | await self.hass.async_add_executor_job(
572 | self.proxy.set_power_limits, False, None, None, None
573 | )
574 |
575 | _LOGGER.debug("Successfully cleared the power limits")
576 |
577 | async def async_set_wallbox_max_charge_current(
578 | self, current: int | None, wallbox_index: int
579 | ) -> None:
580 | """Set the wallbox max charge current."""
581 |
582 | # TODO: Add more refined way to deal with maximum charge current, right now it's hard coded to 32A. The max current is dependant on the local installations, many WBs are throttled at 16A, not 32A due to power grid restrictions.
583 |
584 | # Validate the argument
585 | if current is None or current <= 0:
586 | raise ServiceValidationError(
587 | "async_set_wallbox_max_charge_current must be called with a positive current value."
588 | )
589 |
590 | if wallbox_index < 0 or wallbox_index >= MAX_WALLBOXES_POSSIBLE:
591 | raise ServiceValidationError(
592 | "async_set_wallbox_max_charge_current must be called with a valid wallbox id."
593 | )
594 |
595 | upperCurrentLimit = self.getWallboxValue(wallbox_index, "upperCurrentLimit")
596 | if current > upperCurrentLimit:
597 | _LOGGER.warning(
598 | "Requested Wallbox current of %s is too high. Limiting current to %s",
599 | current,
600 | upperCurrentLimit,
601 | )
602 | current = upperCurrentLimit
603 |
604 | lowerCurrentLimit = self.getWallboxValue(wallbox_index, "lowerCurrentLimit")
605 | if current < lowerCurrentLimit:
606 | _LOGGER.warning(
607 | "Requested Wallbox current of %s is too low. Limiting current to %s",
608 | current,
609 | lowerCurrentLimit,
610 | )
611 | current = lowerCurrentLimit
612 |
613 | _LOGGER.debug("Setting wallbox max charge current to %s", current)
614 |
615 | await self.hass.async_add_executor_job(
616 | self.proxy.set_wallbox_max_charge_current, current, wallbox_index
617 | )
618 |
619 | _LOGGER.debug("Successfully set the wallbox max charge current to %s", current)
620 |
621 | async def async_set_power_limits(
622 | self, max_charge: int | None, max_discharge: int | None
623 | ) -> None:
624 | """Set the given power limits and enable them."""
625 |
626 | # Validate the arguments, at least one has to be set.
627 | if max_charge is None and max_discharge is None:
628 | raise ServiceValidationError(
629 | "async_set_power_limits must be called with at least one of "
630 | "max_charge or max_discharge."
631 | )
632 |
633 | if max_charge is not None and max_charge > self.proxy.e3dc.maxBatChargePower:
634 | _LOGGER.warning(
635 | "Limiting max_charge to %s", self.proxy.e3dc.maxBatChargePower
636 | )
637 | max_charge = self.proxy.e3dc.maxBatChargePower
638 | if (
639 | max_discharge is not None
640 | and max_discharge > self.proxy.e3dc.maxBatDischargePower
641 | ):
642 | _LOGGER.warning(
643 | "Limiting max_discharge to %s", self.proxy.e3dc.maxBatDischargePower
644 | )
645 | max_discharge = self.proxy.e3dc.maxBatDischargePower
646 |
647 | _LOGGER.debug(
648 | "Enabling power limits, max_charge: %s, max_discharge: %s",
649 | max_charge,
650 | max_discharge,
651 | )
652 |
653 | await self.hass.async_add_executor_job(
654 | self.proxy.set_power_limits, True, max_charge, max_discharge, None
655 | )
656 |
657 | _LOGGER.debug("Successfully set the power limits")
658 |
659 | async def async_manual_charge(self, charge_amount_wh: int) -> None:
660 | """Start manual charging the given amount, zero will stop charging."""
661 |
662 | # Validate the arguments
663 | if charge_amount_wh < 0:
664 | raise ServiceValidationError("Charge amount must be positive or zero.")
665 |
666 | _LOGGER.debug(
667 | "Starting manual charge of: %s Wh",
668 | charge_amount_wh,
669 | )
670 |
671 | # Call RSCP service.
672 | # no update guard necessary, as we're called from a service, not an entity
673 | await self.hass.async_add_executor_job(
674 | self.proxy.start_manual_charge, charge_amount_wh
675 | )
676 |
677 | _LOGGER.debug("Manual charging start command has been sent.")
678 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/diagnostics.py:
--------------------------------------------------------------------------------
1 | """Diagnostics support for E3DC RSCP."""
2 |
3 | from __future__ import annotations
4 |
5 | from collections.abc import Callable
6 | import logging
7 | import re
8 | from traceback import format_exception
9 | from typing import Any
10 |
11 | from e3dc import E3DC
12 | from e3dc._rscpTags import RscpTag, RscpType
13 |
14 | from homeassistant.config_entries import ConfigEntry
15 | from homeassistant.core import HomeAssistant
16 |
17 | from .const import DOMAIN
18 | from .coordinator import E3DCCoordinator
19 | from .e3dc_proxy import E3DCProxy
20 |
21 | _LOGGER = logging.getLogger(__name__)
22 |
23 | _redact_regex = re.compile("(system-mac|macAddress|serial)", re.IGNORECASE)
24 |
25 |
26 | async def async_get_config_entry_diagnostics(
27 | hass: HomeAssistant, entry: ConfigEntry
28 | ) -> dict[str, Any]:
29 | """Return diagnostics for our config entry."""
30 |
31 | dumper: _DiagnosticsDumper = _DiagnosticsDumper(hass, entry)
32 | dumper.create_dump()
33 | return dumper.get_dump()
34 |
35 |
36 | class _DiagnosticsDumper:
37 | """Helper class to collect a diagnostic dump in a failsafe way."""
38 |
39 | def __init__(self, _hass: HomeAssistant, _entry: ConfigEntry):
40 | """Initialize the dumper and set up a few references."""
41 | self.hass: HomeAssistant = _hass
42 | self.entry: ConfigEntry = _entry
43 | self.coordinator: E3DCCoordinator = self.hass.data[DOMAIN][self.entry.unique_id]
44 | self.proxy: E3DCProxy = self.coordinator.proxy
45 | self.e3dc: E3DC = self.proxy.e3dc
46 | self.result: dict[str, Any] = {}
47 |
48 | def create_dump(self):
49 | """Create the dump data and redact pricate data, central call-in point."""
50 | self._collect_data()
51 | self._redact_private_information(self.result)
52 |
53 | def get_dump(self) -> dict[str, Any]:
54 | """Get the collected data."""
55 | return self.result
56 |
57 | def _collect_data(self):
58 | """Collect the individual dumped data successivley."""
59 | self.result: dict[str, Any] = {
60 | "current_data": self.coordinator.data,
61 | "get_system_info": self._query_data_for_dump(self.e3dc.get_system_info),
62 | "get_system_status": self._query_data_for_dump(self.e3dc.get_system_status),
63 | "get_powermeters": self._query_data_for_dump(self.e3dc.get_powermeters),
64 | "e3dc_config": self.proxy.e3dc_config,
65 | "poll": self._query_data_for_dump(self.e3dc.poll),
66 | "switches": self._query_data_for_dump(self.e3dc.poll_switches),
67 | "get_pvis_data": self._query_data_for_dump(self.e3dc.get_pvis_data),
68 | "get_powermeters_data": self._query_data_for_dump(
69 | self.e3dc.get_powermeters_data
70 | ),
71 | "get_wallbox_data": self._query_data_for_dump(self.e3dc.get_wallbox_data),
72 | "get_batteries_data": self._query_data_for_dump(
73 | self.e3dc.get_batteries_data
74 | ),
75 | "get_idle_periods": self._query_data_for_dump(self.e3dc.get_idle_periods),
76 | "get_power_settings": self._query_data_for_dump(
77 | self.e3dc.get_power_settings
78 | ),
79 | "EMS_REQ_GET_MANUAL_CHARGE": self._query_data_for_dump(
80 | lambda: self.e3dc.sendRequestTag(
81 | RscpTag.EMS_REQ_GET_MANUAL_CHARGE, keepAlive=True
82 | )
83 | ),
84 | "DB_REQ_HISTORY_DATA_DAY": self._query_data_for_dump(
85 | lambda: self.e3dc.sendRequest(
86 | (
87 | RscpTag.DB_REQ_HISTORY_DATA_DAY,
88 | "Container",
89 | [
90 | (
91 | RscpTag.DB_REQ_HISTORY_TIME_START,
92 | RscpType.Uint64,
93 | self.coordinator.data["db-day-startts"],
94 | ),
95 | (
96 | RscpTag.DB_REQ_HISTORY_TIME_INTERVAL,
97 | RscpType.Uint64,
98 | 86400,
99 | ),
100 | (RscpTag.DB_REQ_HISTORY_TIME_SPAN, RscpType.Uint64, 86400),
101 | ],
102 | ),
103 | keepAlive=True,
104 | )
105 | ),
106 | }
107 |
108 | def _query_data_for_dump(self, call: Callable[[], Any]) -> Any:
109 | """Query an individual data point using a lambda, protect by exception handling."""
110 | try:
111 | tmp = call()
112 | return tmp
113 | except Exception as ex: # pylint: disable=broad-exception-caught
114 | return {"exception": format_exception(ex)}
115 |
116 | def _redact_private_information(self, data: Any):
117 | """Redact data recursively so that it can be shared."""
118 |
119 | if isinstance(data, dict | list):
120 | for key, value in (
121 | data.items() if isinstance(data, dict) else enumerate(data)
122 | ):
123 | if (
124 | isinstance(value, str)
125 | and isinstance(key, str)
126 | and _redact_regex.search(key) is not None
127 | ):
128 | data[key] = f"{value[:3]}"
129 | self._redact_private_information(value)
130 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/e3dc_proxy.py:
--------------------------------------------------------------------------------
1 | """Diagnostics support for E3DC RSCP."""
2 | from __future__ import annotations
3 |
4 | from functools import wraps
5 | import logging
6 | from typing import Any
7 |
8 | from e3dc import E3DC, SendError, NotAvailableError, RSCPKeyError, AuthenticationError
9 | from e3dc._rscpLib import rscpFindTag, rscpFindTagIndex
10 | from e3dc._rscpTags import RscpTag, RscpType, PowermeterType
11 |
12 | from homeassistant.config_entries import ConfigEntry
13 | from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
14 | from homeassistant.core import HomeAssistant
15 | from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
16 |
17 | from .const import CONF_RSCPKEY
18 |
19 | _LOGGER = logging.getLogger(__name__)
20 |
21 |
22 | def e3dc_call(func):
23 | """Wrap e3dc call in boilerplate exception handling."""
24 |
25 | @wraps(func)
26 | def wrapper_handle_e3dc_ex(*args, **kwargs) -> Any:
27 | """Send a call to E3DC asynchronusly and do general exception handling."""
28 | try:
29 | return func(*args, **kwargs)
30 | except NotAvailableError as ex:
31 | _LOGGER.debug("E3DC is unavailable: %s", ex, exc_info=True)
32 | raise HomeAssistantError(
33 | "Communication Failure: E3DC mot available"
34 | ) from ex
35 | except SendError as ex:
36 | _LOGGER.debug("Communication error with E3DC: %s", ex, exc_info=True)
37 | raise HomeAssistantError(
38 | "Communication Failure: Failed to send data"
39 | ) from ex
40 | except AuthenticationError as ex:
41 | _LOGGER.debug("Failed to authenticate with E3DC: %s", ex, exc_info=True)
42 | raise ConfigEntryAuthFailed("Failed to authenticate with E3DC") from ex
43 | except RSCPKeyError as ex:
44 | _LOGGER.debug("Encryption error with E3DC, key invalid: %s", ex, exc_info=True)
45 | raise ConfigEntryAuthFailed(
46 | "Encryption Error with E3DC, key invalid"
47 | ) from ex
48 | except (HomeAssistantError, ConfigEntryAuthFailed):
49 | raise
50 | except Exception as ex:
51 | _LOGGER.debug("Fatal error when talking to E3DC: %s", ex, exc_info=True)
52 | raise HomeAssistantError("Fatal error when talking to E3DC") from ex
53 |
54 | return wrapper_handle_e3dc_ex
55 |
56 |
57 | class E3DCProxy:
58 | """Proxies requests to pye3dc, takes care of error and async handling."""
59 |
60 | def __init__(self, _hass: HomeAssistant, _config: ConfigEntry | dict[str, str]):
61 | """Initialize E3DC Proxy and connect."""
62 | # TODO: move to readonly properties
63 | self.e3dc: E3DC = None
64 | self.e3dc_config: dict[str, Any] = {}
65 | self._hass: HomeAssistant = _hass
66 | self._config: ConfigEntry = _config
67 | self._host: str
68 | self._username: str
69 | self._password: str
70 | self._rscpkey: str
71 |
72 | if isinstance(_config, ConfigEntry):
73 | self._host = self._config.data.get(CONF_HOST)
74 | self._username = self._config.data.get(CONF_USERNAME)
75 | self._password = self._config.data.get(CONF_PASSWORD)
76 | self._rscpkey = self._config.data.get(CONF_RSCPKEY)
77 | else:
78 | self._host = _config[CONF_HOST]
79 | self._username = _config[CONF_USERNAME]
80 | self._password = _config[CONF_PASSWORD]
81 | self._rscpkey = _config[CONF_RSCPKEY]
82 |
83 | @e3dc_call
84 | def connect(self, config: dict[str, Any] | None = None):
85 | """Connect to E3DC with an optional device setup."""
86 | if config is None:
87 | config = {}
88 |
89 | self.e3dc = E3DC(
90 | E3DC.CONNECT_LOCAL,
91 | username=self._username,
92 | password=self._password,
93 | ipAddress=self._host,
94 | key=self._rscpkey,
95 | configuration=config,
96 | )
97 |
98 | self.e3dc_config = config
99 |
100 | @e3dc_call
101 | def disconnect(self):
102 | """Disconnect from E3DC if connected."""
103 | if self.e3dc is None:
104 | return
105 | if self.e3dc.rscp.isConnected():
106 | self.e3dc.disconnect()
107 | self.e3dc = None
108 |
109 | @e3dc_call
110 | def get_db_data(self, timestamp: int, timespan_seconds: int) -> dict[str, Any]:
111 | """Return the statics data for the specified timespan."""
112 | return self.e3dc.get_db_data_timestamp(timestamp, timespan_seconds, True)
113 |
114 | @e3dc_call
115 | def get_manual_charge(self) -> dict[str, Any]:
116 | """Poll manual charging state."""
117 | try:
118 | data = self.e3dc.sendRequest(
119 | (RscpTag.EMS_REQ_GET_MANUAL_CHARGE, RscpType.NoneType, None), keepAlive=True
120 | )
121 |
122 | result: dict[str, Any] = {}
123 | result["active"] = rscpFindTag(data, RscpTag.EMS_MANUAL_CHARGE_ACTIVE)[2]
124 |
125 | # These seem to be kAh per individual cell, so this is considered very strange.
126 | # To get this working for a start, we assume 3,65 V per cell, taking my own unit
127 | # as a base, but this obviously will need some real work to base this on
128 | # current voltages.
129 | # Round to Watts, this should prevent negative values in the magnitude of 10^-6,
130 | # which are probably floating point errors.
131 | tmp = rscpFindTag(data, RscpTag.EMS_MANUAL_CHARGE_ENERGY_COUNTER)[2]
132 | powerfactor = 3.65
133 | result["energy"] = round(tmp * powerfactor, 3)
134 |
135 | # The timestamp seem to correctly show the UTC Date when manual charging started
136 | # Not yet enabled, just for reference.
137 | # self._mydata["manual-charge-start"] = rscpFindTag(
138 | # request_data, "EMS_MANUAL_CHARGE_LASTSTART"
139 | # )[2]
140 | except SendError:
141 | _LOGGER.debug("Failed to query manual charging data, might be related to a recent E3DC API change, ignoring the error, reverting to empty defaults.")
142 | result: dict[str, Any] = {}
143 | result["active"] = False
144 | result["energy"] = 0
145 |
146 | return result
147 |
148 | @e3dc_call
149 | def get_power_settings(self) -> dict[str, Any]:
150 | """Retrieve current power settings."""
151 | return self.e3dc.get_power_settings(keepAlive=True)
152 |
153 | @e3dc_call
154 | def get_powermeters(self) -> dict[str, Any]:
155 | """Load available powermeters from E3DC."""
156 | return self.e3dc.get_powermeters(keepAlive=True)
157 |
158 | @e3dc_call
159 | def get_wallbox_data(self, wallbox_index: int) -> dict[str, Any]:
160 | """Poll current wallbox readings."""
161 | return self.e3dc.get_wallbox_data(wbIndex=wallbox_index, keepAlive=True)
162 |
163 | @e3dc_call
164 | def get_wallbox_identification_data(self, wallbox_index: int) -> dict[str, Any]:
165 | """Get identification data for wallbox with given index."""
166 | req = self.e3dc.sendRequest(
167 | (
168 | "WB_REQ_DATA",
169 | "Container",
170 | [
171 | ("WB_INDEX", "UChar8", wallbox_index),
172 | ("WB_REQ_FIRMWARE_VERSION", "None", None),
173 | ("WB_REQ_MAC_ADDRESS", "None", None),
174 | ("WB_REQ_DEVICE_NAME", "None", None),
175 | ("WB_REQ_SERIAL", "None", None),
176 | ("WB_REQ_WALLBOX_TYPE", "None", None),
177 | ("WB_REQ_LOWER_CURRENT_LIMIT", "None", None),
178 | ("WB_REQ_UPPER_CURRENT_LIMIT", "None", None)
179 | ],
180 | ),
181 | keepAlive=True,
182 | )
183 |
184 | outObj = {
185 | "index": rscpFindTagIndex(req, "WB_INDEX"),
186 | }
187 |
188 | firmware_version = rscpFindTag(req, "WB_FIRMWARE_VERSION")
189 | if firmware_version is not None:
190 | outObj["firmwareVersion"] = rscpFindTagIndex(firmware_version, "WB_FIRMWARE_VERSION")
191 |
192 | device_name = rscpFindTag(req, "WB_DEVICE_NAME")
193 | if device_name is not None:
194 | outObj["deviceName"] = rscpFindTagIndex(device_name, "WB_DEVICE_NAME")
195 |
196 | wallbox_serial = rscpFindTag(req, "WB_SERIAL")
197 | if wallbox_serial is not None:
198 | outObj["wallboxSerial"] = rscpFindTagIndex(wallbox_serial, "WB_SERIAL")
199 |
200 | mac_address = rscpFindTag(req, "WB_MAC_ADDRESS")
201 | if mac_address is not None:
202 | outObj["macAddress"] = rscpFindTagIndex(mac_address, "WB_MAC_ADDRESS")
203 |
204 | wallbox_type = rscpFindTag(req, "WB_WALLBOX_TYPE")
205 | if wallbox_type is not None:
206 | outObj["wallboxType"] = rscpFindTagIndex(wallbox_type, "WB_WALLBOX_TYPE")
207 |
208 | lower_current_limit = rscpFindTag(req, "WB_LOWER_CURRENT_LIMIT")
209 | if lower_current_limit is not None:
210 | outObj["lowerCurrentLimit"] = rscpFindTagIndex(lower_current_limit, "WB_LOWER_CURRENT_LIMIT")
211 |
212 | upper_current_limit = rscpFindTag(req, "WB_UPPER_CURRENT_LIMIT")
213 | if upper_current_limit is not None:
214 | outObj["upperCurrentLimit"] = rscpFindTagIndex(upper_current_limit, "WB_UPPER_CURRENT_LIMIT")
215 |
216 | return outObj
217 |
218 |
219 | @e3dc_call
220 | def get_powermeters_data(self) -> dict[str, Any]:
221 | """Poll all powermeters for their current readings."""
222 | data = self.e3dc.get_powermeters_data(keepAlive=True)
223 | result: dict[str, Any] = {}
224 |
225 | # Process and aggregate the data for each found powermeter
226 | for meter in data:
227 | # skip the root powermeter
228 | if meter["type"] == PowermeterType.PM_TYPE_ROOT.value:
229 | continue
230 |
231 | # TODO: Rewrite the config so that we can index into it.
232 | for config in self.e3dc_config["powermeters"]:
233 | if meter["index"] != config["index"]:
234 | continue
235 |
236 | result[config["key"]] = (
237 | meter["power"]["L1"] + meter["power"]["L2"] + meter["power"]["L3"]
238 | )
239 |
240 | # TODO: Store the total key in the config as well.
241 | result[config["key"] + "-total"] = (
242 | meter["energy"]["L1"]
243 | + meter["energy"]["L2"]
244 | + meter["energy"]["L3"]
245 | )
246 |
247 | if config["negate-measure"]:
248 | result[config["key"]] *= -1
249 | result[config["key"] + "-total"] *= -1
250 |
251 | return result
252 |
253 | @e3dc_call
254 | def get_software_version(self) -> str:
255 | """Return the current software version of the E3DC."""
256 | return self.e3dc.sendRequestTag(RscpTag.INFO_REQ_SW_RELEASE, keepAlive=True)
257 |
258 | @e3dc_call
259 | def get_time(self) -> int:
260 | """Get current local timestamp."""
261 | return self.e3dc.sendRequestTag(RscpTag.INFO_REQ_TIME, keepAlive=True)
262 |
263 | @e3dc_call
264 | def get_timeutc(self) -> int:
265 | """Get current local timestamp."""
266 | return self.e3dc.sendRequestTag(RscpTag.INFO_REQ_UTC_TIME, keepAlive=True)
267 |
268 | @e3dc_call
269 | def get_timezone(self) -> str:
270 | """Load the E3DC Timezone."""
271 | return self.e3dc.sendRequestTag(RscpTag.INFO_REQ_TIME_ZONE, keepAlive=True)
272 |
273 | @e3dc_call
274 | def poll(self) -> dict[str, Any]:
275 | """Poll E3DC current state."""
276 | return self.e3dc.poll(keepAlive=True)
277 |
278 | @e3dc_call
279 | def start_manual_charge(self, charge_amount_wh: int) -> None:
280 | """Initiate the manual charging process, zero will stop charging."""
281 | result_data = self.e3dc.sendRequest(
282 | (RscpTag.EMS_REQ_START_MANUAL_CHARGE, RscpType.Uint32, charge_amount_wh),
283 | keepAlive=True,
284 | )
285 | result: bool = result_data[2]
286 |
287 | if not result:
288 | _LOGGER.warning("Manual charging could not be activated")
289 |
290 | @e3dc_call
291 | def set_wallbox_sun_mode(self, enabled: bool, wallbox_index: int):
292 | """Set wallbox charging mode to sun mode on/off.
293 |
294 | Args:
295 | enabled(bool): the desired state True = sun mode enabled, False = sun mode disabled
296 | wallbox_index (Optional[int]): index of the requested wallbox,
297 |
298 | Returns:
299 | nothing
300 |
301 | """
302 | result: bool = self.e3dc.set_wallbox_sunmode(enable=enabled, wbIndex=wallbox_index, keepAlive=True)
303 | if not result:
304 | raise HomeAssistantError("Failed to set wallbox to sun mode %s", enabled)
305 |
306 | @e3dc_call
307 | def set_wallbox_schuko(self, enabled: bool, wallbox_index: int):
308 | """Set wallbox power outlet (schuko) to on/off.
309 |
310 | Args:
311 | enabled(bool): the desired state True = on, False = off
312 | wallbox_index (Optional[int]): index of the requested wallbox,
313 |
314 | Returns:
315 | nothing
316 |
317 | """
318 | result: bool = self.e3dc.set_wallbox_schuko(enable=enabled, wbIndex=wallbox_index, keepAlive=True)
319 | if not result:
320 | raise HomeAssistantError("Failed to set wallbox schuko to %s", enabled)
321 |
322 | @e3dc_call
323 | def toggle_wallbox_charging(self, wallbox_index: int):
324 | """Toggle charging of the wallbox.
325 |
326 | Args:
327 | wallbox_index (Optional[int]): index of the requested wallbox,
328 |
329 | Returns:
330 | nothing
331 |
332 | """
333 | result: bool = self.e3dc.toggle_wallbox_charging(wbIndex=wallbox_index, keepAlive=True)
334 | if not result:
335 | raise HomeAssistantError("Failed to toggle wallbox charging")
336 |
337 | @e3dc_call
338 | def toggle_wallbox_phases(self, wallbox_index: int):
339 | """Toggle the phases of wallbox charging between 1 and 3 phases.
340 |
341 | Only works if "Phasen" in the portal/device is not set to Auto.
342 |
343 | Args:
344 | wallbox_index (Optional[int]): index of the requested wallbox,
345 |
346 | Returns:
347 | nothing
348 |
349 | """
350 | result: bool = self.e3dc.toggle_wallbox_phases(wbIndex=wallbox_index, keepAlive=True)
351 | if not result:
352 | raise HomeAssistantError("Failed to toggle wallbox phases")
353 |
354 | @e3dc_call
355 | def set_wallbox_max_charge_current(
356 | self, max_charge_current: int, wallbox_index: int
357 | ) -> bool:
358 | """Set the maximum charge current of the wallbox via RSCP protocol locally.
359 |
360 | Args:
361 | max_charge_current (int): maximum allowed charge current in A
362 | wallbox_index (Optional[int]): index of the requested wallbox
363 |
364 | Returns:
365 | True if success (wallbox has understood the request, but might have clipped the value)
366 | False if error
367 |
368 | """
369 | _LOGGER.debug("Wallbox %s: Setting max_charge_current to %s", wallbox_index, max_charge_current)
370 |
371 | return self.e3dc.set_wallbox_max_charge_current(
372 | max_charge_current=max_charge_current, wbIndex=wallbox_index, keepAlive=True
373 | )
374 |
375 | @e3dc_call
376 | def set_power_limits(
377 | self,
378 | enable: bool,
379 | max_charge: int | None = None,
380 | max_discharge: int | None = None,
381 | discharge_start: int | None = None,
382 | ) -> None:
383 | """Set or clear power limits."""
384 | result: int = self.e3dc.set_power_limits(
385 | enable, max_charge, max_discharge, discharge_start, True
386 | )
387 |
388 | if result == -1:
389 | raise HomeAssistantError("Failed to clear power limits")
390 | if result == 1:
391 | _LOGGER.warning("The given power limits are not optimal, continuing anyway")
392 |
393 | @e3dc_call
394 | def set_powersave(self, enabled: bool):
395 | """Set powersaving flag."""
396 | # The call would normally return the new state, however, various e3dc's
397 | # react differently here, my E3DC does not work as the way e3dc lib is
398 | # implemented, so so far we ignore the return value. If the change was
399 | # unsuccessful, the next polling cycle will reset this to the actual
400 | # value.
401 | # TODO: Find a way to deal with the powersaving api
402 | self.e3dc.set_powersave(enabled, True)
403 |
404 | @e3dc_call
405 | def set_weather_regulated_charge(self, enabled: bool):
406 | """Set weather regulated charging flag."""
407 | # The call would normally return the new state, however, various e3dc's
408 | # react differently here, my E3DC does not work as the way e3dc lib is
409 | # implemented, so so far we ignore the return value. If the change was
410 | # unsuccessful, the next polling cycle will reset this to the actual
411 | # value.
412 | # TODO: Find a way to deal with the weather regulation api
413 | self.e3dc.set_weather_regulated_charge(enabled, True)
414 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "domain": "e3dc_rscp",
3 | "name": "E3DC Remote Storage Control Protocol (Git)",
4 | "codeowners": [
5 | "@torbennehmer"
6 | ],
7 | "config_flow": true,
8 | "dependencies": [],
9 | "documentation": "https://github.com/torbennehmer/hacs-e3dc",
10 | "homekit": {},
11 | "integration_type": "device",
12 | "iot_class": "cloud_polling",
13 | "issue_tracker": "https://github.com/torbennehmer/hacs-e3dc/issues",
14 | "requirements": [
15 | "pye3dc==0.9.2"
16 | ],
17 | "ssdp": [],
18 | "version": "3.9.0",
19 | "zeroconf": []
20 | }
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/number.py:
--------------------------------------------------------------------------------
1 | """E3DC Number platform."""
2 |
3 | from collections.abc import Callable, Coroutine
4 | from dataclasses import dataclass
5 | import logging
6 | from typing import Any
7 |
8 | from homeassistant.components.number import (
9 | NumberDeviceClass,
10 | NumberEntity,
11 | NumberEntityDescription,
12 | )
13 | from homeassistant.config_entries import ConfigEntry
14 | from homeassistant.core import HomeAssistant, callback
15 | from homeassistant.const import EntityCategory
16 |
17 | from homeassistant.helpers.entity import DeviceInfo
18 | from homeassistant.helpers.entity_platform import AddEntitiesCallback
19 | from homeassistant.helpers.update_coordinator import CoordinatorEntity
20 |
21 | from .const import DOMAIN
22 | from .coordinator import E3DCCoordinator
23 |
24 | _LOGGER = logging.getLogger(__name__)
25 |
26 |
27 | @dataclass(slots=True, frozen=True)
28 | class E3DCNumberEntityDescription(NumberEntityDescription):
29 | """Derived helper for advanced configs."""
30 |
31 | async_set_native_value_action: (
32 | Callable[[E3DCCoordinator, float, int], Coroutine[Any, Any, bool]] | None
33 | ) = None
34 |
35 |
36 | async def async_setup_entry(
37 | hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
38 | ) -> None:
39 | """Initialize Number Platform."""
40 | assert isinstance(entry.unique_id, str)
41 | coordinator: E3DCCoordinator = hass.data[DOMAIN][entry.unique_id]
42 | entities: list[E3DCNumber] = []
43 |
44 | # Add Number descriptions for wallboxes
45 | for wallbox in coordinator.wallboxes:
46 | unique_id = list(wallbox["deviceInfo"]["identifiers"])[0][1]
47 | wallbox_key = wallbox["key"]
48 |
49 | wallbox_charge_current_limit_description = E3DCNumberEntityDescription(
50 | key=f"{wallbox_key}-max-charge-current",
51 | translation_key="wallbox-max-charge-current",
52 | name="Wallbox Max Charge Current",
53 | icon="mdi:current-ac",
54 | native_min_value=wallbox["lowerCurrentLimit"],
55 | native_max_value=wallbox["upperCurrentLimit"],
56 | native_step=1,
57 | device_class=NumberDeviceClass.CURRENT,
58 | entity_category=EntityCategory.CONFIG,
59 | native_unit_of_measurement="A",
60 | async_set_native_value_action=lambda coordinator, value, index=wallbox[
61 | "index"
62 | ]: coordinator.async_set_wallbox_max_charge_current(int(value), index),
63 | )
64 | entities.append(
65 | E3DCNumber(
66 | coordinator,
67 | wallbox_charge_current_limit_description,
68 | unique_id,
69 | wallbox["deviceInfo"],
70 | )
71 | )
72 |
73 | async_add_entities(entities)
74 |
75 |
76 | class E3DCNumber(CoordinatorEntity, NumberEntity):
77 | """Custom E3DC Number Implementation."""
78 |
79 | _attr_has_entity_name = True
80 |
81 | def __init__(
82 | self,
83 | coordinator: E3DCCoordinator,
84 | description: E3DCNumberEntityDescription,
85 | uid: str,
86 | device_info: DeviceInfo | None = None,
87 | ) -> None:
88 | """Initialize the Number."""
89 | super().__init__(coordinator)
90 | self.coordinator: E3DCCoordinator = coordinator
91 | self.entity_description: E3DCNumberEntityDescription = description
92 | self._attr_value = self.coordinator.data.get(self.entity_description.key)
93 | self._attr_unique_id = f"{uid}_{description.key}"
94 | if device_info is not None:
95 | self._deviceInfo = device_info
96 | else:
97 | self._deviceInfo = self.coordinator.device_info()
98 |
99 | @property
100 | def native_value(self):
101 | """Return the current value."""
102 | return self._attr_value
103 |
104 | @callback
105 | def _handle_coordinator_update(self) -> None:
106 | """Process coordinator updates."""
107 | self._attr_value = self.coordinator.data.get(self.entity_description.key)
108 | self.async_write_ha_state()
109 |
110 | async def async_set_native_value(self, value: float) -> None:
111 | """Set the number value asynchronously."""
112 | if self.entity_description.async_set_native_value_action is not None:
113 | self._attr_value = value
114 | self.async_write_ha_state()
115 | await self.entity_description.async_set_native_value_action(
116 | self.coordinator, value
117 | )
118 |
119 | @property
120 | def device_info(self) -> DeviceInfo:
121 | """Return the device information."""
122 | return self._deviceInfo
123 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/sensor.py:
--------------------------------------------------------------------------------
1 | """E3DC sensor platform."""
2 | import logging
3 | from typing import Final
4 |
5 | from e3dc._rscpTags import PowermeterType
6 |
7 | from homeassistant.components.sensor import (
8 | SensorDeviceClass,
9 | SensorEntity,
10 | SensorEntityDescription,
11 | SensorStateClass,
12 | )
13 | from homeassistant.config_entries import ConfigEntry
14 | from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfEnergy, UnitOfPower
15 | from homeassistant.core import HomeAssistant
16 | from homeassistant.helpers.entity import DeviceInfo
17 | from homeassistant.helpers.entity_platform import AddEntitiesCallback
18 | from homeassistant.helpers.typing import StateType
19 | from homeassistant.helpers.update_coordinator import CoordinatorEntity
20 |
21 | from .const import DOMAIN
22 | from .coordinator import E3DCCoordinator
23 |
24 | _LOGGER = logging.getLogger(__name__)
25 |
26 | SENSOR_DESCRIPTIONS: Final[tuple[SensorEntityDescription, ...]] = (
27 | # DIAGNOSTIC SENSORS
28 | SensorEntityDescription(
29 | key="system-derate-percent",
30 | translation_key="system-derate-percent",
31 | icon="mdi:transmission-tower-off",
32 | entity_category=EntityCategory.DIAGNOSTIC,
33 | native_unit_of_measurement=PERCENTAGE,
34 | device_class=SensorDeviceClass.POWER_FACTOR,
35 | state_class=SensorStateClass.MEASUREMENT,
36 | ),
37 | SensorEntityDescription(
38 | key="system-derate-power",
39 | translation_key="system-derate-power",
40 | icon="mdi:transmission-tower-off",
41 | entity_category=EntityCategory.DIAGNOSTIC,
42 | native_unit_of_measurement=UnitOfPower.WATT,
43 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
44 | suggested_display_precision=1,
45 | device_class=SensorDeviceClass.POWER,
46 | state_class=SensorStateClass.MEASUREMENT,
47 | entity_registry_enabled_default=False,
48 | ),
49 | SensorEntityDescription(
50 | key="system-battery-installed-capacity",
51 | translation_key="system-battery-installed-capacity",
52 | icon="mdi:battery-high",
53 | entity_category=EntityCategory.DIAGNOSTIC,
54 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
55 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
56 | suggested_display_precision=1,
57 | device_class=SensorDeviceClass.ENERGY_STORAGE,
58 | state_class=SensorStateClass.MEASUREMENT,
59 | ),
60 | SensorEntityDescription(
61 | key="system-battery-installed-peak",
62 | translation_key="system-battery-installed-peak",
63 | icon="mdi:solar-power-variant",
64 | entity_category=EntityCategory.DIAGNOSTIC,
65 | native_unit_of_measurement=UnitOfPower.WATT,
66 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
67 | suggested_display_precision=1,
68 | device_class=SensorDeviceClass.POWER,
69 | state_class=SensorStateClass.MEASUREMENT,
70 | ),
71 | SensorEntityDescription(
72 | key="system-ac-maxpower",
73 | translation_key="system-ac-maxpower",
74 | icon="mdi:solar-power-variant",
75 | entity_category=EntityCategory.DIAGNOSTIC,
76 | native_unit_of_measurement=UnitOfPower.WATT,
77 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
78 | suggested_display_precision=1,
79 | device_class=SensorDeviceClass.POWER,
80 | state_class=SensorStateClass.MEASUREMENT,
81 | entity_registry_enabled_default=False,
82 | ),
83 | SensorEntityDescription(
84 | key="system-battery-charge-max",
85 | translation_key="system-battery-charge-max",
86 | icon="mdi:battery-arrow-up-outline",
87 | entity_category=EntityCategory.DIAGNOSTIC,
88 | native_unit_of_measurement=UnitOfPower.WATT,
89 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
90 | suggested_display_precision=1,
91 | device_class=SensorDeviceClass.POWER,
92 | state_class=SensorStateClass.MEASUREMENT,
93 | ),
94 | SensorEntityDescription(
95 | key="system-battery-discharge-max",
96 | translation_key="system-battery-discharge-max",
97 | icon="mdi:battery-arrow-down-outline",
98 | entity_category=EntityCategory.DIAGNOSTIC,
99 | native_unit_of_measurement=UnitOfPower.WATT,
100 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
101 | suggested_display_precision=1,
102 | device_class=SensorDeviceClass.POWER,
103 | state_class=SensorStateClass.MEASUREMENT,
104 | ),
105 | SensorEntityDescription(
106 | key="system-mac",
107 | translation_key="system-mac",
108 | icon="mdi:ethernet",
109 | entity_category=EntityCategory.DIAGNOSTIC,
110 | entity_registry_enabled_default=False,
111 | ),
112 | SensorEntityDescription(
113 | key="pset-limit-discharge-minimum",
114 | translation_key="pset-limit-discharge-minimum",
115 | icon="mdi:battery-arrow-down-outline",
116 | entity_category=EntityCategory.DIAGNOSTIC,
117 | native_unit_of_measurement=UnitOfPower.WATT,
118 | suggested_unit_of_measurement=UnitOfPower.WATT,
119 | suggested_display_precision=0,
120 | device_class=SensorDeviceClass.POWER,
121 | state_class=SensorStateClass.MEASUREMENT,
122 | entity_registry_enabled_default=False,
123 | ),
124 | SensorEntityDescription(
125 | key="system-battery-discharge-minimum-default",
126 | translation_key="system-battery-discharge-minimum-default",
127 | icon="mdi:battery-arrow-down-outline",
128 | entity_category=EntityCategory.DIAGNOSTIC,
129 | native_unit_of_measurement=UnitOfPower.WATT,
130 | suggested_unit_of_measurement=UnitOfPower.WATT,
131 | suggested_display_precision=0,
132 | device_class=SensorDeviceClass.POWER,
133 | state_class=SensorStateClass.MEASUREMENT,
134 | entity_registry_enabled_default=False,
135 | ),
136 | # DEVICE SENSORS
137 | SensorEntityDescription(
138 | key="autarky",
139 | translation_key="autarky",
140 | icon="mdi:home-percent-outline",
141 | native_unit_of_measurement=PERCENTAGE,
142 | suggested_display_precision=0,
143 | device_class=SensorDeviceClass.POWER_FACTOR,
144 | state_class=SensorStateClass.MEASUREMENT,
145 | ),
146 | SensorEntityDescription(
147 | key="battery-charge",
148 | translation_key="battery-charge",
149 | icon="mdi:battery-charging-outline",
150 | native_unit_of_measurement=UnitOfPower.WATT,
151 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
152 | suggested_display_precision=2,
153 | device_class=SensorDeviceClass.POWER,
154 | state_class=SensorStateClass.MEASUREMENT,
155 | ),
156 | SensorEntityDescription(
157 | key="battery-netchange",
158 | translation_key="battery-netchange",
159 | icon="mdi:battery-charging",
160 | native_unit_of_measurement=UnitOfPower.WATT,
161 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
162 | suggested_display_precision=2,
163 | device_class=SensorDeviceClass.POWER,
164 | state_class=SensorStateClass.MEASUREMENT,
165 | entity_registry_enabled_default=False,
166 | ),
167 | SensorEntityDescription(
168 | key="grid-consumption",
169 | translation_key="grid-consumption",
170 | icon="mdi:transmission-tower-export",
171 | native_unit_of_measurement=UnitOfPower.WATT,
172 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
173 | suggested_display_precision=2,
174 | device_class=SensorDeviceClass.POWER,
175 | state_class=SensorStateClass.MEASUREMENT,
176 | ),
177 | SensorEntityDescription(
178 | key="house-consumption",
179 | translation_key="house-consumption",
180 | icon="mdi:home-import-outline",
181 | native_unit_of_measurement=UnitOfPower.WATT,
182 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
183 | suggested_display_precision=2,
184 | device_class=SensorDeviceClass.POWER,
185 | state_class=SensorStateClass.MEASUREMENT,
186 | ),
187 | SensorEntityDescription(
188 | key="grid-netchange",
189 | translation_key="grid-netchange",
190 | icon="mdi:battery-charging",
191 | native_unit_of_measurement=UnitOfPower.WATT,
192 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
193 | suggested_display_precision=2,
194 | device_class=SensorDeviceClass.POWER,
195 | state_class=SensorStateClass.MEASUREMENT,
196 | entity_registry_enabled_default=False,
197 | ),
198 | SensorEntityDescription(
199 | key="battery-discharge",
200 | translation_key="battery-discharge",
201 | icon="mdi:battery-arrow-down-outline",
202 | native_unit_of_measurement=UnitOfPower.WATT,
203 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
204 | suggested_display_precision=2,
205 | device_class=SensorDeviceClass.POWER,
206 | state_class=SensorStateClass.MEASUREMENT,
207 | ),
208 | SensorEntityDescription(
209 | key="additional-production",
210 | translation_key="additional-production",
211 | icon="mdi:power-plug",
212 | native_unit_of_measurement=UnitOfPower.WATT,
213 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
214 | suggested_display_precision=2,
215 | device_class=SensorDeviceClass.POWER,
216 | state_class=SensorStateClass.MEASUREMENT,
217 | entity_registry_enabled_default=False,
218 | ),
219 | SensorEntityDescription(
220 | key="grid-production",
221 | translation_key="grid-production",
222 | icon="mdi:transmission-tower-import",
223 | native_unit_of_measurement=UnitOfPower.WATT,
224 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
225 | suggested_display_precision=2,
226 | device_class=SensorDeviceClass.POWER,
227 | state_class=SensorStateClass.MEASUREMENT,
228 | ),
229 | SensorEntityDescription(
230 | key="solar-production",
231 | translation_key="solar-production",
232 | icon="mdi:solar-power",
233 | native_unit_of_measurement=UnitOfPower.WATT,
234 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
235 | suggested_display_precision=2,
236 | device_class=SensorDeviceClass.POWER,
237 | state_class=SensorStateClass.MEASUREMENT,
238 | ),
239 | SensorEntityDescription(
240 | key="selfconsumption",
241 | translation_key="selfconsumption",
242 | icon="mdi:cloud-percent-outline",
243 | native_unit_of_measurement=PERCENTAGE,
244 | suggested_display_precision=0,
245 | device_class=SensorDeviceClass.POWER_FACTOR,
246 | state_class=SensorStateClass.MEASUREMENT,
247 | ),
248 | SensorEntityDescription(
249 | key="soc",
250 | translation_key="soc",
251 | native_unit_of_measurement=PERCENTAGE,
252 | suggested_display_precision=0,
253 | device_class=SensorDeviceClass.BATTERY,
254 | state_class=SensorStateClass.MEASUREMENT,
255 | ),
256 | SensorEntityDescription(
257 | key="manual-charge-energy",
258 | translation_key="manual-charge-energy",
259 | icon="mdi:transmission-tower",
260 | native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
261 | suggested_display_precision=2,
262 | device_class=SensorDeviceClass.ENERGY,
263 | state_class=SensorStateClass.TOTAL_INCREASING,
264 | ),
265 | SensorEntityDescription(
266 | key="pset-limit-charge",
267 | translation_key="pset-limit-charge",
268 | icon="mdi:battery-arrow-up-outline",
269 | native_unit_of_measurement=UnitOfPower.WATT,
270 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
271 | suggested_display_precision=1,
272 | device_class=SensorDeviceClass.POWER,
273 | state_class=SensorStateClass.MEASUREMENT,
274 | ),
275 | SensorEntityDescription(
276 | key="pset-limit-discharge",
277 | translation_key="pset-limit-discharge",
278 | icon="mdi:battery-arrow-down-outline",
279 | native_unit_of_measurement=UnitOfPower.WATT,
280 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
281 | suggested_display_precision=1,
282 | device_class=SensorDeviceClass.POWER,
283 | state_class=SensorStateClass.MEASUREMENT,
284 | ),
285 | # LONGTERM STATISTIC SENSORS
286 | SensorEntityDescription(
287 | key="db-day-autarky",
288 | translation_key="db-day-autarky",
289 | icon="mdi:cloud-percent-outline",
290 | native_unit_of_measurement=PERCENTAGE,
291 | suggested_display_precision=0,
292 | device_class=SensorDeviceClass.POWER_FACTOR,
293 | state_class=SensorStateClass.MEASUREMENT,
294 | ),
295 | SensorEntityDescription(
296 | key="db-day-battery-charge",
297 | translation_key="db-day-battery-charge",
298 | icon="mdi:battery-charging-outline",
299 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
300 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
301 | suggested_display_precision=2,
302 | device_class=SensorDeviceClass.ENERGY,
303 | state_class=SensorStateClass.TOTAL_INCREASING,
304 | ),
305 | SensorEntityDescription(
306 | key="db-day-battery-discharge",
307 | translation_key="db-day-battery-discharge",
308 | icon="mdi:battery-arrow-down-outline",
309 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
310 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
311 | suggested_display_precision=2,
312 | device_class=SensorDeviceClass.ENERGY,
313 | state_class=SensorStateClass.TOTAL_INCREASING,
314 | ),
315 | SensorEntityDescription(
316 | key="db-day-grid-consumption",
317 | translation_key="db-day-grid-consumption",
318 | icon="mdi:transmission-tower-export",
319 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
320 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
321 | suggested_display_precision=2,
322 | device_class=SensorDeviceClass.ENERGY,
323 | state_class=SensorStateClass.TOTAL_INCREASING,
324 | ),
325 | SensorEntityDescription(
326 | key="db-day-house-consumption",
327 | translation_key="db-day-house-consumption",
328 | icon="mdi:home-import-outline",
329 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
330 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
331 | suggested_display_precision=2,
332 | device_class=SensorDeviceClass.ENERGY,
333 | state_class=SensorStateClass.TOTAL_INCREASING,
334 | ),
335 | SensorEntityDescription(
336 | key="db-day-grid-production",
337 | translation_key="db-day-grid-production",
338 | icon="mdi:transmission-tower-import",
339 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
340 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
341 | suggested_display_precision=2,
342 | device_class=SensorDeviceClass.ENERGY,
343 | state_class=SensorStateClass.TOTAL_INCREASING,
344 | ),
345 | SensorEntityDescription(
346 | key="db-day-solar-production",
347 | translation_key="db-day-solar-production",
348 | icon="mdi:solar-power",
349 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
350 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
351 | suggested_display_precision=2,
352 | device_class=SensorDeviceClass.ENERGY,
353 | state_class=SensorStateClass.TOTAL_INCREASING,
354 | ),
355 | SensorEntityDescription(
356 | key="db-day-selfconsumption",
357 | translation_key="db-day-selfconsumption",
358 | icon="mdi:cloud-percent-outline",
359 | native_unit_of_measurement=PERCENTAGE,
360 | suggested_display_precision=0,
361 | device_class=SensorDeviceClass.POWER_FACTOR,
362 | state_class=SensorStateClass.MEASUREMENT,
363 | ),
364 | )
365 |
366 |
367 | async def async_setup_entry(
368 | hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
369 | ) -> None:
370 | """Initialize Sensor Platform."""
371 | assert isinstance(entry.unique_id, str)
372 | coordinator: E3DCCoordinator = hass.data[DOMAIN][entry.unique_id]
373 | entities: list[E3DCSensor] = [
374 | E3DCSensor(coordinator, description, entry.unique_id)
375 | for description in SENSOR_DESCRIPTIONS
376 | ]
377 |
378 | # Add Sensor descriptions for additional powermeters, skipp root PM
379 | for powermeter_config in coordinator.proxy.e3dc_config["powermeters"]:
380 | if powermeter_config["type"] == PowermeterType.PM_TYPE_ROOT.value:
381 | continue
382 |
383 | energy_description = SensorEntityDescription(
384 | has_entity_name=True,
385 | name=powermeter_config["name"] + " - total",
386 | key=powermeter_config["key"] + "-total",
387 | translation_key=powermeter_config["key"] + "-total",
388 | icon="mdi:meter-electric",
389 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
390 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
391 | suggested_display_precision=2,
392 | device_class=SensorDeviceClass.ENERGY,
393 | state_class=powermeter_config["total-state-class"],
394 | )
395 | entities.append(E3DCSensor(coordinator, energy_description, entry.unique_id))
396 |
397 | power_description = SensorEntityDescription(
398 | has_entity_name=True,
399 | name=powermeter_config["name"],
400 | key=powermeter_config["key"],
401 | translation_key=powermeter_config["key"],
402 | icon="mdi:meter-electric",
403 | native_unit_of_measurement=UnitOfPower.WATT,
404 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
405 | suggested_display_precision=1,
406 | device_class=SensorDeviceClass.POWER,
407 | state_class=SensorStateClass.MEASUREMENT,
408 | )
409 | entities.append(E3DCSensor(coordinator, power_description, entry.unique_id))
410 |
411 | for wallbox in coordinator.wallboxes:
412 | # Get the UID & Key for the given wallbox
413 | unique_id = list(wallbox["deviceInfo"]["identifiers"])[0][1]
414 | wallbox_key = wallbox["key"]
415 |
416 | wallbox_app_software_description = SensorEntityDescription(
417 | key=f"{wallbox_key}-app-software",
418 | translation_key="wallbox-app-software",
419 | icon="mdi:information-outline",
420 | device_class=None,
421 | entity_registry_enabled_default=False,
422 | entity_category=EntityCategory.DIAGNOSTIC
423 | )
424 | entities.append(E3DCSensor(coordinator, wallbox_app_software_description, unique_id, wallbox["deviceInfo"]))
425 |
426 | wallbox_consumption_net_description = SensorEntityDescription(
427 | key=f"{wallbox_key}-consumption-net",
428 | translation_key="wallbox-consumption-net",
429 | icon="mdi:transmission-tower-import",
430 | native_unit_of_measurement=UnitOfPower.WATT,
431 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
432 | device_class=SensorDeviceClass.POWER,
433 | state_class=SensorStateClass.MEASUREMENT,
434 | )
435 | entities.append(E3DCSensor(coordinator, wallbox_consumption_net_description, unique_id, wallbox["deviceInfo"]))
436 |
437 | wallbox_consumption_sun_description = SensorEntityDescription(
438 | key=f"{wallbox_key}-consumption-sun",
439 | translation_key="wallbox-consumption-sun",
440 | icon="mdi:solar-power",
441 | native_unit_of_measurement=UnitOfPower.WATT,
442 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
443 | device_class=SensorDeviceClass.POWER,
444 | state_class=SensorStateClass.MEASUREMENT,
445 | )
446 | entities.append(E3DCSensor(coordinator, wallbox_consumption_sun_description, unique_id, wallbox["deviceInfo"]))
447 |
448 | wallbox_energy_all_description = SensorEntityDescription(
449 | key=f"{wallbox_key}-energy-all",
450 | translation_key="wallbox-energy-all",
451 | icon="mdi:counter",
452 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
453 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
454 | suggested_display_precision=2,
455 | device_class=SensorDeviceClass.ENERGY,
456 | state_class=SensorStateClass.TOTAL_INCREASING,
457 | )
458 | entities.append(E3DCSensor(coordinator, wallbox_energy_all_description, unique_id, wallbox["deviceInfo"]))
459 |
460 | wallbox_energy_net_description = SensorEntityDescription(
461 | key=f"{wallbox_key}-energy-net",
462 | translation_key="wallbox-energy-net",
463 | icon="mdi:counter",
464 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
465 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
466 | suggested_display_precision=2,
467 | device_class=SensorDeviceClass.ENERGY,
468 | state_class=SensorStateClass.TOTAL_INCREASING,
469 | )
470 | entities.append(E3DCSensor(coordinator, wallbox_energy_net_description, unique_id, wallbox["deviceInfo"]))
471 |
472 | wallbox_energy_sun_description = SensorEntityDescription(
473 | key=f"{wallbox_key}-energy-sun",
474 | translation_key="wallbox-energy-sun",
475 | icon="mdi:counter",
476 | native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
477 | suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
478 | suggested_display_precision=2,
479 | device_class=SensorDeviceClass.ENERGY,
480 | state_class=SensorStateClass.TOTAL_INCREASING,
481 | )
482 | entities.append(E3DCSensor(coordinator, wallbox_energy_sun_description, unique_id, wallbox["deviceInfo"]))
483 |
484 | wallbox_index_description = SensorEntityDescription(
485 | key=f"{wallbox_key}-index",
486 | translation_key="wallbox-index",
487 | icon="mdi:numeric",
488 | device_class=None,
489 | entity_registry_enabled_default=False,
490 | entity_category=EntityCategory.DIAGNOSTIC
491 | )
492 | entities.append(E3DCSensor(coordinator, wallbox_index_description, unique_id, wallbox["deviceInfo"]))
493 |
494 | wallbox_max_charge_current_description = SensorEntityDescription(
495 | key=f"{wallbox_key}-max-charge-current",
496 | translation_key="wallbox-max-charge-current",
497 | icon="mdi:current-ac",
498 | native_unit_of_measurement="A",
499 | device_class=SensorDeviceClass.CURRENT,
500 | state_class=SensorStateClass.MEASUREMENT,
501 | )
502 | entities.append(E3DCSensor(coordinator, wallbox_max_charge_current_description, unique_id, wallbox["deviceInfo"]))
503 |
504 | wallbox_phases_description = SensorEntityDescription(
505 | key=f"{wallbox_key}-phases",
506 | translation_key="wallbox-phases",
507 | icon="mdi:sine-wave",
508 | device_class=None,
509 | )
510 | entities.append(E3DCSensor(coordinator, wallbox_phases_description, unique_id, wallbox["deviceInfo"]))
511 |
512 | wallbox_soc_description = SensorEntityDescription(
513 | key=f"{wallbox_key}-soc",
514 | translation_key="wallbox-soc",
515 | icon="mdi:battery-charging",
516 | native_unit_of_measurement=PERCENTAGE,
517 | suggested_display_precision=0,
518 | device_class=SensorDeviceClass.BATTERY,
519 | state_class=SensorStateClass.MEASUREMENT,
520 | entity_registry_enabled_default=False,
521 | )
522 | entities.append(E3DCSensor(coordinator, wallbox_soc_description, unique_id, wallbox["deviceInfo"]))
523 |
524 | if len(coordinator.wallboxes) > 0:
525 | wallbox_consumption_description = SensorEntityDescription(
526 | key="wallbox-consumption",
527 | translation_key="wallbox-consumption",
528 | icon="mdi:ev-station",
529 | native_unit_of_measurement=UnitOfPower.WATT,
530 | suggested_unit_of_measurement=UnitOfPower.KILO_WATT,
531 | suggested_display_precision=2,
532 | device_class=SensorDeviceClass.POWER,
533 | state_class=SensorStateClass.MEASUREMENT,
534 | )
535 | entities.append(E3DCSensor(coordinator, wallbox_consumption_description, entry.unique_id))
536 |
537 | async_add_entities(entities)
538 |
539 |
540 | class E3DCSensor(CoordinatorEntity, SensorEntity):
541 | """Custom E3DC Sensor implementation."""
542 |
543 | _attr_has_entity_name = True
544 |
545 | def __init__(
546 | self,
547 | coordinator: E3DCCoordinator,
548 | description: SensorEntityDescription,
549 | uid: str,
550 | device_info: DeviceInfo | None = None
551 | ) -> None:
552 | """Initialize the Sensor."""
553 | super().__init__(coordinator)
554 | self.coordinator: E3DCCoordinator = coordinator
555 | self.entity_description: SensorEntityDescription = description
556 | self._attr_unique_id = f"{uid}_{description.key}"
557 | if device_info is not None:
558 | self._deviceInfo = device_info
559 | else:
560 | self._deviceInfo = self.coordinator.device_info()
561 |
562 | @property
563 | def native_value(self) -> StateType:
564 | """Return the reported sensor value."""
565 | return self.coordinator.data.get(self.entity_description.key)
566 |
567 | @property
568 | def device_info(self) -> DeviceInfo:
569 | """Return the device information."""
570 | return self._deviceInfo
571 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/services.py:
--------------------------------------------------------------------------------
1 | """Main Service interfaces, acts as proxy for actual execution."""
2 |
3 | import logging
4 |
5 | import voluptuous as vol
6 |
7 | from homeassistant.core import HomeAssistant, ServiceCall
8 | from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
9 | from homeassistant.helpers.device_registry import (
10 | DeviceEntry,
11 | DeviceRegistry,
12 | async_get,
13 | )
14 | from .const import (
15 | DOMAIN,
16 | SERVICE_SET_POWER_LIMITS,
17 | SERVICE_CLEAR_POWER_LIMITS,
18 | SERVICE_MANUAL_CHARGE,
19 | SERVICE_SET_WALLBOX_MAX_CHARGE_CURRENT,
20 | )
21 | from .coordinator import E3DCCoordinator
22 |
23 | _LOGGER = logging.getLogger(__name__)
24 | _device_map: dict[str, E3DCCoordinator] = {}
25 |
26 | ATTR_DEVICEID = "device_id"
27 | ATTR_MAX_CHARGE = "max_charge"
28 | ATTR_MAX_DISCHARGE = "max_discharge"
29 | ATTR_CHARGE_AMOUNT = "charge_amount"
30 | ATTR_MAX_CHARGE_CURRENT = "max_charge_current"
31 |
32 | SCHEMA_CLEAR_POWER_LIMITS = vol.Schema(
33 | {
34 | vol.Required(ATTR_DEVICEID): str,
35 | }
36 | )
37 |
38 | SCHEMA_SET_POWER_LIMITS = vol.Schema(
39 | {
40 | vol.Required(ATTR_DEVICEID): str,
41 | vol.Optional(ATTR_MAX_CHARGE): vol.All(int, vol.Range(min=0)),
42 | vol.Optional(ATTR_MAX_DISCHARGE): vol.All(int, vol.Range(min=0)),
43 | }
44 | )
45 |
46 | SCHEMA_SET_WALLBOX_MAX_CHARGE_CURRENT = vol.Schema(
47 | {
48 | vol.Required(ATTR_DEVICEID): str,
49 | vol.Optional(ATTR_MAX_CHARGE_CURRENT): vol.All(int, vol.Range(min=0)),
50 | }
51 | )
52 |
53 | SCHEMA_MANUAL_CHARGE = vol.Schema(
54 | {
55 | vol.Required(ATTR_DEVICEID): str,
56 | vol.Optional(ATTR_CHARGE_AMOUNT): vol.All(int, vol.Range(min=0)),
57 | }
58 | )
59 |
60 |
61 | async def async_setup_services(hass: HomeAssistant) -> None:
62 | """Central hook to register all services, called by component setup."""
63 |
64 | # hass.services.register(DOMAIN, "servicename", lambda, schema)
65 | async def async_call_set_power_limits(call: ServiceCall) -> None:
66 | await _async_set_power_limits(hass, call)
67 |
68 | hass.services.async_register(
69 | domain=DOMAIN,
70 | service=SERVICE_SET_POWER_LIMITS,
71 | service_func=async_call_set_power_limits,
72 | schema=SCHEMA_SET_POWER_LIMITS,
73 | )
74 |
75 | async def async_call_clear_power_limits(call: ServiceCall) -> None:
76 | await _async_clear_power_limits(hass, call)
77 |
78 | hass.services.async_register(
79 | domain=DOMAIN,
80 | service=SERVICE_CLEAR_POWER_LIMITS,
81 | service_func=async_call_clear_power_limits,
82 | schema=SCHEMA_CLEAR_POWER_LIMITS,
83 | )
84 |
85 | async def async_call_manual_charge(call: ServiceCall) -> None:
86 | await _async_manual_charge(hass, call)
87 |
88 | hass.services.async_register(
89 | domain=DOMAIN,
90 | service=SERVICE_MANUAL_CHARGE,
91 | service_func=async_call_manual_charge,
92 | schema=SCHEMA_MANUAL_CHARGE,
93 | )
94 |
95 | async def async_call_set_wallbox_max_charge_current(call: ServiceCall) -> None:
96 | await _async_set_wallbox_max_charge_current(hass, call)
97 |
98 | hass.services.async_register(
99 | domain=DOMAIN,
100 | service=SERVICE_SET_WALLBOX_MAX_CHARGE_CURRENT,
101 | service_func=async_call_set_wallbox_max_charge_current,
102 | schema=SCHEMA_SET_WALLBOX_MAX_CHARGE_CURRENT,
103 | )
104 |
105 |
106 | def _resolve_device_id(hass: HomeAssistant, devid: str) -> E3DCCoordinator:
107 | """Resolve a device ID to its coordinator with caching."""
108 | if devid in _device_map:
109 | return _device_map[devid]
110 | dev_reg: DeviceRegistry = async_get(hass)
111 | dev: DeviceEntry | None = dev_reg.async_get(devid)
112 | if dev is None:
113 | raise HomeAssistantError(
114 | f"{SERVICE_SET_POWER_LIMITS}: Unkown device ID {devid}."
115 | )
116 |
117 | identifier: tuple[str, str]
118 | uid: str | None = None
119 |
120 | # Follow the via device and make it the new device if it is an E3DC
121 | if dev.via_device_id is not None:
122 | via_dev = dev_reg.async_get(dev.via_device_id)
123 | if via_dev is None:
124 | raise HomeAssistantError(
125 | f"{SERVICE_SET_POWER_LIMITS}: Invalid via Device ID {devid}."
126 | )
127 | for identifier in via_dev.identifiers:
128 | domain: str = identifier[0]
129 | if domain == DOMAIN:
130 | dev = via_dev
131 |
132 | for identifier in dev.identifiers:
133 | domain: str = identifier[0]
134 | if domain == DOMAIN:
135 | uid = identifier[1]
136 | break
137 |
138 | if uid is None:
139 | raise HomeAssistantError(
140 | f"{SERVICE_SET_POWER_LIMITS}: Device {devid} is no E3DC."
141 | )
142 |
143 | coordinator: E3DCCoordinator = hass.data[DOMAIN][uid]
144 | _device_map[devid] = coordinator
145 | return coordinator
146 |
147 |
148 | def _resolve_wallbox_id(hass: HomeAssistant, devid: str) -> int | None:
149 | """Resolve a device ID to its wallbox ID."""
150 |
151 | # Get the coordinator
152 | coordinator: E3DCCoordinator = _resolve_device_id(hass, devid)
153 |
154 | # Get the wallbox Index
155 | dev_reg: DeviceRegistry = async_get(hass)
156 | dev: DeviceEntry | None = dev_reg.async_get(devid)
157 | if dev is None:
158 | raise HomeAssistantError(
159 | f"{SERVICE_SET_WALLBOX_MAX_CHARGE_CURRENT}: Unkown device ID {devid}."
160 | )
161 | for wallbox in coordinator.wallboxes:
162 | if (
163 | list(wallbox["deviceInfo"]["identifiers"])[0][1]
164 | == list(dev.identifiers)[0][1]
165 | ):
166 | return wallbox["index"]
167 |
168 | raise HomeAssistantError(
169 | f"{SERVICE_SET_WALLBOX_MAX_CHARGE_CURRENT}: Could not find a Wallbox Index for device ID {devid}."
170 | )
171 |
172 |
173 | async def _async_set_wallbox_max_charge_current(
174 | hass: HomeAssistant, call: ServiceCall
175 | ) -> None:
176 | """Extract service information and relay to coordinator."""
177 |
178 | coordinator: E3DCCoordinator = _resolve_device_id(
179 | hass, call.data.get(ATTR_DEVICEID)
180 | )
181 |
182 | wallbox_index: int | None = _resolve_wallbox_id(hass, call.data.get(ATTR_DEVICEID))
183 |
184 | if wallbox_index is None:
185 | raise ServiceValidationError(
186 | f"{SERVICE_SET_WALLBOX_MAX_CHARGE_CURRENT}: Service needs to be executed for a E3DC Wallbox!"
187 | )
188 | max_charge_current: int | None = call.data.get(ATTR_MAX_CHARGE_CURRENT)
189 | if max_charge_current is None:
190 | raise ServiceValidationError(
191 | f"{SERVICE_SET_WALLBOX_MAX_CHARGE_CURRENT}: Need to set {ATTR_MAX_CHARGE_CURRENT}"
192 | )
193 | await coordinator.async_set_wallbox_max_charge_current(
194 | current=max_charge_current, wallbox_index=wallbox_index
195 | )
196 |
197 |
198 | async def _async_set_power_limits(hass: HomeAssistant, call: ServiceCall) -> None:
199 | """Extract service information and relay to coordinator."""
200 | coordinator: E3DCCoordinator = _resolve_device_id(
201 | hass, call.data.get(ATTR_DEVICEID)
202 | )
203 | max_charge: int | None = call.data.get(ATTR_MAX_CHARGE)
204 | max_discharge: int | None = call.data.get(ATTR_MAX_DISCHARGE)
205 | if max_charge is None and max_discharge is None:
206 | raise ServiceValidationError(
207 | f"{SERVICE_SET_POWER_LIMITS}: Need to set at least one of {ATTR_MAX_CHARGE} or {ATTR_MAX_DISCHARGE}"
208 | )
209 | await coordinator.async_set_power_limits(
210 | max_charge=max_charge, max_discharge=max_discharge
211 | )
212 |
213 |
214 | async def _async_clear_power_limits(hass: HomeAssistant, call: ServiceCall) -> None:
215 | """Extract service information and relay to coordinator."""
216 | coordinator: E3DCCoordinator = _resolve_device_id(
217 | hass, call.data.get(ATTR_DEVICEID)
218 | )
219 | await coordinator.async_clear_power_limits()
220 |
221 |
222 | async def _async_manual_charge(hass: HomeAssistant, call: ServiceCall) -> None:
223 | """Extract service information and relay to coordinator."""
224 | coordinator: E3DCCoordinator = _resolve_device_id(
225 | hass, call.data.get(ATTR_DEVICEID)
226 | )
227 | charge_amount: int = call.data.get(ATTR_CHARGE_AMOUNT)
228 | await coordinator.async_manual_charge(charge_amount_wh=charge_amount)
229 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/services.yaml:
--------------------------------------------------------------------------------
1 | clear_power_limits:
2 | fields:
3 | device_id:
4 | required: true
5 | example: "64d3b74a1bcf319288844ff9e93e4010"
6 | selector:
7 | device:
8 | filter:
9 | integration: e3dc_rscp
10 |
11 | set_power_limits:
12 | fields:
13 | device_id:
14 | required: true
15 | example: "64d3b74a1bcf319288844ff9e93e4010"
16 | selector:
17 | device:
18 | filter:
19 | integration: e3dc_rscp
20 | max_charge:
21 | required: false
22 | example: "1000"
23 | selector:
24 | number:
25 | min: 0
26 | unit_of_measurement: W
27 | mode: box
28 | step: 100
29 | max_discharge:
30 | required: false
31 | example: "1000"
32 | selector:
33 | number:
34 | min: 0
35 | unit_of_measurement: W
36 | mode: box
37 | step: 100
38 |
39 | set_wallbox_max_charge_current:
40 | fields:
41 | device_id:
42 | required: true
43 | example: "64d3b74a1bcf319288844ff9e93e4010"
44 | selector:
45 | device:
46 | filter:
47 | integration: e3dc_rscp
48 | max_charge_current:
49 | required: false
50 | example: "16"
51 | selector:
52 | number:
53 | min: 0
54 | unit_of_measurement: A
55 | mode: box
56 | step: 1
57 |
58 | manual_charge:
59 | fields:
60 | device_id:
61 | required: true
62 | example: "64d3b74a1bcf319288844ff9e93e4010"
63 | selector:
64 | device:
65 | filter:
66 | integration: e3dc_rscp
67 | charge_amount:
68 | required: true
69 | example: "1000"
70 | selector:
71 | number:
72 | min: 0
73 | unit_of_measurement: Wh
74 | mode: box
75 | step: 100
76 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/strings.json:
--------------------------------------------------------------------------------
1 | {
2 | "config": {
3 | "step": {
4 | "reauth_confirm": {
5 | "title": "Updating E3DC credentials",
6 | "data": {
7 | "host": "[%key:common::config_flow::data::host%]",
8 | "username": "[%key:common::config_flow::data::username%]",
9 | "password": "[%key:common::config_flow::data::password%]",
10 | "rscpkey": "RSCP encryption key"
11 | }
12 | },
13 | "user": {
14 | "data": {
15 | "host": "[%key:common::config_flow::data::host%]",
16 | "username": "[%key:common::config_flow::data::username%]",
17 | "password": "[%key:common::config_flow::data::password%]",
18 | "rscpkey": "RSCP encryption key"
19 | }
20 | }
21 | },
22 | "error": {
23 | "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
24 | "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]"
25 | },
26 | "abort": {
27 | "already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
28 | "reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
29 | }
30 | },
31 | "entity": {
32 | "binary_sensor": {
33 | "system-additional-source-available": {
34 | "name": "Additional source"
35 | },
36 | "pset-limit-enabled": {
37 | "name": "Power limits"
38 | },
39 | "manual-charge-active": {
40 | "name": "Manual charge"
41 | },
42 | "wallbox-battery-to-car": {
43 | "name": "Battery to car"
44 | },
45 | "wallbox-charging": {
46 | "name": "Charging"
47 | },
48 | "wallbox-charging-canceled": {
49 | "name": "Charging canceled"
50 | },
51 | "wallbox-sun-mode": {
52 | "name": "Sun mode"
53 | },
54 | "wallbox-plug-lock": {
55 | "name": "Plug lock"
56 | },
57 | "wallbox-plug": {
58 | "name": "Plug"
59 | },
60 | "wallbox-schuko": {
61 | "name": "Schuko"
62 | },
63 | "wallbox-key-state": {
64 | "name": "Key state"
65 | }
66 | },
67 | "sensor": {
68 | "system-derate-percent": {
69 | "name": "Derate feed above %"
70 | },
71 | "system-derate-power": {
72 | "name": "Derate feed above W"
73 | },
74 | "system-battery-installed-capacity": {
75 | "name": "Installed battery capacity"
76 | },
77 | "system-battery-installed-peak": {
78 | "name": "Installed peak power"
79 | },
80 | "system-ac-maxpower": {
81 | "name": "Maximum AC power"
82 | },
83 | "system-battery-charge-max": {
84 | "name": "System maximum charge"
85 | },
86 | "system-battery-discharge-max": {
87 | "name": "System maximum discharge"
88 | },
89 | "system-mac": {
90 | "name": "MAC address"
91 | },
92 | "system-battery-discharge-minimum-default": {
93 | "name": "System minimum discharge"
94 | },
95 | "autarky": {
96 | "name": "Autarky"
97 | },
98 | "battery-charge": {
99 | "name": "Battery charge"
100 | },
101 | "battery-netchange": {
102 | "name": "Battery net change"
103 | },
104 | "grid-consumption": {
105 | "name": "Consumption from grid"
106 | },
107 | "house-consumption": {
108 | "name": "House consumption"
109 | },
110 | "wallbox-consumption": {
111 | "name": "Wallbox consumption"
112 | },
113 | "grid-netchange": {
114 | "name": "Transfer to/from grid"
115 | },
116 | "battery-discharge": {
117 | "name": "Battery discharge"
118 | },
119 | "grid-production": {
120 | "name": "Export to grid"
121 | },
122 | "solar-production": {
123 | "name": "Solar production"
124 | },
125 | "pset-limit-charge": {
126 | "name": "Maximum charge"
127 | },
128 | "pset-limit-discharge": {
129 | "name": "Maximum discharge"
130 | },
131 | "pset-limit-discharge-minimum": {
132 | "name": "Minimum required discharge"
133 | },
134 | "selfconsumption": {
135 | "name": "Self consumption"
136 | },
137 | "soc": {
138 | "name": "State of charge"
139 | },
140 | "db-day-autarky": {
141 | "name": "Autarky - today"
142 | },
143 | "db-day-battery-charge": {
144 | "name": "Battery charge - today"
145 | },
146 | "db-day-battery-discharge": {
147 | "name": "Battery discharge - today"
148 | },
149 | "db-day-grid-consumption": {
150 | "name": "Consumption from grid - today"
151 | },
152 | "db-day-house-consumption": {
153 | "name": "House consumption - today"
154 | },
155 | "db-day-grid-production": {
156 | "name": "Export to grid - today"
157 | },
158 | "db-day-solar-production": {
159 | "name": "Solar production - today"
160 | },
161 | "db-day-selfconsumption": {
162 | "name": "Self consumption - today"
163 | },
164 | "manual-charge-energy": {
165 | "name": "Energy charged from grid"
166 | },
167 | "undefined": {
168 | "name": "Undefined Powermeter"
169 | },
170 | "root-pm": {
171 | "name": "Root Powermeter"
172 | },
173 | "additional": {
174 | "name": "Additional powermeter"
175 | },
176 | "additional-production": {
177 | "name": "Additional production"
178 | },
179 | "additional-consumption": {
180 | "name": "Additional consumption"
181 | },
182 | "farm": {
183 | "name": "Farm"
184 | },
185 | "unused": {
186 | "name": "Unused powermeter"
187 | },
188 | "wallbox": {
189 | "name": "Wallbox"
190 | },
191 | "farm-additional": {
192 | "name": "Farm additional powermeter"
193 | },
194 | "undefined-total": {
195 | "name": "Undefined Powermeter - total"
196 | },
197 | "root-pm-total": {
198 | "name": "Root Powermeter - total"
199 | },
200 | "additional-total": {
201 | "name": "Additional Powermeter - total"
202 | },
203 | "additional-production-total": {
204 | "name": "Additional production - total"
205 | },
206 | "additional-consumption-total": {
207 | "name": "Additional consumption - total"
208 | },
209 | "farm-total": {
210 | "name": "Farm - total"
211 | },
212 | "unused-total": {
213 | "name": "Unused powermeter - total"
214 | },
215 | "wallbox-total": {
216 | "name": "Wallbox - total"
217 | },
218 | "farm-additional-total": {
219 | "name": "Farm additional powermeter - total"
220 | },
221 | "wallbox-app-software": {
222 | "name": "App software"
223 | },
224 | "wallbox-consumption-net": {
225 | "name": "Consumption net"
226 | },
227 | "wallbox-consumption-sun": {
228 | "name": "Consumption sun"
229 | },
230 | "wallbox-energy-all": {
231 | "name": "Energy all"
232 | },
233 | "wallbox-energy-net": {
234 | "name": "Energy net"
235 | },
236 | "wallbox-energy-sun": {
237 | "name": "Energy sun"
238 | },
239 | "wallbox-index": {
240 | "name": "Index"
241 | },
242 | "wallbox-max-charge-current": {
243 | "name": "Max charge current"
244 | },
245 | "wallbox-phases": {
246 | "name": "Phases"
247 | },
248 | "wallbox-soc": {
249 | "name": "State of charge"
250 | }
251 | },
252 | "switch": {
253 | "pset-weatherregulationenabled": {
254 | "name": "Weather regulation"
255 | },
256 | "pset-powersaving-enabled": {
257 | "name": "SmartPower powersaving"
258 | },
259 | "wallbox-sun-mode": {
260 | "name": "Sun mode"
261 | },
262 | "wallbox-schuko": {
263 | "name": "Schuko"
264 | }
265 | },
266 | "button": {
267 | "wallbox-toggle-wallbox-charging": {
268 | "name": "Toggle charging"
269 | },
270 | "wallbox-toggle-wallbox-phases": {
271 | "name": "Toggle phases"
272 | }
273 | },
274 | "number": {
275 | "wallbox-max-charge-current": {
276 | "name": "Max charge current"
277 | }
278 | }
279 | },
280 | "services": {
281 | "clear_power_limits": {
282 | "name": "Clear power limits",
283 | "description": "Clears any active power limit of the E3DC unit.",
284 | "fields": {
285 | "device_id": {
286 | "name": "E3DC Device ID",
287 | "description": "E3DC Device ID, take it either from the YAML-Mode on the website of out of the URL of the device configuration page."
288 | }
289 | }
290 | },
291 | "set_power_limits": {
292 | "name": "Set power limits",
293 | "description": "Sets the maximum charge/discharge limits of the E3DC unit.",
294 | "fields": {
295 | "device_id": {
296 | "name": "E3DC Device ID",
297 | "description": "E3DC Device ID, take it either from the YAML-Mode on the website of out of the URL of the device configuration page."
298 | },
299 | "max_charge": {
300 | "name": "Maximum Charge (W)",
301 | "description": "Maximum allowed battery charge in Watts."
302 | },
303 | "max_discharge": {
304 | "name": "Maximum Discharge (W)",
305 | "description": "Maximum allowed battery discharge in Watts."
306 | }
307 | }
308 | },
309 | "set_wallbox_max_charge_current": {
310 | "name": "Set Wallbox Charge Maximum",
311 | "description": "Sets the maximum charge limits of the Wallbox",
312 | "fields": {
313 | "device_id": {
314 | "name": "E3DC Device ID",
315 | "description": "E3DC Device ID, take it either from the YAML-Mode on the website of out of the URL of the device configuration page."
316 | },
317 | "max_charge_current": {
318 | "name": "Maximum Charging Current (A)",
319 | "description": "Maximum allowed Charging via Wallbox in Ampere."
320 | }
321 | }
322 | },
323 | "manual_charge": {
324 | "name": "Control manual charging",
325 | "description": "Starts or stops manual charging, set charge amount to zero to stop charging if it is running. Use this feature at your own risk. Take conversion losses, battery wear local laws/regulations and the E3DC warranty in mind when using this action. There is a rate limit on this call (once every few hours).",
326 | "fields": {
327 | "device_id": {
328 | "name": "E3DC Device ID",
329 | "description": "E3DC Device ID, take it either from the YAML-Mode on the website of out of the URL of the device configuration page."
330 | },
331 | "charge_amount": {
332 | "name": "Charge amount (Wh)",
333 | "description": "Amount to charge in Wh."
334 | }
335 | }
336 | }
337 | }
338 | }
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/switch.py:
--------------------------------------------------------------------------------
1 | """E3DC Switch platform."""
2 |
3 | from collections.abc import Callable, Coroutine
4 | from dataclasses import dataclass
5 | import logging
6 | from typing import Any, Final
7 |
8 | from homeassistant.components.switch import (
9 | SwitchDeviceClass,
10 | SwitchEntity,
11 | SwitchEntityDescription,
12 | )
13 | from homeassistant.config_entries import ConfigEntry
14 | from homeassistant.const import EntityCategory
15 | from homeassistant.core import HomeAssistant, callback
16 | from homeassistant.helpers.entity import DeviceInfo
17 | from homeassistant.helpers.entity_platform import AddEntitiesCallback
18 | from homeassistant.helpers.update_coordinator import CoordinatorEntity
19 |
20 | from .const import DOMAIN
21 | from .coordinator import E3DCCoordinator
22 |
23 | _LOGGER = logging.getLogger(__name__)
24 |
25 |
26 | @dataclass(slots=True, frozen=True)
27 | class E3DCSwitchEntityDescription(SwitchEntityDescription):
28 | """Derived helper for advanced configs."""
29 |
30 | on_icon: str | None = None
31 | off_icon: str | None = None
32 | async_turn_on_action: (
33 | Callable[[E3DCCoordinator], Coroutine[Any, Any, bool]] | None
34 | ) = None
35 | async_turn_off_action: (
36 | Callable[[E3DCCoordinator], Coroutine[Any, Any, bool]] | None
37 | ) = None
38 |
39 |
40 | SWITCHES: Final[tuple[E3DCSwitchEntityDescription, ...]] = (
41 | # CONFIG AND DIAGNOSTIC SWITCHES
42 | E3DCSwitchEntityDescription(
43 | key="pset-powersaving-enabled",
44 | translation_key="pset-powersaving-enabled",
45 | on_icon="mdi:leaf",
46 | off_icon="mdi:leaf-off",
47 | device_class=SwitchDeviceClass.SWITCH,
48 | entity_category=EntityCategory.CONFIG,
49 | async_turn_on_action=lambda coordinator: coordinator.async_set_powersave(True),
50 | async_turn_off_action=lambda coordinator: coordinator.async_set_powersave(
51 | False
52 | ),
53 | entity_registry_enabled_default=False,
54 | ),
55 | E3DCSwitchEntityDescription(
56 | key="pset-weatherregulationenabled",
57 | translation_key="pset-weatherregulationenabled",
58 | on_icon="mdi:weather-sunny",
59 | off_icon="mdi:weather-sunny-off",
60 | device_class=SwitchDeviceClass.SWITCH,
61 | entity_category=EntityCategory.CONFIG,
62 | async_turn_on_action=lambda coordinator: coordinator.async_set_weather_regulated_charge(
63 | True
64 | ),
65 | async_turn_off_action=lambda coordinator: coordinator.async_set_weather_regulated_charge(
66 | False
67 | ),
68 | ),
69 | # REGULAR SWITCHES (None yet)
70 | )
71 |
72 |
73 | async def async_setup_entry(
74 | hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
75 | ) -> None:
76 | """Initialize Switch Platform."""
77 | assert isinstance(entry.unique_id, str)
78 | coordinator: E3DCCoordinator = hass.data[DOMAIN][entry.unique_id]
79 | entities: list[E3DCSwitch] = [
80 | E3DCSwitch(coordinator, description, entry.unique_id)
81 | for description in SWITCHES
82 | ]
83 |
84 | for wallbox in coordinator.wallboxes:
85 | # Get the UID & Key for the given wallbox
86 | unique_id = list(wallbox["deviceInfo"]["identifiers"])[0][1]
87 | wallbox_key = wallbox["key"]
88 |
89 | wallbox_sun_mode_description = E3DCSwitchEntityDescription(
90 | # TODO: Figure out how the icons match the on/off state
91 | key=f"{wallbox_key}-sun-mode",
92 | translation_key="wallbox-sun-mode",
93 | name="Wallbox Sun Mode",
94 | on_icon="mdi:weather-sunny",
95 | off_icon="mdi:weather-sunny-off",
96 | device_class=SwitchDeviceClass.SWITCH,
97 | async_turn_on_action=lambda coordinator, index=wallbox[
98 | "index"
99 | ]: coordinator.async_set_wallbox_sun_mode(True, index),
100 | async_turn_off_action=lambda coordinator, index=wallbox[
101 | "index"
102 | ]: coordinator.async_set_wallbox_sun_mode(False, index),
103 | )
104 | entities.append(
105 | E3DCSwitch(
106 | coordinator,
107 | wallbox_sun_mode_description,
108 | unique_id,
109 | wallbox["deviceInfo"],
110 | )
111 | )
112 |
113 | wallbox_schuko_description = E3DCSwitchEntityDescription(
114 | key=f"{wallbox_key}-schuko",
115 | translation_key="wallbox-schuko",
116 | name="Wallbox Schuko",
117 | on_icon="mdi:power-plug",
118 | off_icon="mdi:power-plug-off",
119 | device_class=SwitchDeviceClass.OUTLET,
120 | async_turn_on_action=lambda coordinator, index=wallbox[
121 | "index"
122 | ]: coordinator.async_set_wallbox_schuko(True, index),
123 | async_turn_off_action=lambda coordinator, index=wallbox[
124 | "index"
125 | ]: coordinator.async_set_wallbox_schuko(False, index),
126 | entity_registry_enabled_default=False, # Disabled per default as only Wallbox multi connect I provides this feature
127 | )
128 | entities.append(
129 | E3DCSwitch(
130 | coordinator,
131 | wallbox_schuko_description,
132 | unique_id,
133 | wallbox["deviceInfo"],
134 | )
135 | )
136 |
137 | async_add_entities(entities)
138 |
139 |
140 | class E3DCSwitch(CoordinatorEntity, SwitchEntity):
141 | """Custom E3DC Switch Implementation."""
142 |
143 | _attr_has_entity_name = True
144 |
145 | def __init__(
146 | self,
147 | coordinator: E3DCCoordinator,
148 | description: E3DCSwitchEntityDescription,
149 | uid: str,
150 | device_info: DeviceInfo | None = None,
151 | ) -> None:
152 | """Initialize the Switch."""
153 | super().__init__(coordinator)
154 | self.coordinator: E3DCCoordinator = coordinator
155 | self.entity_description: E3DCSwitchEntityDescription = description
156 | self._attr_is_on = self.coordinator.data.get(self.entity_description.key)
157 | self._attr_unique_id = f"{uid}_{description.key}"
158 | self._has_custom_icons: bool = (
159 | self.entity_description.on_icon is not None
160 | and self.entity_description.off_icon is not None
161 | )
162 | if device_info is not None:
163 | self._deviceInfo = device_info
164 | else:
165 | self._deviceInfo = self.coordinator.device_info()
166 |
167 | @property
168 | def icon(self) -> str | None:
169 | """Return dynamic icon reference."""
170 | if self._has_custom_icons:
171 | return (
172 | self.entity_description.on_icon
173 | if (self.is_on)
174 | else self.entity_description.off_icon
175 | )
176 |
177 | return self._attr_icon
178 |
179 | @callback
180 | def _handle_coordinator_update(self) -> None:
181 | """Process coordinator updates."""
182 | self._attr_is_on = self.coordinator.data.get(self.entity_description.key)
183 | self.async_write_ha_state()
184 |
185 | async def async_turn_on(self, **kwargs: Any) -> None:
186 | """Turn off the switch asynchronnously."""
187 | if self.entity_description.async_turn_on_action is not None:
188 | self._attr_is_on = True
189 | self.async_write_ha_state()
190 | await self.entity_description.async_turn_on_action(self.coordinator)
191 |
192 | async def async_turn_off(self, **kwargs: Any) -> None:
193 | """Turn on the switch asynchronnously."""
194 | if self.entity_description.async_turn_off_action is not None:
195 | self._attr_is_on = False
196 | self.async_write_ha_state()
197 | await self.entity_description.async_turn_off_action(self.coordinator)
198 |
199 | @property
200 | def device_info(self) -> DeviceInfo:
201 | """Return the device information."""
202 | return self._deviceInfo
203 |
--------------------------------------------------------------------------------
/custom_components/e3dc_rscp/translations/en.json:
--------------------------------------------------------------------------------
1 | {
2 | "config": {
3 | "abort": {
4 | "already_configured": "Device is already configured",
5 | "reauth_successful": "Re-authentication was successful"
6 | },
7 | "error": {
8 | "cannot_connect": "Failed to connect",
9 | "invalid_auth": "Invalid authentication"
10 | },
11 | "step": {
12 | "reauth_confirm": {
13 | "data": {
14 | "host": "Host",
15 | "password": "Password",
16 | "rscpkey": "RSCP encryption key",
17 | "username": "Username"
18 | },
19 | "title": "Updating E3DC credentials"
20 | },
21 | "user": {
22 | "data": {
23 | "host": "Host",
24 | "password": "Password",
25 | "rscpkey": "RSCP encryption key",
26 | "username": "Username"
27 | }
28 | }
29 | }
30 | },
31 | "entity": {
32 | "binary_sensor": {
33 | "system-additional-source-available": {
34 | "name": "Additional source"
35 | },
36 | "pset-limit-enabled": {
37 | "name": "Power limits"
38 | },
39 | "manual-charge-active": {
40 | "name": "Manual charge"
41 | },
42 | "wallbox-battery-to-car": {
43 | "name": "Battery to car"
44 | },
45 | "wallbox-charging-canceled": {
46 | "name": "Charging canceled"
47 | },
48 | "wallbox-sun-mode": {
49 | "name": "Sun mode"
50 | },
51 | "wallbox-key-state": {
52 | "name": "Key state"
53 | },
54 | "wallbox-plug-lock": {
55 | "name": "Plug lock"
56 | },
57 | "wallbox-plug": {
58 | "name": "Plug"
59 | },
60 | "wallbox-schuko": {
61 | "name": "Schuko"
62 | },
63 | "wallbox-charging": {
64 | "name": "Charging"
65 | }
66 | },
67 | "sensor": {
68 | "system-derate-percent": {
69 | "name": "Derate feed above %"
70 | },
71 | "system-derate-power": {
72 | "name": "Derate feed above W"
73 | },
74 | "system-battery-installed-capacity": {
75 | "name": "Installed battery capacity"
76 | },
77 | "system-battery-installed-peak": {
78 | "name": "Installed peak power"
79 | },
80 | "system-ac-maxpower": {
81 | "name": "Maximum AC power"
82 | },
83 | "system-battery-charge-max": {
84 | "name": "System maximum charge"
85 | },
86 | "system-battery-discharge-max": {
87 | "name": "System maximum discharge"
88 | },
89 | "system-mac": {
90 | "name": "MAC address"
91 | },
92 | "system-battery-discharge-minimum-default": {
93 | "name": "System minimum discharge"
94 | },
95 | "autarky": {
96 | "name": "Autarky"
97 | },
98 | "battery-charge": {
99 | "name": "Battery charge"
100 | },
101 | "battery-netchange": {
102 | "name": "Battery net change"
103 | },
104 | "grid-consumption": {
105 | "name": "Consumption from grid"
106 | },
107 | "house-consumption": {
108 | "name": "House consumption"
109 | },
110 | "wallbox-consumption": {
111 | "name": "Wallbox consumption"
112 | },
113 | "grid-netchange": {
114 | "name": "Transfer to/from grid"
115 | },
116 | "battery-discharge": {
117 | "name": "Battery discharge"
118 | },
119 | "grid-production": {
120 | "name": "Export to grid"
121 | },
122 | "solar-production": {
123 | "name": "Solar production"
124 | },
125 | "pset-limit-charge": {
126 | "name": "Maximum charge"
127 | },
128 | "pset-limit-discharge": {
129 | "name": "Maximum discharge"
130 | },
131 | "pset-limit-discharge-minimum": {
132 | "name": "Minimum required discharge"
133 | },
134 | "selfconsumption": {
135 | "name": "Self consumption"
136 | },
137 | "soc": {
138 | "name": "State of charge"
139 | },
140 | "db-day-autarky": {
141 | "name": "Autarky - today"
142 | },
143 | "db-day-battery-charge": {
144 | "name": "Battery charge - today"
145 | },
146 | "db-day-battery-discharge": {
147 | "name": "Battery discharge - today"
148 | },
149 | "db-day-grid-consumption": {
150 | "name": "Consumption from grid - today"
151 | },
152 | "db-day-house-consumption": {
153 | "name": "House consumption - today"
154 | },
155 | "db-day-grid-production": {
156 | "name": "Export to grid - today"
157 | },
158 | "db-day-solar-production": {
159 | "name": "Solar production - today"
160 | },
161 | "db-day-selfconsumption": {
162 | "name": "Self consumption - today"
163 | },
164 | "manual-charge-energy": {
165 | "name": "Energy charged from grid"
166 | },
167 | "undefined": {
168 | "name": "Undefined Powermeter"
169 | },
170 | "root-pm": {
171 | "name": "Root Powermeter"
172 | },
173 | "additional": {
174 | "name": "Additional powermeter"
175 | },
176 | "additional-production": {
177 | "name": "Additional production"
178 | },
179 | "additional-consumption": {
180 | "name": "Additional consumption"
181 | },
182 | "farm": {
183 | "name": "Farm"
184 | },
185 | "unused": {
186 | "name": "Unused powermeter"
187 | },
188 | "wallbox": {
189 | "name": "Wallbox"
190 | },
191 | "farm-additional": {
192 | "name": "Farm additional powermeter"
193 | },
194 | "undefined-total": {
195 | "name": "Undefined Powermeter - total"
196 | },
197 | "root-pm-total": {
198 | "name": "Root Powermeter - total"
199 | },
200 | "additional-total": {
201 | "name": "Additional Powermeter - total"
202 | },
203 | "additional-production-total": {
204 | "name": "Additional production - total"
205 | },
206 | "additional-consumption-total": {
207 | "name": "Additional consumption - total"
208 | },
209 | "farm-total": {
210 | "name": "Farm - total"
211 | },
212 | "unused-total": {
213 | "name": "Unused powermeter - total"
214 | },
215 | "wallbox-total": {
216 | "name": "Wallbox - total"
217 | },
218 | "farm-additional-total": {
219 | "name": "Farm additional powermeter - total"
220 | },
221 | "wallbox-app-software": {
222 | "name": "App software"
223 | },
224 | "wallbox-consumption-net": {
225 | "name": "Consumption net"
226 | },
227 | "wallbox-consumption-sun": {
228 | "name": "Consumption sun"
229 | },
230 | "wallbox-energy-all": {
231 | "name": "Energy all"
232 | },
233 | "wallbox-energy-net": {
234 | "name": "Energy net"
235 | },
236 | "wallbox-energy-sun": {
237 | "name": "Energy sun"
238 | },
239 | "wallbox-index": {
240 | "name": "Index"
241 | },
242 | "wallbox-max-charge-current": {
243 | "name": "Max charge current"
244 | },
245 | "wallbox-phases": {
246 | "name": "Phases"
247 | },
248 | "wallbox-soc": {
249 | "name": "State of charge"
250 | }
251 | },
252 | "switch": {
253 | "pset-weatherregulationenabled": {
254 | "name": "Weather regulation"
255 | },
256 | "pset-powersaving-enabled": {
257 | "name": "SmartPower powersaving"
258 | },
259 | "wallbox-sun-mode": {
260 | "name": "Sun mode"
261 | },
262 | "wallbox-schuko": {
263 | "name": "Schuko"
264 | }
265 | },
266 | "button": {
267 | "wallbox-toggle-wallbox-charging": {
268 | "name": "Toggle charging"
269 | },
270 | "wallbox-toggle-wallbox-phases": {
271 | "name": "Toggle phases"
272 | }
273 | },
274 | "number": {
275 | "wallbox-max-charge-current": {
276 | "name": "Max charge current"
277 | }
278 | }
279 | },
280 | "services": {
281 | "clear_power_limits": {
282 | "name": "Clear power limits",
283 | "description": "Clears any active power limit of the E3DC unit.",
284 | "fields": {
285 | "device_id": {
286 | "name": "E3DC Device ID",
287 | "description": "E3DC Device ID, take it either from the YAML-Mode on the website of out of the URL of the device configuration page."
288 | }
289 | }
290 | },
291 | "set_power_limits": {
292 | "name": "Set power limits",
293 | "description": "Sets the maximum charge/discharge limits of the E3DC unit.",
294 | "fields": {
295 | "device_id": {
296 | "name": "E3DC Device ID",
297 | "description": "E3DC Device ID, take it either from the YAML-Mode on the website of out of the URL of the device configuration page."
298 | },
299 | "max_charge": {
300 | "name": "Maximum Charge (W)",
301 | "description": "Maximum allowed battery charge in Watts."
302 | },
303 | "max_discharge": {
304 | "name": "Maximum Discharge (W)",
305 | "description": "Maximum allowed battery discharge in Watts."
306 | }
307 | }
308 | },
309 | "set_wallbox_max_charge_current": {
310 | "name": "Set Wallbox Charge Maximum",
311 | "description": "Sets the maximum charge limits of the Wallbox",
312 | "fields": {
313 | "device_id": {
314 | "name": "E3DC Device ID",
315 | "description": "E3DC Device ID, take it either from the YAML-Mode on the website of out of the URL of the device configuration page."
316 | },
317 | "max_charge_current": {
318 | "name": "Maximum Charging Current (A)",
319 | "description": "Maximum allowed Charging via Wallbox in Ampere."
320 | }
321 | }
322 | },
323 | "manual_charge": {
324 | "name": "Control manual charging",
325 | "description": "Starts or stops manual charging, set charge amount to zero to stop charging if it is running. Use this feature at your own risk. Take conversion losses, battery wear local laws/regulations and the E3DC warranty in mind when using this action. There is a rate limit on this call (once every few hours).",
326 | "fields": {
327 | "device_id": {
328 | "name": "E3DC Device ID",
329 | "description": "E3DC Device ID, take it either from the YAML-Mode on the website of out of the URL of the device configuration page."
330 | },
331 | "charge_amount": {
332 | "name": "Charge amount (Wh)",
333 | "description": "Amount to charge in Wh."
334 | }
335 | }
336 | }
337 | }
338 | }
--------------------------------------------------------------------------------
/hacs.json:
--------------------------------------------------------------------------------
1 | {
2 | "filename": "hacs-e3dc_rscp.zip",
3 | "hide_default_branch": true,
4 | "homeassistant": "2025.1.0",
5 | "name": "E3DC Remote Storage Control Protocol (Git)",
6 | "render_readme": true,
7 | "zip_release": true
8 | }
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | homeassistant>=2025.1.0
2 | colorlog==6.9.0
3 | pip>=24.1.1,<24.4
4 | ruff==0.8.4
5 | pye3dc==0.9.2
6 |
--------------------------------------------------------------------------------
/scripts/develop:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -e
4 |
5 | cd "$(dirname "$0")/.."
6 |
7 | # Create config dir if not present
8 | if [[ ! -d "${PWD}/config" ]]; then
9 | mkdir -p "${PWD}/config"
10 | hass --config "${PWD}/config" --script ensure_config
11 | fi
12 |
13 | # Set the path to custom_components
14 | ## This let's us have the structure we want /custom_components/integration_blueprint
15 | ## while at the same time have Home Assistant configuration inside /config
16 | ## without resulting to symlinks.
17 | export PYTHONPATH="${PYTHONPATH}:/home/vscode/.local/lib/python3.13/site-packages/:${PWD}/custom_components"
18 |
19 | # Start Home Assistant
20 | hass --config "${PWD}/config" --debug
21 |
--------------------------------------------------------------------------------
/scripts/lint:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -e
4 |
5 | cd "$(dirname "$0")/.."
6 |
7 | ruff check . --fix
8 |
--------------------------------------------------------------------------------
/scripts/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -e
4 |
5 | cd "$(dirname "$0")/.."
6 |
7 | python3 -m pip install --requirement requirements.txt
8 |
--------------------------------------------------------------------------------