├── .devcontainer ├── configuration.yaml ├── devcontainer.json └── setup.sh ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ ├── issue.md │ └── issue.yml ├── dependabot.yml ├── labels.yml ├── release-drafter.yml └── workflows │ ├── constraints.txt │ ├── dependabot-auto-merge.yml │ ├── labeler.yml │ ├── release-drafter.yml │ └── tests.yaml ├── .gitignore ├── .pre-commit-config.yaml ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── custom_components ├── __init__.py └── ha_registry │ ├── __init__.py │ ├── config_flow.py │ ├── const.py │ ├── manifest.json │ └── services.yaml ├── hacs.json ├── pytest.ini ├── requirements_dev.txt ├── requirements_test.txt ├── setup.cfg └── tests ├── __init__.py └── test_init.py /.devcontainer/configuration.yaml: -------------------------------------------------------------------------------- 1 | default_config: 2 | 3 | logger: 4 | default: info 5 | logs: 6 | custom_components.ha_registry: debug 7 | 8 | # If you need to debug uncommment the line below (doc: https://www.home-assistant.io/integrations/debugpy/) 9 | debugpy: 10 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // See https://aka.ms/vscode-remote/devcontainer.json for format details. 2 | { 3 | "image": "ghcr.io/ludeeus/devcontainer/integration:stable", 4 | "name": "Home Assistant Registry integration development", 5 | "context": "..", 6 | "appPort": ["9123:8123"], 7 | "postCreateCommand": ".devcontainer/setup.sh", 8 | "mounts": [ 9 | "source=${localEnv:HOME}${localEnv:USERPROFILE}/.gitconfig,target=/root/.gitconfig,type=bind,consistency=cached" 10 | ], 11 | "extensions": [ 12 | "ms-python.python", 13 | "github.vscode-pull-request-github", 14 | "ryanluker.vscode-coverage-gutters", 15 | "ms-python.vscode-pylance", 16 | "esbenp.prettier-vscode" 17 | ], 18 | "settings": { 19 | "files.eol": "\n", 20 | "editor.tabSize": 4, 21 | "terminal.integrated.shell.linux": "/bin/bash", 22 | "python.pythonPath": "/usr/bin/python3", 23 | "python.analysis.autoSearchPaths": false, 24 | "python.linting.pylintEnabled": true, 25 | "python.linting.enabled": true, 26 | "python.formatting.provider": "black", 27 | "editor.formatOnPaste": false, 28 | "editor.formatOnSave": true, 29 | "editor.formatOnType": true, 30 | "files.trimTrailingWhitespace": true 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /.devcontainer/setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Setups the repository. 3 | 4 | # Stop on errors 5 | set -e 6 | 7 | cd "$(dirname "$0")/.." 8 | 9 | pip3 install -r .github/workflows/constraints.txt 10 | pip3 install -r requirements_dev.txt 11 | pip3 install -r requirements_test.txt 12 | pre-commit install 13 | 14 | container install 15 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | --- 5 | 6 | **Is your feature request related to a problem? Please describe.** 7 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 8 | 9 | **Describe the solution you'd like** 10 | A clear and concise description of what you want to happen. 11 | 12 | **Describe alternatives you've considered** 13 | A clear and concise description of any alternative solutions or features you've considered. 14 | 15 | **Additional context** 16 | Add any other context or screenshots about the feature request here. 17 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Issue 3 | about: Create a report to help us improve 4 | --- 5 | 6 | 14 | 15 | ## Version of the custom_component 16 | 17 | 20 | 21 | ## Describe the bug 22 | 23 | A clear and concise description of what the bug is. 24 | 25 | ## Debug log 26 | 27 | Enable debug logging in `configuration.yaml` by adding these lines: 28 | 29 | ```yaml 30 | logger: 31 | logs: 32 | custom_components.google_assistant_relay: debug 33 | ``` 34 | 35 | ```text 36 | 37 | Add your debug logs here. 38 | 39 | ``` 40 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue.yml: -------------------------------------------------------------------------------- 1 | name: Report an issue with Home Assistant Registry 2 | description: Report an issue with Home Assistant Registry 3 | body: 4 | - type: markdown 5 | attributes: 6 | value: | 7 | This issue form is for reporting bugs only! 8 | - type: textarea 9 | validations: 10 | required: true 11 | attributes: 12 | label: Problem 13 | description: >- 14 | Describe the issue you are experiencing here, to communicate to the 15 | maintainers. Tell us what you were trying to do and what happened. 16 | 17 | Provide a clear and concise description of what the problem is. 18 | - type: markdown 19 | attributes: 20 | value: | 21 | # Environment 22 | - type: input 23 | validations: 24 | required: true 25 | attributes: 26 | label: Home Assistant Registry Version 27 | placeholder: e.g. v2.2.5 28 | - type: markdown 29 | attributes: 30 | value: | 31 | # Details 32 | - type: textarea 33 | validations: 34 | required: true 35 | attributes: 36 | label: Debugging Information 37 | description: >- 38 | Include logs after enabling debugging. 39 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | - package-ecosystem: pip 8 | directory: "/.github/workflows" 9 | schedule: 10 | interval: daily 11 | - package-ecosystem: pip 12 | directory: "/" 13 | schedule: 14 | interval: daily 15 | -------------------------------------------------------------------------------- /.github/labels.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # Labels names are important as they are used by Release Drafter to decide 3 | # regarding where to record them in changelog or if to skip them. 4 | # 5 | # The repository labels will be automatically configured using this file and 6 | # the GitHub Action https://github.com/marketplace/actions/github-labeler. 7 | - name: breaking 8 | description: Breaking Changes 9 | color: bfd4f2 10 | - name: bug 11 | description: Something isn't working 12 | color: d73a4a 13 | - name: build 14 | description: Build System and Dependencies 15 | color: bfdadc 16 | - name: ci 17 | description: Continuous Integration 18 | color: 4a97d6 19 | - name: dependencies 20 | description: Pull requests that update a dependency file 21 | color: 0366d6 22 | - name: documentation 23 | description: Improvements or additions to documentation 24 | color: 0075ca 25 | - name: duplicate 26 | description: This issue or pull request already exists 27 | color: cfd3d7 28 | - name: enhancement 29 | description: New feature or request 30 | color: a2eeef 31 | - name: github_actions 32 | description: Pull requests that update Github_actions code 33 | color: "000000" 34 | - name: good first issue 35 | description: Good for newcomers 36 | color: 7057ff 37 | - name: help wanted 38 | description: Extra attention is needed 39 | color: 008672 40 | - name: invalid 41 | description: This doesn't seem right 42 | color: e4e669 43 | - name: performance 44 | description: Performance 45 | color: "016175" 46 | - name: python 47 | description: Pull requests that update Python code 48 | color: 2b67c6 49 | - name: question 50 | description: Further information is requested 51 | color: d876e3 52 | - name: refactoring 53 | description: Refactoring 54 | color: ef67c4 55 | - name: removal 56 | description: Removals and Deprecations 57 | color: 9ae7ea 58 | - name: style 59 | description: Style 60 | color: c120e5 61 | - name: testing 62 | description: Testing 63 | color: b1fc6f 64 | - name: wontfix 65 | description: This will not be worked on 66 | color: ffffff 67 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | categories: 2 | - title: ":boom: Breaking Changes" 3 | label: "breaking" 4 | - title: ":rocket: Features" 5 | label: "enhancement" 6 | - title: ":fire: Removals and Deprecations" 7 | label: "removal" 8 | - title: ":beetle: Fixes" 9 | label: "bug" 10 | - title: ":racehorse: Performance" 11 | label: "performance" 12 | - title: ":rotating_light: Testing" 13 | label: "testing" 14 | - title: ":construction_worker: Continuous Integration" 15 | label: "ci" 16 | - title: ":books: Documentation" 17 | label: "documentation" 18 | - title: ":hammer: Refactoring" 19 | label: "refactoring" 20 | - title: ":lipstick: Style" 21 | label: "style" 22 | - title: ":package: Dependencies" 23 | labels: 24 | - "dependencies" 25 | - "build" 26 | template: | 27 | ## Changes 28 | 29 | $CHANGES 30 | -------------------------------------------------------------------------------- /.github/workflows/constraints.txt: -------------------------------------------------------------------------------- 1 | pip==23.3.2 2 | pre-commit==3.8.0 3 | black==23.12.1 4 | flake8==6.1.0 5 | reorder-python-imports==3.15.0 6 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-auto-merge.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot auto-merge 2 | on: pull_request 3 | 4 | permissions: 5 | contents: write 6 | pull-requests: write 7 | 8 | jobs: 9 | dependabot: 10 | runs-on: ubuntu-latest 11 | if: ${{ github.actor == 'dependabot[bot]' }} 12 | steps: 13 | - name: Dependabot metadata 14 | id: metadata 15 | uses: dependabot/fetch-metadata@v1.7.0 16 | with: 17 | github-token: "${{ secrets.GITHUB_TOKEN }}" 18 | - name: Enable auto-merge for Dependabot PRs 19 | if: ${{ steps.metadata.outputs.update-type != 'version-update:semver-major' }} 20 | run: gh pr merge --auto --merge "$PR_URL" 21 | env: 22 | PR_URL: ${{ github.event.pull_request.html_url }} 23 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 24 | -------------------------------------------------------------------------------- /.github/workflows/labeler.yml: -------------------------------------------------------------------------------- 1 | name: Manage labels 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | 9 | jobs: 10 | labeler: 11 | name: Labeler 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Check out the repository 15 | uses: actions/checkout@v3 16 | 17 | - name: Run Labeler 18 | uses: crazy-max/ghaction-github-labeler@v4.2.0 19 | with: 20 | skip-delete: true 21 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Draft a release note 2 | on: 3 | push: 4 | branches: 5 | - main 6 | - master 7 | jobs: 8 | draft_release: 9 | name: Release Drafter 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Run release-drafter 13 | uses: release-drafter/release-drafter@v5.25.0 14 | env: 15 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 16 | -------------------------------------------------------------------------------- /.github/workflows/tests.yaml: -------------------------------------------------------------------------------- 1 | name: Linting 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | - dev 9 | pull_request: 10 | schedule: 11 | - cron: "0 0 * * *" 12 | 13 | env: 14 | DEFAULT_PYTHON: 3.9 15 | 16 | jobs: 17 | pre-commit: 18 | runs-on: ubuntu-latest 19 | name: Pre-commit 20 | steps: 21 | - name: Check out the repository 22 | uses: actions/checkout@v3 23 | 24 | - name: Set up Python ${{ env.DEFAULT_PYTHON }} 25 | uses: actions/setup-python@v4.8.0 26 | with: 27 | python-version: ${{ env.DEFAULT_PYTHON }} 28 | 29 | - name: Upgrade pip 30 | run: | 31 | pip install --constraint=.github/workflows/constraints.txt pip 32 | pip --version 33 | 34 | - name: Install Python modules 35 | run: | 36 | pip install --constraint=.github/workflows/constraints.txt pre-commit black flake8 reorder-python-imports 37 | 38 | - name: Run pre-commit on all files 39 | run: | 40 | pre-commit run --all-files --show-diff-on-failure --color=always 41 | 42 | hacs: 43 | runs-on: "ubuntu-latest" 44 | name: HACS 45 | steps: 46 | - name: Check out the repository 47 | uses: actions/checkout@v3 48 | 49 | - name: HACS validation 50 | uses: hacs/action@main 51 | with: 52 | category: "integration" 53 | ignore: brands 54 | 55 | hassfest: 56 | runs-on: ubuntu-latest 57 | name: Hassfest 58 | steps: 59 | - name: Check out the repository 60 | uses: "actions/checkout@v3" 61 | 62 | - name: Hassfest validation 63 | uses: "home-assistant/actions/hassfest@master" 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | pythonenv* 3 | .python-version 4 | .coverage 5 | venv 6 | .venv 7 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v3.3.0 4 | hooks: 5 | - id: check-added-large-files 6 | - id: check-yaml 7 | - id: end-of-file-fixer 8 | - id: trailing-whitespace 9 | - repo: local 10 | hooks: 11 | - id: black 12 | name: black 13 | entry: black 14 | language: system 15 | types: [python] 16 | require_serial: true 17 | - id: flake8 18 | name: flake8 19 | entry: flake8 20 | language: system 21 | types: [python] 22 | require_serial: true 23 | - id: reorder-python-imports 24 | name: Reorder python imports 25 | entry: reorder-python-imports 26 | language: system 27 | types: [python] 28 | args: [--application-directories=custom_components] 29 | - repo: https://github.com/pre-commit/mirrors-prettier 30 | rev: v2.2.1 31 | hooks: 32 | - id: prettier 33 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 3 | "version": "0.2.0", 4 | "configurations": [ 5 | { 6 | // Example of attaching to local debug server 7 | "name": "Python: Attach Local", 8 | "type": "python", 9 | "request": "attach", 10 | "port": 5678, 11 | "host": "localhost", 12 | "pathMappings": [ 13 | { 14 | "localRoot": "${workspaceFolder}", 15 | "remoteRoot": "." 16 | } 17 | ] 18 | }, 19 | { 20 | // Example of attaching to my production server 21 | "name": "Python: Attach Remote", 22 | "type": "python", 23 | "request": "attach", 24 | "port": 5678, 25 | "host": "homeassistant.local", 26 | "pathMappings": [ 27 | { 28 | "localRoot": "${workspaceFolder}", 29 | "remoteRoot": "/usr/src/homeassistant" 30 | } 31 | ] 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.linting.pylintEnabled": true, 3 | "python.linting.enabled": true, 4 | "python.pythonPath": "venv/bin/python", 5 | "files.associations": { 6 | "*.yaml": "home-assistant" 7 | }, 8 | "[javascript]": { 9 | "editor.defaultFormatter": "esbenp.prettier-vscode" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Run Home Assistant on port 9123", 6 | "type": "shell", 7 | "command": "container start", 8 | "problemMatcher": [], 9 | "group": { 10 | "kind": "build", 11 | "isDefault": true 12 | } 13 | }, 14 | { 15 | "label": "Run Home Assistant configuration against /config", 16 | "type": "shell", 17 | "command": "container check", 18 | "problemMatcher": [] 19 | }, 20 | { 21 | "label": "Upgrade Home Assistant to latest dev", 22 | "type": "shell", 23 | "command": "container install", 24 | "problemMatcher": [] 25 | }, 26 | { 27 | "label": "Install a specific version of Home Assistant", 28 | "type": "shell", 29 | "command": "container set-version", 30 | "problemMatcher": [] 31 | } 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution guidelines 2 | 3 | Contributing to this project should be as easy and transparent as possible, whether it's: 4 | 5 | - Reporting a bug 6 | - Discussing the current state of the code 7 | - Submitting a fix 8 | - Proposing new features 9 | 10 | ## Github is used for everything 11 | 12 | Github is used to host code, to track issues and feature requests, as well as accept pull requests. 13 | 14 | Pull requests are the best way to propose changes to the codebase. 15 | 16 | 1. Fork the repo and create your branch from `master`. 17 | 2. If you've changed something, update the documentation. 18 | 3. Make sure your code lints (using black). 19 | 4. Test you contribution. 20 | 5. Issue that pull request! 21 | 22 | ## Any contributions you make will be under the MIT Software License 23 | 24 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern. 25 | 26 | ## Report bugs using Github's [issues](../../issues) 27 | 28 | GitHub issues are used to track public bugs. 29 | Report a bug by [opening a new issue](../../issues/new/choose); it's that easy! 30 | 31 | ## Write bug reports with detail, background, and sample code 32 | 33 | **Great Bug Reports** tend to have: 34 | 35 | - A quick summary and/or background 36 | - Steps to reproduce 37 | - Be specific! 38 | - Give sample code if you can. 39 | - What you expected would happen 40 | - What actually happens 41 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 42 | 43 | People _love_ thorough bug reports. I'm not even kidding. 44 | 45 | ## Use a Consistent Coding Style 46 | 47 | Use [black](https://github.com/ambv/black) and [prettier](https://prettier.io/) 48 | to make sure the code follows the style. 49 | 50 | Or use the `pre-commit` settings implemented in this repository 51 | (see deicated section below). 52 | 53 | ## Test your code modification 54 | 55 | This custom component is based on [integration_blueprint template](https://github.com/custom-components/integration_blueprint). 56 | 57 | It comes with development environment in a container, easy to launch 58 | if you use Visual Studio Code. With this container you will have a stand alone 59 | Home Assistant instance running and already configured with the included 60 | [`.devcontainer/configuration.yaml`](./.devcontainer/configuration.yaml) 61 | file. 62 | 63 | You can use the `pre-commit` settings implemented in this repository to have 64 | linting tool checking your contributions (see deicated section below). 65 | 66 | ## Pre-commit 67 | 68 | You can use the [pre-commit](https://pre-commit.com/) settings included in the 69 | repostory to have code style and linting checks. 70 | 71 | With `pre-commit` tool already installed, 72 | activate the settings of the repository: 73 | 74 | ```console 75 | $ pre-commit install 76 | ``` 77 | 78 | Now the pre-commit tests will be done every time you commit. 79 | 80 | You can run the tests on all repository file with the command: 81 | 82 | ```console 83 | $ pre-commit run --all-files 84 | ``` 85 | 86 | ## License 87 | 88 | By contributing, you agree that your contributions will be licensed under its MIT License. 89 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Home Assistant Registry 2 | 3 | [![GitHub Release][releases-shield]][releases] 4 | [![GitHub Activity][commits-shield]][commits] 5 | [![License][license-shield]](LICENSE) 6 | 7 | [![pre-commit][pre-commit-shield]][pre-commit] 8 | [![Black][black-shield]][black] 9 | 10 | [![hacs][hacsbadge]][hacs] 11 | [![Project Maintenance][maintenance-shield]][user_profile] 12 | [![BuyMeCoffee][buymecoffeebadge]][buymecoffee] 13 | 14 | [![Community Forum][forum-shield]][forum] 15 | 16 | ## Description 17 | 18 | Adds services for home assistant registry operations. 19 | 20 | > **WARNING**: These are low level APIs that only have basic validation. They are intended for power users. Misuse could result in entities getting into strange states. 21 | 22 | HA core has decided to not support services for common registry operations mentioned in https://github.com/home-assistant/core/pull/86281#event-8320797538. 23 | 24 | ### Services 25 | 26 | #### Remove Entity 27 | 28 | Remove all targeted entity registry configs, 29 | 30 | `entity_id` is a repeated field that takes comma separated values in a string or a yaml list 31 | 32 | ```yaml 33 | service: ha_registry.remove_entity 34 | data: 35 | entity_id: 36 | - sensor.bathroom_temperature 37 | - sensor.bedroom_temperature 38 | ``` 39 | 40 | #### Update Entity 41 | 42 | Updates all targeted entity registry configs to the specified values. 43 | 44 | `entity_id` and `aliases` are repeated fields that take comma separated values in a string or a yaml list 45 | 46 | ```yaml 47 | service: ha_registry.update_entity 48 | data: 49 | entity_id: sensor.bathroom_temperature,sensor.bedroom_temperature 50 | aliases: 51 | - Alias1 52 | - Alias2 53 | area_id: bedroom 54 | device_class: temperature 55 | disabled: true 56 | hidden: true 57 | icon: mdi:home 58 | name: Bedroom Temperature 59 | new_entity_id: sensor.new_entity_id 60 | options_domain: sensor 61 | options: 62 | unit_of_measurement: °F 63 | ``` 64 | 65 | {% if not installed %} 66 | 67 | ## Installation 68 | 69 | ### HACS 70 | 71 | 1. Install [HACS](https://hacs.xyz/) 72 | 2. Go to HACS "Integrations >" section 73 | 3. In the lower right click "+ Explore & Download repositories" 74 | 4. Search for "Home Assistant Registry" and add it 75 | - HA Restart is not needed since it is configured in UI config flow 76 | 5. In the Home Assistant (HA) UI go to "Configuration" 77 | 6. Click "Integrations" 78 | 7. Click "+ Add Integration" 79 | 8. Search for "Home Assistant Registry" 80 | 81 | ### Manual 82 | 83 | 1. Using the tool of choice open the directory (folder) for your [HA configuration](https://www.home-assistant.io/docs/configuration/) (where you find `configuration.yaml`). 84 | 2. If you do not have a `custom_components` directory (folder) there, you need to create it. 85 | 3. In the `custom_components` directory (folder) create a new folder called `ha_registry`. 86 | 4. Download _all_ the files from the `custom_components/ha_registry/` directory (folder) in this repository. 87 | 5. Place the files you downloaded in the new directory (folder) you created. 88 | 6. Restart Home Assistant 89 | 7. In the Home Assistant (HA) UI go to "Configuration" 90 | 8. Click "Integrations" 91 | 9. Click "+ Add Integration" 92 | 10. Search for "Home Assistant Registry" 93 | 94 | {% endif %} 95 | 96 | ## Contributions are welcome! 97 | 98 | If you want to contribute to this please read the [Contribution guidelines](https://github.com/amosyuen/ha-registry/blob/master/CONTRIBUTING.md) 99 | 100 | ## Credits 101 | 102 | Code template was mainly taken from [@Ludeeus](https://github.com/ludeeus)'s [integration_blueprint][integration_blueprint] template 103 | 104 | --- 105 | 106 | [integration_blueprint]: https://github.com/custom-components/integration_blueprint 107 | [black]: https://github.com/psf/black 108 | [black-shield]: https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge 109 | [buymecoffee]: https://paypal.me/amosyuen 110 | [buymecoffeebadge]: https://img.shields.io/badge/buy%20me%20a%20coffee-donate-yellow.svg?style=for-the-badge 111 | [commits-shield]: https://img.shields.io/github/commit-activity/y/amosyuen/ha-registry.svg?style=for-the-badge 112 | [commits]: https://github.com/amosyuen/ha-registry/commits/main 113 | [hacs]: https://hacs.xyz 114 | [hacsbadge]: https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge 115 | [forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg?style=for-the-badge 116 | [forum]: https://community.home-assistant.io/ 117 | [license-shield]: https://img.shields.io/github/license/amosyuen/ha-registry.svg?style=for-the-badge 118 | [maintenance-shield]: https://img.shields.io/badge/maintainer-%40amosyuen-blue.svg?style=for-the-badge 119 | [pre-commit]: https://github.com/pre-commit/pre-commit 120 | [pre-commit-shield]: https://img.shields.io/badge/pre--commit-enabled-brightgreen?style=for-the-badge 121 | [releases-shield]: https://img.shields.io/github/release/amosyuen/ha-registry.svg?style=for-the-badge 122 | [releases]: https://github.com/amosyuen/ha-registry/releases 123 | [user_profile]: https://github.com/amosyuen 124 | -------------------------------------------------------------------------------- /custom_components/__init__.py: -------------------------------------------------------------------------------- 1 | """Custom components module.""" 2 | -------------------------------------------------------------------------------- /custom_components/ha_registry/__init__.py: -------------------------------------------------------------------------------- 1 | """The Home Assistant Registry integration.""" 2 | import logging 3 | 4 | import homeassistant.core as ha 5 | import voluptuous as vol 6 | from homeassistant.auth.permissions.const import CAT_ENTITIES 7 | from homeassistant.auth.permissions.const import POLICY_EDIT 8 | from homeassistant.config_entries import ConfigEntry 9 | from homeassistant.const import ATTR_AREA_ID 10 | from homeassistant.const import ATTR_DEVICE_CLASS 11 | from homeassistant.const import ATTR_ENTITY_ID 12 | from homeassistant.const import ATTR_ICON 13 | from homeassistant.const import ATTR_NAME 14 | from homeassistant.core import HomeAssistant 15 | from homeassistant.exceptions import NoEntitySpecifiedError 16 | from homeassistant.exceptions import Unauthorized 17 | from homeassistant.exceptions import UnknownUser 18 | from homeassistant.helpers import config_validation as cv 19 | from homeassistant.helpers import device_registry as dr 20 | from homeassistant.helpers import entity_registry as er 21 | from homeassistant.helpers.entity_registry import RegistryEntryDisabler 22 | from homeassistant.helpers.entity_registry import RegistryEntryHider 23 | 24 | from .const import ATTR_ALIASES 25 | from .const import ATTR_DISABLED 26 | from .const import ATTR_DISABLED_BY 27 | from .const import ATTR_HIDDEN 28 | from .const import ATTR_HIDDEN_BY 29 | from .const import ATTR_NEW_ENTITY_ID 30 | from .const import ATTR_OPTIONS 31 | from .const import ATTR_OPTIONS_DOMAIN 32 | from .const import DOMAIN 33 | from .const import SERVICE_REMOVE_ENTITY 34 | from .const import SERVICE_UPDATE_ENTITY 35 | 36 | 37 | SCHEMA_REMOVE_ENTITY = vol.Schema( 38 | { 39 | vol.Required(ATTR_ENTITY_ID): cv.entity_ids, 40 | } 41 | ) 42 | SCHEMA_UPDATE_ENTITY = vol.Schema( 43 | { 44 | vol.Required(ATTR_ENTITY_ID): cv.entity_ids, 45 | vol.Optional(ATTR_ALIASES): vol.All(cv.ensure_list_csv, [cv.string]), 46 | vol.Optional(ATTR_AREA_ID): vol.Any(None, str), 47 | vol.Optional(ATTR_DEVICE_CLASS): vol.Any(None, str), 48 | vol.Optional(ATTR_ICON): vol.Any(None, str), 49 | vol.Optional(ATTR_NAME): vol.Any(None, str), 50 | vol.Optional(ATTR_NEW_ENTITY_ID): cv.string, 51 | vol.Inclusive(ATTR_OPTIONS_DOMAIN, "entity_option"): vol.Any(None, str), 52 | vol.Inclusive(ATTR_OPTIONS, "entity_option"): vol.Any(None, dict), 53 | vol.Optional(ATTR_DISABLED): bool, 54 | vol.Optional(ATTR_HIDDEN): bool, 55 | } 56 | ) 57 | 58 | _LOGGER = logging.getLogger(__name__) 59 | 60 | 61 | async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: 62 | """Set up Home Assistant Registry from a config entry.""" 63 | 64 | async def check_permissions_and_entities( 65 | entity_registry, entities, context 66 | ) -> None: 67 | """Check user has permissions to edit entities and that entity registries exist.""" 68 | if context.user_id: 69 | user = await hass.auth.async_get_user(context.user_id) 70 | 71 | if user is None: 72 | raise UnknownUser( 73 | context=context, 74 | permission=POLICY_EDIT, 75 | user_id=context.user_id, 76 | ) 77 | 78 | for entity_id in entities: 79 | if not user.permissions.check_entity(entity_id, POLICY_EDIT): 80 | raise Unauthorized( 81 | context=context, 82 | permission=POLICY_EDIT, 83 | user_id=context.user_id, 84 | perm_category=CAT_ENTITIES, 85 | ) 86 | 87 | not_found_entities = [ 88 | entity_id 89 | for entity_id in entities 90 | if not entity_registry.async_is_registered(entity_id) 91 | ] 92 | if len(not_found_entities) > 0: 93 | raise NoEntitySpecifiedError( 94 | f"Entity registries not found: {not_found_entities}" 95 | ) 96 | 97 | async def async_remove_entity(call: ha.ServiceCall) -> None: 98 | """Remove entity.""" 99 | entity_ids = call.data[ATTR_ENTITY_ID] 100 | registry = er.async_get(hass) 101 | 102 | await check_permissions_and_entities(registry, entity_ids, call.context) 103 | 104 | for entity_id in entity_ids: 105 | _LOGGER.debug("Removing entity %s", entity_id) 106 | registry.async_remove(entity_id) 107 | 108 | hass.services.async_register( 109 | DOMAIN, 110 | SERVICE_REMOVE_ENTITY, 111 | async_remove_entity, 112 | schema=SCHEMA_REMOVE_ENTITY, 113 | ) 114 | 115 | async def async_update_entity(call): 116 | """Update entity""" 117 | entities = call.data[ATTR_ENTITY_ID] 118 | entity_registry = er.async_get(hass) 119 | 120 | await check_permissions_and_entities(entity_registry, entities, call.context) 121 | 122 | changes = {ATTR_ICON: None} 123 | for key in ( 124 | ATTR_AREA_ID, 125 | ATTR_DEVICE_CLASS, 126 | ATTR_ICON, 127 | ATTR_NAME, 128 | ATTR_NEW_ENTITY_ID, 129 | ): 130 | if key in call.data: 131 | value = call.data[key] 132 | if type(value) is str and value.strip() == "": 133 | value = None 134 | _LOGGER.debug("Service call {%s:%s}", key, value) 135 | changes[key] = value 136 | 137 | aliases = call.data.get(ATTR_ALIASES) 138 | if aliases is not None: 139 | changes[ATTR_ALIASES] = set(aliases) 140 | 141 | disabled = call.data.get(ATTR_DISABLED) 142 | if disabled is not None: 143 | changes[ATTR_DISABLED_BY] = RegistryEntryDisabler.USER if disabled else None 144 | if disabled is False: 145 | device_registry = dr.async_get(hass) 146 | disabled_entities = [] 147 | for entity_id in entities: 148 | entity_entry = entity_registry.async_get(entity_id) 149 | if entity_entry.device_id: 150 | device = device_registry.async_get(entity_entry.device_id) 151 | if device and device.disabled: 152 | disabled_entities.append(entity_id) 153 | if len(disabled_entities) > 0: 154 | raise ValueError( 155 | "Can not enable entities wtih disabled devices: {disabled_entities}" 156 | ) 157 | 158 | hidden = call.data.get(ATTR_HIDDEN) 159 | if hidden is not None: 160 | changes[ATTR_HIDDEN_BY] = RegistryEntryHider.USER if hidden else None 161 | 162 | for entity_id in entities: 163 | if ATTR_OPTIONS_DOMAIN in call.data: 164 | _LOGGER.debug("Updating entity %s options", entity_id) 165 | entity_entry = entity_registry.async_update_entity_options( 166 | entity_id, call.data[ATTR_OPTIONS_DOMAIN], call.data[ATTR_OPTIONS] 167 | ) 168 | 169 | if changes: 170 | _LOGGER.debug("Updating entity %s", entity_id) 171 | entity_registry.async_update_entity(entity_id, **changes) 172 | 173 | hass.services.async_register( 174 | DOMAIN, SERVICE_UPDATE_ENTITY, async_update_entity, schema=SCHEMA_UPDATE_ENTITY 175 | ) 176 | 177 | return True 178 | 179 | 180 | async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: 181 | return True 182 | -------------------------------------------------------------------------------- /custom_components/ha_registry/config_flow.py: -------------------------------------------------------------------------------- 1 | """Config flow.""" 2 | from homeassistant import config_entries 3 | 4 | from .const import DOMAIN 5 | 6 | 7 | class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): 8 | VERSION = 1 9 | 10 | async def async_step_user(self, user_input=None): 11 | await self.async_set_unique_id("ha_registry") 12 | return self.async_create_entry(title="Home Assistant Registry", data={}) 13 | -------------------------------------------------------------------------------- /custom_components/ha_registry/const.py: -------------------------------------------------------------------------------- 1 | """Constants for the ha_registry integration.""" 2 | 3 | DOMAIN = "ha_registry" 4 | 5 | ATTR_ALIASES = "aliases" 6 | ATTR_DISABLED = "disabled" 7 | ATTR_DISABLED_BY = "disabled_by" 8 | ATTR_HIDDEN = "hidden" 9 | ATTR_HIDDEN_BY = "hidden_by" 10 | ATTR_NEW_ENTITY_ID = "new_entity_id" 11 | ATTR_OPTIONS = "options" 12 | ATTR_OPTIONS_DOMAIN = "options_domain" 13 | ATTR_STATUS = "status" 14 | 15 | SERVICE_REMOVE_ENTITY = "remove_entity" 16 | SERVICE_UPDATE_ENTITY = "update_entity" 17 | -------------------------------------------------------------------------------- /custom_components/ha_registry/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "ha_registry", 3 | "name": "Home Assistant Registry", 4 | "codeowners": ["@amosyuen"], 5 | "config_flow": true, 6 | "dependencies": [], 7 | "documentation": "https://github.com/amosyuen/ha-registry", 8 | "iot_class": "local_push", 9 | "issue_tracker": "https://github.com/amosyuen/ha-registry/issues", 10 | "version": "1.0.0" 11 | } 12 | -------------------------------------------------------------------------------- /custom_components/ha_registry/services.yaml: -------------------------------------------------------------------------------- 1 | # Services.yaml for ha_registry integration 2 | 3 | update_entity: 4 | name: Update Entity 5 | description: Update entity registry 6 | fields: 7 | entity_id: 8 | name: Entity 9 | description: Entity or list of entity to update 10 | required: true 11 | example: ["sensor.bathroom_temperature", "sensor.bedroom_temperature"] 12 | selector: 13 | entity: 14 | multiple: true 15 | aliases: 16 | name: Aliases 17 | description: Single alias or a list of aliases 18 | example: ["Living Room", "Family Room"] 19 | selector: 20 | object: 21 | area_id: 22 | name: Area 23 | description: Area to set 24 | example: bedroom 25 | selector: 26 | area: 27 | device_class: 28 | name: Device Class 29 | description: Device class to set 30 | example: temperature 31 | selector: 32 | text: 33 | disabled: 34 | name: Disabled 35 | description: Whether to set entity as disabled 36 | example: true 37 | selector: 38 | boolean: 39 | hidden: 40 | name: Hidden 41 | description: Whether to set entity as hidden 42 | example: true 43 | selector: 44 | boolean: 45 | icon: 46 | name: Icon 47 | description: Icon to set 48 | example: mdi:home 49 | selector: 50 | icon: 51 | name: 52 | name: Name 53 | description: Name to set 54 | example: Bedroom Temperature 55 | selector: 56 | text: 57 | new_entity_id: 58 | name: New Entity ID 59 | description: New entity ID to set (Only possible if entity has unique ID) 60 | example: sensor.new_entity_id 61 | selector: 62 | text: 63 | options_domain: 64 | name: Options Domain 65 | description: Domain of "Options" argument 66 | example: sensor 67 | selector: 68 | text: 69 | options: 70 | name: Options 71 | description: Entity options of "Options Domain" argument to set 72 | example: '{unit_of_measurement: "°F"}' 73 | selector: 74 | object: 75 | 76 | remove_entity: 77 | name: Remove Entity 78 | description: Remove entity registry 79 | fields: 80 | entity_id: 81 | name: Entity ID 82 | description: Entity or list of entities to remove 83 | required: true 84 | example: ["sensor.bathroom_temperature", "sensor.bedroom_temperature"] 85 | selector: 86 | entity: 87 | multiple: true 88 | -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Home Assistant Registry", 3 | "hacs": "1.6.0", 4 | "homeassistant": "2023.1.0", 5 | "render_readme": true 6 | } 7 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | asyncio_mode=auto 3 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | homeassistant==2023.12.4 2 | -------------------------------------------------------------------------------- /requirements_test.txt: -------------------------------------------------------------------------------- 1 | pytest-asyncio==0.26.0 2 | pytest-homeassistant-custom-component==0.13.224 3 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = .venv,.git,.tox,docs,venv,bin,lib,deps,build 3 | doctests = True 4 | # To work with Black 5 | max-line-length = 88 6 | # E501: line too long 7 | # W503: Line break occurred before a binary operator 8 | # E203: Whitespace before ':' 9 | # D202 No blank lines allowed after function docstring 10 | # W504 line break after binary operator 11 | ignore = 12 | E501, 13 | W503, 14 | E203, 15 | D202, 16 | W504 17 | 18 | [isort] 19 | # https://github.com/timothycrosley/isort 20 | # https://github.com/timothycrosley/isort/wiki/isort-Settings 21 | # splits long import on multiple lines indented by 4 spaces 22 | multi_line_output = 3 23 | include_trailing_comma=True 24 | force_grid_wrap=0 25 | use_parentheses=True 26 | line_length=88 27 | indent = " " 28 | # by default isort don't check module indexes 29 | not_skip = __init__.py 30 | # will group `import x` and `from x import` of the same module. 31 | force_sort_within_sections = true 32 | sections = FUTURE,STDLIB,INBETWEENS,THIRDPARTY,FIRSTPARTY,LOCALFOLDER 33 | default_section = THIRDPARTY 34 | known_first_party = custom_components.ha_registry 35 | combine_as_imports = true 36 | 37 | [tool:pytest] 38 | addopts = -qq --cov=custom_components.ha_registry 39 | console_output_style = count 40 | 41 | [coverage:run] 42 | branch = False 43 | 44 | [coverage:report] 45 | show_missing = true 46 | fail_under = 100 47 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Tests for ha_registry integration.""" 2 | -------------------------------------------------------------------------------- /tests/test_init.py: -------------------------------------------------------------------------------- 1 | """Test entity_registry API.""" 2 | import pytest 3 | from custom_components.ha_registry import async_setup_entry 4 | from custom_components.ha_registry.const import DOMAIN 5 | from custom_components.ha_registry.const import SERVICE_REMOVE_ENTITY 6 | from custom_components.ha_registry.const import SERVICE_UPDATE_ENTITY 7 | from homeassistant.const import ATTR_DEVICE_CLASS 8 | from homeassistant.const import ATTR_ICON 9 | from homeassistant.exceptions import NoEntitySpecifiedError 10 | from homeassistant.helpers.device_registry import DeviceEntryDisabler 11 | from homeassistant.helpers.entity_registry import async_get as async_get_entity_registry 12 | from homeassistant.helpers.entity_registry import RegistryEntry 13 | from homeassistant.helpers.entity_registry import RegistryEntryDisabler 14 | from homeassistant.helpers.entity_registry import RegistryEntryHider 15 | from pytest_homeassistant_custom_component.common import mock_device_registry 16 | from pytest_homeassistant_custom_component.common import mock_registry 17 | from pytest_homeassistant_custom_component.common import MockConfigEntry 18 | from pytest_homeassistant_custom_component.common import MockEntity 19 | from pytest_homeassistant_custom_component.common import MockEntityPlatform 20 | 21 | 22 | @pytest.fixture 23 | async def entity_registry(hass): 24 | """Return an loaded, registry.""" 25 | entity_registry = mock_registry( 26 | hass, 27 | { 28 | "test_domain.world": RegistryEntry( 29 | entity_id="test_domain.world", 30 | unique_id="1234", 31 | platform="test_platform", 32 | name="before update", 33 | icon="icon:before update", 34 | ) 35 | }, 36 | ) 37 | platform = MockEntityPlatform(hass) 38 | entity = MockEntity(unique_id="1234") 39 | await platform.async_add_entities([entity]) 40 | return entity_registry 41 | 42 | 43 | @pytest.fixture 44 | def device_registry(hass): 45 | """Return an empty, loaded, registry.""" 46 | return mock_device_registry(hass) 47 | 48 | 49 | async def test_update_entity(hass, entity_registry): 50 | """Test updating entity.""" 51 | 52 | await async_setup_entry(hass, {}) 53 | 54 | # UPDATE AREA, DEVICE_CLASS, ICON, AND NAME 55 | await hass.services.async_call( 56 | DOMAIN, 57 | SERVICE_UPDATE_ENTITY, 58 | { 59 | "entity_id": "test_domain.world", 60 | "aliases": ["alias_1", "alias_2"], 61 | "area_id": "mock-area-id", 62 | "device_class": "custom_device_class", 63 | "icon": "icon:after update", 64 | "name": "after update", 65 | }, 66 | blocking=True, 67 | ) 68 | 69 | state = hass.states.get("test_domain.world") 70 | assert state.attributes[ATTR_DEVICE_CLASS] == "custom_device_class" 71 | assert state.attributes[ATTR_ICON] == "icon:after update" 72 | assert state.name == "after update" 73 | entry = entity_registry.entities["test_domain.world"] 74 | assert entry.aliases == {"alias_1", "alias_2"} 75 | assert entry.area_id == "mock-area-id" 76 | 77 | 78 | async def test_update_entity_disabled_and_hidden(hass, entity_registry): 79 | """Test updating entity disabled and hidden.""" 80 | 81 | await async_setup_entry(hass, {}) 82 | 83 | # Disable and hide 84 | await hass.services.async_call( 85 | DOMAIN, 86 | SERVICE_UPDATE_ENTITY, 87 | { 88 | "entity_id": ["test_domain.world"], 89 | "disabled": True, 90 | "hidden": True, 91 | }, 92 | blocking=True, 93 | ) 94 | 95 | assert hass.states.get("test_domain.world") is None 96 | assert ( 97 | entity_registry.entities["test_domain.world"].disabled_by 98 | is RegistryEntryDisabler.USER 99 | ) 100 | assert ( 101 | entity_registry.entities["test_domain.world"].hidden_by 102 | is RegistryEntryHider.USER 103 | ) 104 | 105 | # Enable and unhide 106 | await hass.services.async_call( 107 | DOMAIN, 108 | SERVICE_UPDATE_ENTITY, 109 | { 110 | "entity_id": "test_domain.world", 111 | "disabled": False, 112 | "hidden": False, 113 | }, 114 | blocking=True, 115 | ) 116 | 117 | assert entity_registry.entities["test_domain.world"].disabled_by is None 118 | assert entity_registry.entities["test_domain.world"].hidden_by is None 119 | 120 | 121 | async def test_enable_entity_disabled_device(hass, device_registry): 122 | """Test enabling entity of disabled device.""" 123 | 124 | await async_setup_entry(hass, {}) 125 | 126 | entity_id = "test_domain.test_platform_1234" 127 | config_entry = MockConfigEntry(domain="test_platform") 128 | config_entry.add_to_hass(hass) 129 | 130 | device = device_registry.async_get_or_create( 131 | config_entry_id="1234", 132 | connections={("ethernet", "12:34:56:78:90:AB:CD:EF")}, 133 | identifiers={("bridgeid", "0123")}, 134 | manufacturer="manufacturer", 135 | model="model", 136 | disabled_by=DeviceEntryDisabler.USER, 137 | ) 138 | device_info = { 139 | "connections": {("ethernet", "12:34:56:78:90:AB:CD:EF")}, 140 | } 141 | 142 | platform = MockEntityPlatform(hass) 143 | platform.config_entry = config_entry 144 | entity = MockEntity(unique_id="1234", device_info=device_info) 145 | await platform.async_add_entities([entity]) 146 | 147 | state = hass.states.get(entity_id) 148 | assert state is None 149 | 150 | entity_registry = async_get_entity_registry(hass) 151 | entity_entry = entity_registry.async_get(entity_id) 152 | assert entity_entry.config_entry_id == config_entry.entry_id 153 | assert entity_entry.device_id == device.id 154 | assert entity_entry.disabled_by == RegistryEntryDisabler.DEVICE 155 | 156 | # Enable 157 | with pytest.raises(ValueError): 158 | await hass.services.async_call( 159 | DOMAIN, 160 | SERVICE_UPDATE_ENTITY, 161 | { 162 | "entity_id": entity_id, 163 | "disabled": False, 164 | }, 165 | blocking=True, 166 | ) 167 | 168 | 169 | async def test_update_entity_option(hass, entity_registry): 170 | """Test updating entity option.""" 171 | 172 | await async_setup_entry(hass, {}) 173 | 174 | await hass.services.async_call( 175 | DOMAIN, 176 | SERVICE_UPDATE_ENTITY, 177 | { 178 | "entity_id": "test_domain.world", 179 | "options_domain": "sensor", 180 | "options": {"unit_of_measurement": "beard_second"}, 181 | }, 182 | blocking=True, 183 | ) 184 | 185 | assert entity_registry.entities["test_domain.world"].options == { 186 | "sensor": {"unit_of_measurement": "beard_second"} 187 | } 188 | 189 | 190 | async def test_update_entity_id(hass, entity_registry): 191 | """Test update entity id.""" 192 | 193 | await async_setup_entry(hass, {}) 194 | 195 | assert entity_registry.async_is_registered("test_domain.world") is not None 196 | 197 | await hass.services.async_call( 198 | DOMAIN, 199 | SERVICE_UPDATE_ENTITY, 200 | { 201 | "entity_id": "test_domain.world", 202 | "new_entity_id": "test_domain.planet", 203 | }, 204 | blocking=True, 205 | ) 206 | 207 | assert not entity_registry.async_is_registered("test_domain.world") 208 | assert entity_registry.async_is_registered("test_domain.planet") 209 | 210 | 211 | async def test_update_non_existing_entity(hass): 212 | """Test update non existing entity.""" 213 | 214 | await async_setup_entry(hass, {}) 215 | 216 | mock_registry(hass, {}) 217 | 218 | with pytest.raises(NoEntitySpecifiedError): 219 | await hass.services.async_call( 220 | DOMAIN, 221 | SERVICE_UPDATE_ENTITY, 222 | { 223 | "entity_id": ["test_domain.world"], 224 | }, 225 | blocking=True, 226 | ) 227 | 228 | 229 | async def test_remove_entity(hass): 230 | """Test removing entity.""" 231 | 232 | await async_setup_entry(hass, {}) 233 | 234 | registry = mock_registry( 235 | hass, 236 | { 237 | "test_domain.world": RegistryEntry( 238 | entity_id="test_domain.world", 239 | unique_id="1234", 240 | # Using component.async_add_entities is equal to platform "domain" 241 | platform="test_platform", 242 | name="before update", 243 | ), 244 | "test_domain.world2": RegistryEntry( 245 | entity_id="test_domain.world2", 246 | unique_id="12345", 247 | # Using component.async_add_entities is equal to platform "domain" 248 | platform="test_platform", 249 | name="before update", 250 | ), 251 | }, 252 | ) 253 | 254 | await hass.services.async_call( 255 | DOMAIN, 256 | SERVICE_REMOVE_ENTITY, 257 | { 258 | "entity_id": ["test_domain.world", "test_domain.world2"], 259 | }, 260 | blocking=True, 261 | ) 262 | 263 | assert len(registry.entities) == 0 264 | 265 | 266 | async def test_remove_non_existing_entity(hass): 267 | """Test removing non existing entity.""" 268 | 269 | await async_setup_entry(hass, {}) 270 | 271 | mock_registry(hass, {}) 272 | 273 | with pytest.raises(NoEntitySpecifiedError): 274 | await hass.services.async_call( 275 | DOMAIN, 276 | SERVICE_REMOVE_ENTITY, 277 | { 278 | "entity_id": ["test_domain.world"], 279 | }, 280 | blocking=True, 281 | ) 282 | --------------------------------------------------------------------------------