diff --git a/.devcontainer.json b/.devcontainer.json new file mode 100644 index 0000000..53d6cdf --- /dev/null +++ b/.devcontainer.json @@ -0,0 +1,43 @@ +{ + "name": "ludeeus/integration_blueprint", + "image": "mcr.microsoft.com/vscode/devcontainers/python:0-3.11-bullseye", + "postCreateCommand": "scripts/setup", + "appPort": [ + "9129:8123" + ], + "portsAttributes": { + "8123": { + "label": "Home Assistant - Webasto Connect", + "onAutoForward": "notify" + } + }, + "customizations": { + "vscode": { + "extensions": [ + "ms-python.python", + "github.vscode-pull-request-github", + "ryanluker.vscode-coverage-gutters", + "ms-python.vscode-pylance", + "ms-python.black-formatter" + ], + "settings": { + "files.eol": "\n", + "editor.tabSize": 4, + "python.pythonPath": "/usr/bin/python3", + "python.analysis.autoSearchPaths": false, + "python.linting.pylintEnabled": true, + "python.linting.enabled": true, + "python.formatting.provider": "black", + "python.formatting.blackPath": "/usr/local/py-utils/bin/black", + "editor.formatOnPaste": false, + "editor.formatOnSave": true, + "editor.formatOnType": true, + "files.trimTrailingWhitespace": true + } + } + }, + "remoteUser": "root", + "features": { + "ghcr.io/devcontainers/features/rust:1": {} + } +} \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..94f480d --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..3ba13e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 0000000..04a46f3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,29 @@ +name: Feature request +description: Make a request for a new feature in the Webasto Connect (ThermoConnect) integration +title: "[FR]: " +labels: ["feature request"] +body: + - type: markdown + attributes: + value: | + This form is only for requesting new features to the integration. + + Remember to add a descriptive title after the predefined text. + - type: textarea + validations: + required: true + attributes: + label: Describe the feature you wish to make a request for + description: >- + Provide a clear and concise description of what you wish for. + The more precise and detailed the more likely it is to be accepted and made. + - type: textarea + attributes: + label: Describe alternatives you've considered + description: >- + Have you considered any alternatives (ie. other existing integrations that can handle this) + - type: textarea + attributes: + label: Additional context + description: >- + Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/issue.yml b/.github/ISSUE_TEMPLATE/issue.yml new file mode 100644 index 0000000..7c1168d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/issue.yml @@ -0,0 +1,84 @@ +name: Report a bug / issue +description: Report an issue with the Webasto Connect (ThermoConnect) integration +labels: ["bug"] +assignees: + - MTrab +body: + - type: markdown + attributes: + value: | + This issue form is for reporting bugs only! + - type: textarea + validations: + required: true + attributes: + label: Describe the issue + description: >- + Describe the issue you are experiencing here. + Describe what you were trying to do and what happened. + + Provide a clear and concise description of what the problem is. + - type: markdown + attributes: + value: | + ## Environment + - type: input + id: version + validations: + required: true + attributes: + label: What version of Home Assistant Core has the issue? + placeholder: core- + description: > + Can be found in: [Settings ⇒ System ⇒ Repairs ⇒ Three Dots in Upper Right ⇒ System information](https://my.home-assistant.io/redirect/system_health/). + + [![Open your Home Assistant instance and show the system information.](https://my.home-assistant.io/badges/system_health.svg)](https://my.home-assistant.io/redirect/system_health/) + - type: input + attributes: + label: What was the last working version of Home Assistant Core? + placeholder: core- + description: > + If known, otherwise leave blank. + - type: dropdown + validations: + required: true + attributes: + label: What type of installation are you running? + description: > + Can be found in: [Settings ⇒ System ⇒ Repairs ⇒ Three Dots in Upper Right ⇒ System information](https://my.home-assistant.io/redirect/system_health/). + + [![Open your Home Assistant instance and show the system information.](https://my.home-assistant.io/badges/system_health.svg)](https://my.home-assistant.io/redirect/system_health/) + options: + - Home Assistant OS + - Home Assistant Container + - Home Assistant Supervised + - Home Assistant Core + - type: markdown + attributes: + value: | + # Details + - type: textarea + validations: + required: true + attributes: + label: Diagnostics information + placeholder: "drag-and-drop the diagnostics data file here (do not copy-and-paste the content)" + description: >- + This integrations provide the ability to [download diagnostic data](https://www.home-assistant.io/docs/configuration/troubleshooting/#debug-logs-and-diagnostics). + + **It would really help if you could download the diagnostics data for the device you are having issues with, + and drag-and-drop that file into the textbox below.** + + It generally allows pinpointing defects and thus resolving issues faster. + + If you are unable to provide the diagnostics (ie. you cannot add the integration), please write **None** in this field. + - type: textarea + attributes: + label: Anything in the logs that might be useful for us? + description: For example, error message, or stack traces. + render: txt + - type: textarea + attributes: + label: Additional information + description: > + If you have any additional information for us, use the field below. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..7d09d6d --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,28 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: daily + labels: + - dependencies + - patch + - skip-changelog + - package-ecosystem: pip + directory: "/.github/workflows" + schedule: + interval: daily + labels: + - dependencies + - patch + - skip-changelog + - package-ecosystem: pip + directory: "/" + schedule: + interval: daily + time: "04:00" + labels: + - dependencies + - patch + ignore: + - dependency-name: "homeassistant" diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 0000000..d49c12f --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,61 @@ +name-template: 'v$RESOLVED_VERSION' +tag-template: 'v$RESOLVED_VERSION' +change-template: '- #$NUMBER $TITLE @$AUTHOR' +sort-direction: ascending +exclude-labels: + - 'skip-changelog' +categories: + - title: '⚒️ Breaking Changes' + labels: + - breaking-change + + - title: '🚀 Features' + labels: + - 'feature request' + - 'enhancement' + + - title: '🐛 Bug Fixes' + labels: + - 'fix' + - 'bugfix' + - 'bug' + + - title: '🧬 Changes to Charge Owner informations' + labels: + - chargeowner + - chargeowners + + - title: '🧬 New Charge Owner(s) added' + labels: + - 'new chargeowner' + + - title: '🧰 Maintenance' + label: 'chore' + + - title: '📦 Dependencies' + labels: + - 'dependencies' + +version-resolver: + major: + labels: + - 'major' + minor: + labels: + - 'minor' + patch: + labels: + - 'patch' + default: patch +template: | + ## Changes + + $CHANGES + +autolabeler: + - label: 'bug' + branch: + - '/fix\/.+/' + - label: 'feature request' + branch: + - '/feature\/.+/' diff --git a/.github/scripts/update_hacs_manifest.py b/.github/scripts/update_hacs_manifest.py new file mode 100644 index 0000000..6456a77 --- /dev/null +++ b/.github/scripts/update_hacs_manifest.py @@ -0,0 +1,75 @@ +"""Update the manifest file.""" +import json +import os +import sys + + +def update_manifest(): + """Update the manifest file.""" + version = "0.0.0" + manifest_path = False + dorequirements = False + + for index, value in enumerate(sys.argv): + if value in ["--version", "-V"]: + version = str(sys.argv[index + 1]).replace("v", "") + if value in ["--path", "-P"]: + manifest_path = str(sys.argv[index + 1])[1:-1] + if value in ["--requirements", "-R"]: + dorequirements = True + + if not manifest_path: + sys.exit("Missing path to manifest file") + + with open( + f"{os.getcwd()}/{manifest_path}/manifest.json", + encoding="UTF-8", + ) as manifestfile: + manifest = json.load(manifestfile) + + manifest["version"] = version + + if dorequirements: + requirements = [] + with open( + f"{os.getcwd()}/requirements.txt", + encoding="UTF-8", + ) as file: + for line in file: + requirements.append(line.rstrip()) + + new_requirements = [] + for requirement in requirements: + req = requirement.split("==")[0].lower() + new_requirements = [ + requirement + for x in manifest["requirements"] + if x.lower().startswith(req) + ] + new_requirements += [ + x for x in manifest["requirements"] if not x.lower().startswith(req) + ] + manifest["requirements"] = new_requirements + + with open( + f"{os.getcwd()}/{manifest_path}/manifest.json", + "w", + encoding="UTF-8", + ) as manifestfile: + manifestfile.write( + json.dumps( + { + "domain": manifest["domain"], + "name": manifest["name"], + **{ + k: v + for k, v in sorted(manifest.items()) + if k not in ("domain", "name") + }, + }, + indent=4, + ) + ) + + +update_manifest() diff --git a/.github/workflows/format-code.yml b/.github/workflows/format-code.yml new file mode 100644 index 0000000..32ab2e2 --- /dev/null +++ b/.github/workflows/format-code.yml @@ -0,0 +1,44 @@ +name: Format code + +on: + push: + branches: + - master + +jobs: + format: + name: Format with black and isort + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Python 3.8 + uses: actions/setup-python@v4.7.0 + with: + python-version: 3.8 + - name: Cache + uses: actions/cache@v3.3.2 + with: + path: ~/.cache/pip + key: pip-format + - name: Install dependencies + run: | + python -m pip install --upgrade pip wheel + python -m pip install --upgrade black isort + - name: Pull again + run: git pull || true + - name: Run formatting + run: | + python -m isort -v --multi-line 3 --trailing-comma -l 88 --recursive . + python -m black -v . + - name: Commit files + run: | + if [ $(git diff HEAD | wc -l) -gt 30 ] + then + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git config user.name "GitHub Actions" + git commit -m "Run formatting" -a || true + git push || true + fi \ No newline at end of file diff --git a/.github/workflows/hacs-validate.yml b/.github/workflows/hacs-validate.yml new file mode 100644 index 0000000..a111ae3 --- /dev/null +++ b/.github/workflows/hacs-validate.yml @@ -0,0 +1,28 @@ +name: Code validation + +on: + push: + pull_request: + schedule: + - cron: "0 0 * * *" + +jobs: + validate-hassfest: + name: Hassfest validation + runs-on: ubuntu-latest + steps: + - name: checkout + uses: actions/checkout@v4 + - name: validation + uses: home-assistant/actions/hassfest@master + + validate-hacs: + name: HACS validation + runs-on: "ubuntu-latest" + steps: + - name: checkout + uses: "actions/checkout@v4" + - name: validation + uses: "hacs/action@main" + with: + category: "integration" \ No newline at end of file diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml new file mode 100644 index 0000000..c391d2c --- /dev/null +++ b/.github/workflows/release-drafter.yml @@ -0,0 +1,25 @@ +name: Release Drafter + +on: + workflow_dispatch: + push: + branches: + - master + pull_request: + types: [opened, reopened, synchronize] + +jobs: + update_release_draft: + name: Update release draft + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Create Release + uses: release-drafter/release-drafter@v5 + with: + disable-releaser: github.ref != 'refs/heads/main' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..8e8a9e7 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,39 @@ +name: Release + +on: + workflow_dispatch: + release: + types: [published] + +env: + COMPONENT_DIR: webastoconnect + +jobs: + release_zip_file: + name: Prepare release asset + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + - name: Update manifest.json version to ${{ github.event.release.tag_name }} + run: | + python3 ${{ github.workspace }}/.github/scripts/update_hacs_manifest.py --version ${{ github.event.release.tag_name }} --path /custom_components/energidataservice/ + - name: Commit manifest update + run: | + git config user.name github-actions + git config user.email github-actions@github.com + git add ./custom_components/webastoconnect/manifest.json + git commit -m "Updated manifest.json" + git push origin HEAD:master + - name: Create zip + run: | + cd custom_components/webastoconnect + zip webastoconnect.zip -r ./ + - name: Upload zip to release + uses: svenstaro/upload-release-action@2.7.0 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: ./custom_components/webastoconnect/webastoconnect.zip + asset_name: webastoconnect.zip + tag: ${{ github.ref }} + overwrite: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..98417a3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +# artifacts +__pycache__ +.pytest* +*.egg-info +*/build/* +*/dist/* + + +# misc +.coverage +.vscode +coverage.xml +notes.txt + + +# Home Assistant configuration +config/* +!config/configuration.yaml \ No newline at end of file diff --git a/.ruff.toml b/.ruff.toml new file mode 100644 index 0000000..65bb225 --- /dev/null +++ b/.ruff.toml @@ -0,0 +1,48 @@ +# The contents of this file is based on https://github.com/home-assistant/core/blob/dev/pyproject.toml + +target-version = "py311" + +select = [ + "B007", # Loop control variable {name} not used within loop body + "B014", # Exception handler with duplicate exception + "C", # complexity + "D", # docstrings + "E", # pycodestyle + "F", # pyflakes/autoflake + "ICN001", # import concentions; {name} should be imported as {asname} + "PGH004", # Use specific rule codes when using noqa + "PLC0414", # Useless import alias. Import alias does not rename original package. + "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass + "SIM117", # Merge with-statements that use the same scope + "SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys() + "SIM201", # Use {left} != {right} instead of not {left} == {right} + "SIM212", # Use {a} if {a} else {b} instead of {b} if not {a} else {a} + "SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'. + "SIM401", # Use get from dict with default instead of an if block + "T20", # flake8-print + "TRY004", # Prefer TypeError exception for invalid type + "RUF006", # Store a reference to the return value of asyncio.create_task + "UP", # pyupgrade + "W", # pycodestyle +] + +ignore = [ + "D202", # No blank lines allowed after function docstring + "D203", # 1 blank line required before class docstring + "D213", # Multi-line docstring summary should start at the second line + "D404", # First word of the docstring should not be This + "D406", # Section name should end with a newline + "D407", # Section name underlining + "D411", # Missing blank line before section + "E501", # line too long + "E731", # do not assign a lambda expression, use a def +] + +[flake8-pytest-style] +fixture-parentheses = false + +[pyupgrade] +keep-runtime-typing = true + +[mccabe] +max-complexity = 25 \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..379681a --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ +[![Current Release](https://img.shields.io/github/release/mtrab/webastoconnect/all.svg?style=plastic)](https://github.com/mtrab/webastoconnect/releases) [![Github All Releases](https://img.shields.io/github/downloads/mtrab/webastoconnect/total.svg?style=plastic)](https://github.com/mtrab/webastoconnect/releases) [![hacs_badge](https://img.shields.io/badge/HACS-Default-41BDF5.svg?style=plastic)](https://github.com/hacs/integration) + +Buy Me A Coffee + +This module provides a way of integrating with Webasto ThermoConnect devices. + +# Please note +Webasto DOES NOT provide any public API or documentation of such, so I cannot provide any guarantees that this will continue to work for all eternity. + +# Table of Content + +**[Installation](#installation)**
+**[Setup](#setup)**
+ +# Installation: + +### Option 1 (easy) - HACS: + +- Ensure that HACS is installed. +- Search for and install the "Energi Data Service" integration. +- Restart Home Assistant. + +### Option 2 - Manual installation: + +- Download the latest release. +- Unpack the release and copy the `custom_components/webastoconnect` directory into the `custom_components` directory of your Home Assistant installation. +- Restart Home Assistant. + +# Setup + +My Home Assistant shortcut:
+[![](https://my.home-assistant.io/badges/config_flow_start.svg)](https://my.home-assistant.io/redirect/config_flow_start/?domain=energidataservice) + +Or go to Home Assistant > Settings > Integrations + +Add "Webasto Connect (ThermoConnect)" integration *(If it doesn't show, try CTRL+F5 to force a refresh of the page)* + +Enter your Webasto account email and password + diff --git a/config/configuration.yaml b/config/configuration.yaml new file mode 100644 index 0000000..36e7c29 --- /dev/null +++ b/config/configuration.yaml @@ -0,0 +1,9 @@ +default_config: + +logger: + default: warning + logs: + custom_components.webastoconnect: debug + +# If you need to debug uncomment the line below (doc: https://www.home-assistant.io/integrations/debugpy/) +# debugpy: diff --git a/custom_components/webastoconnect/__init__.py b/custom_components/webastoconnect/__init__.py new file mode 100644 index 0000000..e7466a7 --- /dev/null +++ b/custom_components/webastoconnect/__init__.py @@ -0,0 +1,53 @@ +"""Add Webasto ThermoConnect support to Home Assistant.""" + +import logging + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_EMAIL, CONF_PASSWORD +from homeassistant.core import HomeAssistant +from homeassistant.loader import async_get_integration + +from .api import WebastoConnector, WebastoConnectUpdateCoordinator +from .const import ATTR_COORDINATOR, DOMAIN, PLATFORMS, STARTUP +from .pywebasto.exceptions import UnauthorizedException + +LOGGER = logging.getLogger(__name__) + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Set up cloud API connector from a config entry.""" + hass.data.setdefault(DOMAIN, {}) + + result = await _async_setup(hass, entry) + + if result: + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + # await async_setup_services(hass) + + return result + + +async def _async_setup(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Setup the integration using a config entry.""" + integration = await async_get_integration(hass, DOMAIN) + LOGGER.info( + STARTUP, + integration.version, + ) + + coordinator = WebastoConnectUpdateCoordinator(hass, entry) + try: + await hass.async_add_executor_job(coordinator.cloud.connect) + LOGGER.debug("Connected to %s", coordinator.cloud.name) + except UnauthorizedException: + LOGGER.error("Invalid email or password specified!") + return False + + hass.data[DOMAIN][entry.entry_id] = { + ATTR_COORDINATOR: coordinator, + } + + await coordinator.async_config_entry_first_refresh() + + return True diff --git a/custom_components/webastoconnect/api.py b/custom_components/webastoconnect/api.py new file mode 100644 index 0000000..c087110 --- /dev/null +++ b/custom_components/webastoconnect/api.py @@ -0,0 +1,55 @@ +"""API connector class.""" + +import logging +from datetime import datetime, timedelta + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_EMAIL, CONF_PASSWORD +from homeassistant.core import HomeAssistant +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator + +from .const import DOMAIN +from .pywebasto import WebastoConnect + +SCAN_INTERVAL = timedelta(seconds=15) +LOGGER = logging.getLogger(__name__) + + +class WebastoConnector: + """Webasto Connector.""" + + def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: + """Initialization of the connector.""" + self.hass = hass + self.entry = entry + self.cloud: WebastoConnect = WebastoConnect( + entry.data.get(CONF_EMAIL), entry.data.get(CONF_PASSWORD) + ) + + +class WebastoConnectUpdateCoordinator(DataUpdateCoordinator[None]): + """webasto Connect data update coordinator.""" + + def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: + """Initialize the connection.""" + DataUpdateCoordinator.__init__( + self, + hass=hass, + name=DOMAIN, + logger=LOGGER, + update_interval=SCAN_INTERVAL, + ) + + self.hass = hass + self.entry = entry + self.cloud: WebastoConnect = WebastoConnect( + entry.data.get(CONF_EMAIL), entry.data.get(CONF_PASSWORD) + ) + + async def _async_update_data(self) -> datetime | None: + """Handle data update request from the coordinator.""" + LOGGER.debug("Data update called") + try: + await self.hass.async_add_executor_job(self.cloud.update) + except Exception as ex: + raise Exception(f"Failed communicating with the API: {ex}") from ex diff --git a/custom_components/webastoconnect/base.py b/custom_components/webastoconnect/base.py new file mode 100644 index 0000000..f66bd26 --- /dev/null +++ b/custom_components/webastoconnect/base.py @@ -0,0 +1,47 @@ +"""Base definitions.""" + +from collections.abc import Callable +from dataclasses import dataclass + +from homeassistant.components.binary_sensor import BinarySensorEntityDescription +from homeassistant.components.sensor import SensorEntityDescription +from homeassistant.components.switch import SwitchEntityDescription + +from .pywebasto import WebastoConnect + + +@dataclass +class WebastoConnectBaseEntityDescriptionMixin: + """Describes a basic Webasto entity.""" + + value_fn: Callable[[WebastoConnect], bool | str | int | float] + + +@dataclass +class WebastoConnectBinarySensorEntityDescription( + BinarySensorEntityDescription, WebastoConnectBaseEntityDescriptionMixin +): + """Describes a Webasto binary sensor.""" + + icon_on: str | None = None + icon_off: str | None = None + + +@dataclass +class WebastoConnectSensorEntityDescription( + SensorEntityDescription, WebastoConnectBaseEntityDescriptionMixin +): + """Describes a Webasto sensor.""" + + unit_fn: Callable[["WebastoConnect"], None] = None + + +@dataclass +class WebastoConnectSwitchEntityDescription( + SwitchEntityDescription, WebastoConnectBaseEntityDescriptionMixin +): + """Describes a Webasto switch.""" + + command_fn: Callable[[WebastoConnect], None] = None + type_fn: Callable[[WebastoConnect], None] = None + name_fn: Callable[[WebastoConnect], None] = None diff --git a/custom_components/webastoconnect/binary_sensor.py b/custom_components/webastoconnect/binary_sensor.py new file mode 100644 index 0000000..8f7a7db --- /dev/null +++ b/custom_components/webastoconnect/binary_sensor.py @@ -0,0 +1,98 @@ +"""Binary sensors for Webasto Connect.""" + +import logging +from typing import cast + +from homeassistant.components import binary_sensor +from homeassistant.components.binary_sensor import BinarySensorEntity +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EntityCategory +from homeassistant.core import callback +from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.util import slugify as util_slugify + +from .api import WebastoConnectUpdateCoordinator +from .base import WebastoConnectBinarySensorEntityDescription +from .const import ATTR_COORDINATOR, DOMAIN + +LOGGER = logging.getLogger(__name__) + +BINARY_SENSORS = [ + WebastoConnectBinarySensorEntityDescription( + key="allow_location", + name="Allow Location Services", + entity_category=EntityCategory.DIAGNOSTIC, + value_fn=lambda webasto: cast(bool, webasto.allow_location), + icon_on="mdi:map-marker", + icon_off="mdi:map-marker-off", + entity_registry_enabled_default=False, + ) +] + + +async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): + """Setup binary_sensors.""" + binarysensors = [] + + coordinator = hass.data[DOMAIN][entry.entry_id][ATTR_COORDINATOR] + + for b_s in BINARY_SENSORS: + entity = WebastoConnectBinarySensor(b_s, coordinator) + LOGGER.debug( + "Adding binary_sensor '%s' with entity_id '%s'", b_s.name, entity.entity_id + ) + binarysensors.append(entity) + + async_add_devices(binarysensors) + + +class WebastoConnectBinarySensor(CoordinatorEntity, BinarySensorEntity): + """Representation of a Webasto Connect Binary Sensor.""" + + def __init__( + self, + description: WebastoConnectBinarySensorEntityDescription, + coordinator: WebastoConnectUpdateCoordinator, + ) -> None: + """Initialize a Webasto Connect Binary Sensor.""" + super().__init__(coordinator) + + self.entity_description = description + self.coordinator = coordinator + self._config = coordinator.entry + self._hass = coordinator.hass + + self._attr_name = self.entity_description.name + self._attr_unique_id = util_slugify( + f"{self._attr_name}_{self._config.entry_id}" + ) + self._attr_should_poll = False + + self._attr_is_on = self.entity_description.value_fn(self.coordinator.cloud) + self._attr_icon = ( + self.entity_description.icon_on + if self._attr_is_on + else self.entity_description.icon_off + ) + + self._attr_device_info = { + "identifiers": {(DOMAIN, self.coordinator.cloud.device_id)}, + "name": self.name, + "model": "ThermoConnect", + "manufacturer": "Webasto", + } + + self.entity_id = binary_sensor.ENTITY_ID_FORMAT.format( + util_slugify(f"{self.coordinator.cloud.name} {self._attr_name}") + ) + + @callback + def _handle_coordinator_update(self) -> None: + """Handle updated data from the coordinator.""" + self._attr_is_on = self.entity_description.value_fn(self.coordinator.cloud) + self._attr_icon = ( + self.entity_description.icon_on + if self._attr_is_on + else self.entity_description.icon_off + ) + self.async_write_ha_state() diff --git a/custom_components/webastoconnect/config_flow.py b/custom_components/webastoconnect/config_flow.py new file mode 100644 index 0000000..0ad88d5 --- /dev/null +++ b/custom_components/webastoconnect/config_flow.py @@ -0,0 +1,59 @@ +"""Config flow for setting up the integration.""" + +import logging +from typing import Any +import voluptuous as vol +from homeassistant import config_entries +from homeassistant.const import CONF_EMAIL, CONF_PASSWORD + +from .pywebasto.exceptions import UnauthorizedException +from .pywebasto import WebastoConnect + +from .const import DOMAIN + +LOGGER = logging.getLogger(__name__) + +CONF_SCHEME = vol.Schema( + { + vol.Required(CONF_EMAIL): str, + vol.Required(CONF_PASSWORD): str, + } +) + + +class WebastoConnectConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): + """Handle a config flow for Webasto Connect.""" + + VERSION = 1 + CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL + + async def async_step_user(self, user_input: Any | None = None): + """Handle the initial config flow step.""" + errors = {} + + if user_input is not None: + try: + webasto = WebastoConnect( + user_input[CONF_EMAIL], user_input[CONF_PASSWORD] + ) + await self.hass.async_add_executor_job(webasto.connect) + LOGGER.debug("Authorization OK") + except UnauthorizedException: + LOGGER.debug("Authorization ERROR") + errors["base"] = "invalid_auth" + + if "base" not in errors: + await self.async_set_unique_id( + f"{user_input[CONF_EMAIL]}_{webasto.device_id}" + ) + + return self.async_create_entry( + title=webasto.name, + data=user_input, + description=f"Webasto ThermoConnect - {webasto.name}", + ) + + LOGGER.debug("Showing configuration form") + return self.async_show_form( + step_id="user", data_schema=CONF_SCHEME, errors=errors + ) diff --git a/custom_components/webastoconnect/const.py b/custom_components/webastoconnect/const.py new file mode 100644 index 0000000..58a8cd3 --- /dev/null +++ b/custom_components/webastoconnect/const.py @@ -0,0 +1,21 @@ +"""Constants for use with the Webasto Connect integration.""" + +# Startup banner +STARTUP = """ +------------------------------------------------------------------- +Webasto Connect (ThermoConnect) + +Version: %s +This is a custom integration +If you have any issues with this you need to open an issue here: +https://github.com/mtrab/webastoconnect/issues +------------------------------------------------------------------- +""" + +DOMAIN = "webastoconnect" + +PLATFORMS = ["binary_sensor", "switch", "sensor", "device_tracker"] + +NEW_DATA = "webasto_signal" + +ATTR_COORDINATOR = "updatecoordinator" diff --git a/custom_components/webastoconnect/device_tracker.py b/custom_components/webastoconnect/device_tracker.py new file mode 100644 index 0000000..ff2cdb6 --- /dev/null +++ b/custom_components/webastoconnect/device_tracker.py @@ -0,0 +1,111 @@ +"""Device tracker for Webasto Connect.""" + +import logging + +from homeassistant.components import device_tracker +from homeassistant.components.device_tracker import SourceType, TrackerEntity +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import callback +from homeassistant.helpers.entity import EntityDescription +from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.util import slugify as util_slugify + +from .api import WebastoConnectUpdateCoordinator +from .const import ATTR_COORDINATOR, DOMAIN + +LOGGER = logging.getLogger(__name__) + +TRACKER = EntityDescription( + key="devicetracker", + name="Location", + entity_registry_enabled_default=True, +) + + +async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): + """Setup device tracker.""" + coordinator = hass.data[DOMAIN][entry.entry_id][ATTR_COORDINATOR] + + entity = WebastoConnectDeviceTracker(TRACKER, coordinator) + LOGGER.debug("Adding device tracker with entity_id '%s'", entity.entity_id) + + async_add_devices([entity]) + + +class WebastoConnectDeviceTracker(CoordinatorEntity, TrackerEntity): + """A device tracker for Webasto Connect.""" + + def __init__( + self, + description: EntityDescription, + coordinator: WebastoConnectUpdateCoordinator, + ) -> None: + """Initialize a Webasto Connect switch.""" + super().__init__(coordinator) + + self.entity_description = description + self._config = coordinator.entry + self.coordinator = coordinator + self._hass = coordinator.hass + + self._attr_name = description.name + self._attr_unique_id = util_slugify( + f"{self._attr_name}_{self._config.entry_id}" + ) + + self._attr_should_poll = False + + self._attr_device_info = { + "identifiers": {(DOMAIN, self.coordinator.cloud.device_id)}, + "name": self.name, + "model": "ThermoConnect", + "manufacturer": "Webasto", + } + + self.entity_id = device_tracker.ENTITY_ID_FORMAT.format( + util_slugify(f"{self.coordinator.cloud.name} {self._attr_name}") + ) + + self._handle_location() + + def _handle_location(self) -> None: + """Handle the location states.""" + if isinstance(self.coordinator.cloud.location, type(None)): + self._attr_available = False + else: + self._attr_available = True + + # if self.coordinator.cloud.allow_location: + # self.enabled = True + # else: + # self.enabled = False + + @callback + def _handle_coordinator_update(self) -> None: + """Handle updated data from the coordinator.""" + self._handle_location() + self.async_write_ha_state() + + @property + def source_type(self) -> SourceType | str | None: + """Return the source type, eg gps or router, of the device.""" + if isinstance(self.coordinator.cloud.location, type(None)): + return None + + return SourceType.GPS + + @property + def latitude(self) -> float | None: + """Return latitude value of the device.""" + if isinstance(self.coordinator.cloud.location, type(None)): + return None + + return float(self.coordinator.cloud.location["lat"]) + + @property + def longitude(self) -> float | None: + """Return longitude value of the device.""" + if isinstance(self.coordinator.cloud.location, type(None)): + return None + + return float(self.coordinator.cloud.location["lon"]) diff --git a/custom_components/webastoconnect/manifest.json b/custom_components/webastoconnect/manifest.json new file mode 100644 index 0000000..da5e455 --- /dev/null +++ b/custom_components/webastoconnect/manifest.json @@ -0,0 +1,16 @@ +{ + "domain": "webastoconnect", + "name": "Webasto Connect (ThermoConnect)", + "after_dependencies": [ + "http" + ], + "codeowners": [ + "@MTrab" + ], + "config_flow": true, + "documentation": "https://github.com/MTrab/webastoconnect/blob/master/README.md", + "iot_class": "cloud_polling", + "issue_tracker": "https://github.com/MTrab/webastoconnect/issues", + "requirements": [], + "version": "0.0.0" +} \ No newline at end of file diff --git a/custom_components/webastoconnect/pywebasto/__init__.py b/custom_components/webastoconnect/pywebasto/__init__.py new file mode 100644 index 0000000..9b5934c --- /dev/null +++ b/custom_components/webastoconnect/pywebasto/__init__.py @@ -0,0 +1,323 @@ +"""Module for interfacing with Webasto Connect.""" + +import json +import threading +from typing import Any + +import requests + +from .consts import ( + API_URL, + CMD_HEATER_OFF, + CMD_HEATER_ON, + CMD_VENTILATION_OFF, + CMD_VENTILATION_ON, +) +from .enums import Outputs, Request +from .exceptions import InvalidRequestException, UnauthorizedException + + +class WebastoConnect: + """Webasto Connect implementation.""" + + def __init__(self, username: str, password: str) -> None: + """Initialize the component.""" + self.__initialized: bool = False + + self._usn: str = username + self._pwd: str = password + self._hssess: str = None + self._authorized: bool = False + self._last_data = {} + self._dev_data = {} + self._settings = {} + self._mainOutput = {} + self._aux = {} + + self._timeout_vent: int = 3600 + self._timeout_heat: int = 3600 + + self._ventilation: bool = False + self._isCelcius: bool = False + + def connect(self) -> None: + """Connect to the API.""" + self._call(Request.LOGIN, {"username": self._usn, "password": self._pwd}) + if self._authorized: + self.__initialized = True + self.update() + else: + raise UnauthorizedException("Username or password incorrect") + + def assemble_headers(self) -> dict: + """Generate headers.""" + _headers: dict = {"origin": "https://my.webastoconnect.com"} + + if isinstance(self._hssess, type(None)): + # _headers.update( + # {"Cookie": "__stripe_mid=70011fb4-8351-41c7-baad-047402d8cafed894b1;"} + # ) + pass + else: + _headers.update({"Cookie": f"hssess={self._hssess};"}) + + return _headers + + def _call( + self, api_type: Request, payload: dict | str | None = None + ) -> dict | None: + """Make an API request.""" + + if isinstance(payload, type(None)): + payload = {} + + response = requests.request( + "POST", + f"{API_URL}{api_type.value}", + headers=self.assemble_headers(), + data=payload, + timeout=60, + ) + # self._cookies = response.cookies + if isinstance(self._hssess, type(None)): + self._hssess = response.cookies["hssess"] + + if response.status_code != 200: + if response.status_code == 401: + self._authorized = False + if self.__initialized: + self.__initialized = False + self._call( + Request.LOGIN, {"username": self._usn, "password": self._pwd} + ) + if self._authorized: + self.__initialized = True + self._call(api_type, payload) + else: + raise UnauthorizedException("Username or password incorrect") + elif response.status_code == 403: + retry = threading.Timer(30, self._call, [api_type, payload]) + retry.start() + else: + raise InvalidRequestException( + f"API reported {response.status_code}: {response.text}" + ) + else: + self._authorized = True + + if "GET" in api_type.name: + return response.json() + + def update(self) -> None: + """Get current data from Webasto API.""" + self._settings = self._call(Request.GET_SETTINGS) + self.__get_timeouts() + self._last_data = self._call(Request.GET_DATA) + self._dev_data = self._call(Request.GET_DATA_NOPOLL) + + if self._last_data["temperature"][-1] == "C": + self._isCelcius = True + + for output in self._last_data["outputs"]: + if output["line"] == "OUTH" or output["line"] == "OUTV": + self._mainOutput = output + if output["line"] == "OUTH": + self._ventilation = False + else: + self._ventilation = True + elif output["line"] == "OUTA": + self._aux = output + + def set_output(self, state: bool) -> None: + """Turn on or off the heater or ventilation.""" + if state: + if self._ventilation: + self._call(Request.COMMAND, CMD_VENTILATION_ON) + else: + self._call(Request.COMMAND, CMD_HEATER_ON) + else: + if self._ventilation: + self._call(Request.COMMAND, CMD_VENTILATION_OFF) + else: + self._call(Request.COMMAND, CMD_HEATER_OFF) + self.update() + + def ventilation_mode(self, state: bool) -> None: + """Turn ventilation mode on or off.""" + vent_sec = self._timeout_vent % (24 * 3600) + vent_h = vent_sec // 3600 + vent_sec = vent_sec % 3600 + vent_m = vent_sec // 60 + + heat_sec = self._timeout_heat % (24 * 3600) + heat_h = heat_sec // 3600 + heat_sec = heat_sec % 3600 + heat_m = heat_sec // 60 + + ventmode = { + "device_settings": { + "webasto_emul_mode": "thermoconnect", + "OUTV_timeout_on": True, + "OUTV_timeout_h": vent_h, + "OUTV_timeout_min": vent_m, + "OUTH_timeout_on": True, + "OUTH_timeout_h": heat_h, + "OUTH_timeout_min": heat_m, + }, + "service_settings": { + "OUTH_on": True if not state else False, + "OUTV_on": False if not state else True, + "heater_mode": 0 if not state else 1, + "OUTV_name": "Ventilation", + "OUTV_icon": "car_vent", + "OUTH_name": "Heater", + "OUTH_icon": "car_heat", + }, + "location_events": None, + "air_heater": {}, + } + + self._call(Request.POST_SETTING, json.dumps(ventmode)) + self.update() + + def set_timeout( + self, + heater: int | None = None, + ventilation: int | None = None, + aux: int | None = None, + ) -> None: + """Sets timeout of an output port in seconds.""" + if not isinstance(heater, type(None)): + self._timeout_heat = heater + + if not isinstance(ventilation, type(None)): + self._timeout_vent = ventilation + + self.ventilation_mode(self._ventilation) + + def set_low_voltage_cutoff(self, value: float) -> None: + """Set the low voltage cutoff value.""" + + payload = { + "device_settings": {"low_voltage_cutoff": value}, + "service_settings": {}, + "location_events": None, + "air_heater": {}, + } + self._call(Request.POST_SETTING, json.dumps(payload)) + self.update() + + def set_temperature_compensation(self, value: float) -> None: + """Set the temperature compensation value.""" + + payload = { + "device_settings": {"ext_temp_comp": value}, + "service_settings": {}, + "location_events": None, + "air_heater": {}, + } + self._call(Request.POST_SETTING, json.dumps(payload, indent=4)) + self.update() + + @property + def temperature(self) -> int: + """Returns the current temperature.""" + return self._last_data["temperature"][: len(self._last_data["temperature"]) - 1] + + @property + def voltage(self) -> float: + """Returns the current voltage.""" + return self._last_data["voltage"][: len(self._last_data["voltage"]) - 1] + + @property + def location(self) -> dict: + """Returns the current location.""" + return ( + self._last_data["location"] + if self._last_data["location"]["state"] == "ON" + else None + ) + + @property + def output(self) -> bool: + """Get the main output state.""" + if self._mainOutput["state"] == "OFF": + return False + else: + return True + + @property + def isVentilation(self) -> bool: + """Get the mode of the output channel.""" + return self._ventilation + + @property + def temperature_unit(self) -> bool: + """Get the temperature unit.""" + return "°C" if self._isCelcius else "°F" + + @property + def hardware_version(self) -> str: + """Get the hardware version.""" + return self._settings["hw_version"] + + @property + def software_version(self) -> str: + """Get the software version.""" + return self._settings["sw_version"] + + @property + def software_variant(self) -> str: + """Get the software variant.""" + return self._settings["sw_variant"] + + @property + def allow_location(self) -> str: + """Get the location setting.""" + return self.__get_value("general", "allow_GPS") + + @property + def low_voltage_cutoff(self) -> str: + """Get the low_voltage_cutoff setting.""" + return self.__get_value("general", "low_voltage_cutoff") + + @property + def temperature_compensation(self) -> str: + """Get the ext_temp_comp setting.""" + return self.__get_value("general", "ext_temp_comp") + + @property + def device_id(self) -> str: + """Get the ID of the device (QR code ID)""" + return self._dev_data["id"] + + @property + def name(self) -> str: + """Get the name of the device.""" + return self._dev_data["alias"] + + @property + def output_name(self) -> str: + """Get the main output name.""" + return self._mainOutput["name"] + + def __get_value(self, group: str, key: str) -> Any: + """Get a value from the settings dict.""" + for g in self._settings["settings_tab"]: + if g["group"] != group: + continue + + for o in g["options"]: + if o["key"] == key: + return o["value"] + + def __get_timeouts(self) -> None: + for g in self._settings["settings_tab"]: + if g["group"] != "webasto": + continue + + for o in g["options"]: + if o["key"] == "OUTH": + self._timeout_heat = o["timeout"] + elif o["key"] == "OUTV": + self._timeout_vent = o["timeout"] diff --git a/custom_components/webastoconnect/pywebasto/consts.py b/custom_components/webastoconnect/pywebasto/consts.py new file mode 100644 index 0000000..5babf5a --- /dev/null +++ b/custom_components/webastoconnect/pywebasto/consts.py @@ -0,0 +1,12 @@ +"""Constants used for Webasto.""" + +API_URL = "https://my.webastoconnect.com/webapi" + +CMD_HEATER_ON = "OUT H ON" +CMD_HEATER_OFF = "OUT H OFF" + +CMD_VENTILATION_ON = "OUT V ON" +CMD_VENTILATION_OFF = "OUT V OFF" + +CMD_AUX_ON = "OUT A ON" +CMD_AUX_OFF = "OUT A OFF" diff --git a/custom_components/webastoconnect/pywebasto/enums.py b/custom_components/webastoconnect/pywebasto/enums.py new file mode 100644 index 0000000..7c857ae --- /dev/null +++ b/custom_components/webastoconnect/pywebasto/enums.py @@ -0,0 +1,21 @@ +"""Enum classes.""" +from enum import Enum + + +class Request(Enum): + """Requests options.""" + + LOGIN = "/login" + COMMAND = "/command" + GET_DATA = "/get_service_data?poll=true" + GET_DATA_NOPOLL = "/get_service_data?poll=false" + POST_SETTING = "/post_settings" + GET_SETTINGS = "/get_settings" + + +class Outputs(Enum): + """Valid Webasto outputs.""" + + HEATER = "OUTH" + VENTILATION = "OUTV" + AUX = "OUTA" diff --git a/custom_components/webastoconnect/pywebasto/exceptions.py b/custom_components/webastoconnect/pywebasto/exceptions.py new file mode 100644 index 0000000..b74abe7 --- /dev/null +++ b/custom_components/webastoconnect/pywebasto/exceptions.py @@ -0,0 +1,9 @@ +"""Exceptions used in this module.""" + + +class UnauthorizedException(Exception): + """User is unauthorized.""" + + +class InvalidRequestException(Exception): + """Something went wrong with the request.""" diff --git a/custom_components/webastoconnect/sensor.py b/custom_components/webastoconnect/sensor.py new file mode 100644 index 0000000..d21d203 --- /dev/null +++ b/custom_components/webastoconnect/sensor.py @@ -0,0 +1,112 @@ +"""Sensors for Webasto Connect.""" + +import logging +from typing import cast + +from homeassistant.components import sensor +from homeassistant.components.sensor import ( + SensorDeviceClass, + SensorEntity, + SensorStateClass, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EntityCategory +from homeassistant.core import callback +from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.util import slugify as util_slugify + +from .api import WebastoConnectUpdateCoordinator +from .base import WebastoConnectSensorEntityDescription +from .const import ATTR_COORDINATOR, DOMAIN + +LOGGER = logging.getLogger(__name__) + +BINARY_SENSORS = [ + WebastoConnectSensorEntityDescription( + key="temperature", + name="Temperature", + entity_category=None, + state_class=SensorStateClass.MEASUREMENT, + device_class=SensorDeviceClass.TEMPERATURE, + value_fn=lambda webasto: webasto.temperature, + icon="mdi:thermometer", + unit_fn=lambda webasto: webasto.temperature_unit, + ), + WebastoConnectSensorEntityDescription( + key="battery_voltage", + name="Battery", + entity_category=None, + state_class=SensorStateClass.MEASUREMENT, + device_class=SensorDeviceClass.VOLTAGE, + native_unit_of_measurement="V", + value_fn=lambda webasto: webasto.voltage, + icon="mdi:car-battery", + ), +] + + +async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): + """Setup binary_sensors.""" + sensors = [] + + coordinator = hass.data[DOMAIN][entry.entry_id][ATTR_COORDINATOR] + + for b_s in BINARY_SENSORS: + entity = WebastoConnectSensor(b_s, coordinator) + LOGGER.debug( + "Adding binary_sensor '%s' with entity_id '%s'", b_s.name, entity.entity_id + ) + sensors.append(entity) + + async_add_devices(sensors) + + +class WebastoConnectSensor(CoordinatorEntity, SensorEntity): + """Representation of a Webasto Connect Sensor.""" + + def __init__( + self, + description: WebastoConnectSensorEntityDescription, + coordinator: WebastoConnectUpdateCoordinator, + ) -> None: + """Initialize a Webasto Connect Sensor.""" + super().__init__(coordinator) + + self.entity_description = description + self.coordinator = coordinator + self._config = coordinator.entry + self._hass = coordinator.hass + + self._attr_name = self.entity_description.name + self._attr_unique_id = util_slugify( + f"{self._attr_name}_{self._config.entry_id}" + ) + self._attr_should_poll = False + self._attr_icon = self.entity_description.icon + self._attr_native_value = self.entity_description.value_fn( + self.coordinator.cloud + ) + + if not isinstance(description.unit_fn, type(None)): + self._attr_native_unit_of_measurement = description.unit_fn( + coordinator.cloud + ) + + self._attr_device_info = { + "identifiers": {(DOMAIN, self.coordinator.cloud.device_id)}, + "name": self.name, + "model": "ThermoConnect", + "manufacturer": "Webasto", + } + + self.entity_id = sensor.ENTITY_ID_FORMAT.format( + util_slugify(f"{self.coordinator.cloud.name} {self._attr_name}") + ) + + @callback + def _handle_coordinator_update(self) -> None: + """Handle updated data from the coordinator.""" + self._attr_native_value = self.entity_description.value_fn( + self.coordinator.cloud + ) + self.async_write_ha_state() diff --git a/custom_components/webastoconnect/switch.py b/custom_components/webastoconnect/switch.py new file mode 100644 index 0000000..3343bf5 --- /dev/null +++ b/custom_components/webastoconnect/switch.py @@ -0,0 +1,135 @@ +"""Switches for Webasto Connect.""" + +import logging +from typing import Any, cast + +from homeassistant.components import switch +from homeassistant.components.switch import SwitchEntity +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EntityCategory +from homeassistant.core import callback +from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.util import slugify as util_slugify + +from .api import WebastoConnectUpdateCoordinator +from .base import WebastoConnectSwitchEntityDescription +from .const import ATTR_COORDINATOR, DOMAIN + +LOGGER = logging.getLogger(__name__) + +BINARY_SENSORS = [ + WebastoConnectSwitchEntityDescription( + key="main_output", + name="Output", + entity_category=None, + value_fn=lambda webasto: cast(bool, webasto.output), + command_fn=lambda webasto, state: webasto.set_output(state), + name_fn=lambda webasto: webasto.output_name, + entity_registry_enabled_default=True, + ), + WebastoConnectSwitchEntityDescription( + key="ventilation_mode", + name="Ventilation Mode", + entity_category=EntityCategory.CONFIG, + value_fn=lambda webasto: cast(bool, webasto.isVentilation), + command_fn=lambda webasto, state: webasto.ventilation_mode(state), + entity_registry_enabled_default=False, + ), +] + + +async def async_setup_entry(hass, entry: ConfigEntry, async_add_devices): + """Setup switch.""" + switches = [] + + coordinator = hass.data[DOMAIN][entry.entry_id][ATTR_COORDINATOR] + + for b_s in BINARY_SENSORS: + entity = WebastoConnectSwitch(b_s, coordinator) + LOGGER.debug( + "Adding switch '%s' with entity_id '%s'", b_s.name, entity.entity_id + ) + switches.append(entity) + + async_add_devices(switches) + + +class WebastoConnectSwitch(CoordinatorEntity, SwitchEntity): + """Representation of a Webasto Connect switch.""" + + def __init__( + self, + description: WebastoConnectSwitchEntityDescription, + coordinator: WebastoConnectUpdateCoordinator, + ) -> None: + """Initialize a Webasto Connect switch.""" + super().__init__(coordinator) + + self.entity_description = description + self._config = coordinator.entry + self.coordinator = coordinator + self._hass = coordinator.hass + self._base_name = self.entity_description.name + + if not isinstance(self.entity_description.name_fn, type(None)): + self._attr_name = self.entity_description.name_fn(coordinator.cloud) + else: + self._attr_name = self.entity_description.name + + self._attr_unique_id = util_slugify( + f"{self._base_name}_{self._config.entry_id}" + ) + + self._attr_should_poll = False + + self._attr_device_info = { + "identifiers": {(DOMAIN, self.coordinator.cloud.device_id)}, + "name": self.name, + "model": "ThermoConnect", + "manufacturer": "Webasto", + } + + self._handle_states() + + self.entity_id = switch.ENTITY_ID_FORMAT.format( + util_slugify(f"{self.coordinator.cloud.name} {self._attr_name}") + ) + + @callback + def _handle_coordinator_update(self) -> None: + """Handle updated data from the coordinator.""" + self._handle_states() + self.async_write_ha_state() + + def _handle_states(self) -> None: + """Handle the switch states.""" + if not isinstance(self.entity_description.name_fn, type(None)): + self._attr_name = self.entity_description.name_fn(self.coordinator.cloud) + + self._attr_is_on = self.entity_description.value_fn(self.coordinator.cloud) + + if self.entity_description.key == "main_output": + if self.coordinator.cloud.isVentilation: + self._attr_icon = "mdi:fan" if self._attr_is_on else "mdi:fan-off" + else: + self._attr_icon = ( + "mdi:radiator" if self._attr_is_on else "mdi:radiator-off" + ) + elif self.entity_description.key == "ventilation_mode": + self._attr_icon = "mdi:fan" if self._attr_is_on else "mdi:fan-off" + + async def async_turn_on(self, **kwargs: Any) -> None: + """Turn on the switch.""" + LOGGER.debug("Turning on %s", self.entity_id) + await self._hass.async_add_executor_job( + self.entity_description.command_fn, self.coordinator.cloud, True + ) + await self.coordinator.async_refresh() + + async def async_turn_off(self, **kwargs: Any) -> None: + """Turn off the switch.""" + LOGGER.debug("Turning off %s", self.entity_id) + await self._hass.async_add_executor_job( + self.entity_description.command_fn, self.coordinator.cloud, False + ) + await self.coordinator.async_refresh() diff --git a/custom_components/webastoconnect/translations/en.json b/custom_components/webastoconnect/translations/en.json new file mode 100644 index 0000000..fa3fbb9 --- /dev/null +++ b/custom_components/webastoconnect/translations/en.json @@ -0,0 +1,19 @@ +{ + "config": { + "title": "Webasto Connect (ThermoConnect)", + "abort": { + "already_configured": "Device is already configured" + }, + "error": { + "invalid_auth": "Invalid authentication" + }, + "step": { + "user": { + "data": { + "email": "Email", + "password": "Password" + } + } + } + } +} \ No newline at end of file diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..b0de819 --- /dev/null +++ b/hacs.json @@ -0,0 +1,7 @@ +{ + "name": "Webasto Connect (ThermoConnect)", + "render_readme": true, + "homeassistant": "2023.10.0", + "zip_release": true, + "filename": "webastoconnect.zip" +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7f624d8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +colorlog==6.7.0 +homeassistant==2023.10.1 +pip>=21.0,<23.3 +ruff==0.0.291 \ No newline at end of file diff --git a/scripts/develop b/scripts/develop new file mode 100755 index 0000000..20366e8 --- /dev/null +++ b/scripts/develop @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +# Create config dir if not present +if [[ ! -d "${PWD}/config" ]]; then + mkdir -p "${PWD}/config" + hass --config "${PWD}/config" --script ensure_config +fi + +# Set the path to custom_components +## This let's us have the structure we want /custom_components/integration_blueprint +## while at the same time have Home Assistant configuration inside /config +## without resulting to symlinks. +export PYTHONPATH="${PYTHONPATH}:${PWD}/custom_components" + +# Start Home Assistant +hass --config "${PWD}/config" --debug \ No newline at end of file diff --git a/scripts/lint b/scripts/lint new file mode 100755 index 0000000..752d23a --- /dev/null +++ b/scripts/lint @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +ruff check . --fix \ No newline at end of file diff --git a/scripts/setup b/scripts/setup new file mode 100755 index 0000000..abe537a --- /dev/null +++ b/scripts/setup @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +python3 -m pip install --requirement requirements.txt \ No newline at end of file