Repository: DeebotUniverse/Deebot-4-Home-Assistant Branch: dev Commit: 2e9182144965 Files: 70 Total size: 193.8 KB Directory structure: gitextract_7_5jqkhe/ ├── .devcontainer.json ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug.yml │ │ ├── bug_setup.yml │ │ ├── config.yml │ │ ├── feature_request.yml │ │ └── question.yml │ ├── dependabot.yml │ ├── release-drafter.yml │ └── workflows/ │ ├── ci.yml │ ├── codeql-analysis.yml │ ├── cron.yaml │ ├── release-drafter.yml │ ├── release.yml │ └── stale.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .prettierrc.js ├── .vscode/ │ ├── launch.json │ ├── settings.json │ └── tasks.json ├── .yamllint ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── bandit.yaml ├── custom_components/ │ ├── __init__.py │ └── deebot/ │ ├── __init__.py │ ├── binary_sensor.py │ ├── button.py │ ├── config_flow.py │ ├── const.py │ ├── controller.py │ ├── diagnostics.py │ ├── entity.py │ ├── image.py │ ├── manifest.json │ ├── number.py │ ├── select.py │ ├── sensor.py │ ├── services.yaml │ ├── switch.py │ ├── translations/ │ │ ├── de.json │ │ ├── en.json │ │ ├── fr.json │ │ ├── it.json │ │ ├── ko.json │ │ ├── pt-BR.json │ │ ├── ru.json │ │ └── zh-Hans.json │ ├── util.py │ └── vacuum.py ├── hacs.json ├── mypy.ini ├── pylintrc ├── pyproject.toml ├── requirements.txt ├── scripts/ │ ├── coverage │ ├── develop │ ├── install/ │ │ └── pip_packages │ ├── lint │ ├── run-in-env.sh │ ├── setup │ └── test ├── setup.cfg ├── tests/ │ ├── README.md │ ├── __init__.py │ └── conftest.py └── translations.schema.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .devcontainer.json ================================================ { "customizations": { "vscode": { "extensions": [ "esbenp.prettier-vscode", "github.vscode-pull-request-github", "ms-python.python", "ms-python.vscode-pylance", "ms-vscode.makefile-tools", "ryanluker.vscode-coverage-gutters", "visualstudioexptteam.vscodeintellicode" ], "settings": { "editor.formatOnPaste": false, "editor.formatOnSave": true, "editor.formatOnType": true, "editor.tabSize": 4, "files.eol": "\n", "files.trimTrailingWhitespace": true, "python.analysis.autoImportCompletions": true, "python.analysis.autoSearchPaths": false, "python.analysis.extraPaths": ["/home/vscode/.local/lib/python*/"], "python.analysis.typeCheckingMode": "basic", "python.defaultInterpreterPath": "/usr/local/bin/python", "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", "python.formatting.blackPath": "/usr/local/py-utils/bin/black", "python.formatting.provider": "black", "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", "python.languageServer": "Pylance", "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", "python.linting.enabled": true, "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", "python.linting.mypyEnabled": true, "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", "python.linting.pylintArgs": ["--disable", "import-error"], "python.linting.pylintEnabled": true, "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint", "python.pythonPath": "/usr/local/python/bin/python", "python.testing.pytestEnabled": true, "python.testing.unittestEnabled": false, "terminal.integrated.defaultProfile.linux": "zsh", "terminal.integrated.profiles.linux": { "zsh": { "path": "/usr/bin/zsh" } } } } }, "features": { "rust": "latest" }, "forwardPorts": [8123], "image": "mcr.microsoft.com/devcontainers/python:3", "name": "Deebot 4 HA", "portsAttributes": { "0-8122": { "label": "Auto-Forwarded - Other", "onAutoForward": "ignore" }, "8123": { "label": "Home Assistant" }, "8124-999999": { "label": "Auto-Forwarded - Other", "onAutoForward": "ignore" } }, "postCreateCommand": "scripts/setup", "remoteUser": "vscode", "runArgs": ["-e", "GIT_EDITOR=code --wait"] } ================================================ FILE: .gitattributes ================================================ text=auto eol=lf ================================================ FILE: .github/FUNDING.yml ================================================ custom: ["https://www.buymeacoffee.com/edenhaus"] ================================================ FILE: .github/ISSUE_TEMPLATE/bug.yml ================================================ name: Report an issue/bug description: Report a issue/bug labels: [bug] body: - type: markdown attributes: value: | This issue form is for reporting bugs only! If you have a feature request or a question, please use discussions. - type: checkboxes attributes: label: Checks options: - label: I have searched the existing issues and no issue is describing my issue required: true - label: I have checked the [FAQ](https://deebot.readthedocs.io/home/faq/) required: true - label: I have checked the [documentation](https://deebot.readthedocs.io/integrations/home-assistant) required: true - label: I have installed the latest version required: true - type: textarea validations: required: true attributes: label: The problem description: >- Describe the issue you are experiencing here to communicate to the maintainers. Tell us 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: textarea validations: required: true attributes: label: Diagnostics information description: >- Download the diagnostic data for the device you are having issues with (found on the device page), and drag-and-drop that file into the textbox below. - type: markdown attributes: value: | # Details - type: textarea attributes: label: Anything in the logs that might be useful for us? description: > For example, error message, or stack traces. Please refer to the [documentation](https://deebot.readthedocs.io/integrations/home-assistant/issues/). render: txt - type: textarea attributes: label: Additional information description: > If you have any additional information for us, use the field below. Please note, you can attach screenshots or screen recordings here, by dragging and dropping files in the field below. ================================================ FILE: .github/ISSUE_TEMPLATE/bug_setup.yml ================================================ name: Report an issue/bug during during installation or configuration description: Report a issue/bug during installation or configuration labels: [bug] body: - type: markdown attributes: value: | This issue form is for reporting setup/install bugs only! If you have successfully configured your robot, please use the other issue form. If you have a feature request or a question, please use discussions. - type: checkboxes attributes: label: Checks options: - label: I have searched the existing issues and no issue is describing my issue required: true - label: I have checked the [FAQ](https://deebot.readthedocs.io/home/faq/) required: true - label: I have checked the [documentation](https://deebot.readthedocs.io/integrations/home-assistant) required: true - label: I have installed/try to install the latest version required: true - type: textarea validations: required: true attributes: label: The problem description: >- Describe the issue you are experiencing here to communicate to the maintainers. Tell us 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: device validations: required: true attributes: label: On which deebot vacuum you have the issue? placeholder: Deebot Ozmo 950 - type: input id: version validations: required: true attributes: label: Which version of the Deebot component are you using? placeholder: X.X.X description: > Will be logged during starting on Level Info. Can be found in the log file. Latest is not a valid version! - type: input id: ha_version validations: required: true attributes: label: Which version of Home Assistant are you using? placeholder: 202X.X.X description: > Can be found in the Configuration panel -> Info. - type: dropdown validations: required: true attributes: label: What type of installation are you running? description: > If you don't know, you can find it in: Configuration panel -> Info. options: - Home Assistant OS - Home Assistant Container - Home Assistant Supervised - Home Assistant Core - type: markdown attributes: value: | # Configuration - type: input id: country attributes: label: Country placeholder: it description: > Which country did you input during the setup of the integration? - type: input id: continent attributes: label: Continent placeholder: eu description: > Which continent did you input during the setup of the integration? - type: dropdown attributes: label: Instance type description: > If you don't know, please select "Cloud". If you have running a bumper instance and you are using it, then and ONLY then select "Bumper" options: - Cloud - Bumper - type: markdown attributes: value: | # Details - type: textarea attributes: label: Anything in the logs that might be useful for us? description: > For example, error message, or stack traces. Please refer to the [documentation](https://deebot.readthedocs.io/integrations/home-assistant/issues/). render: txt - type: textarea attributes: label: Additional information description: > If you have any additional information for us, use the field below. Please note, you can attach screenshots or screen recordings here, by dragging and dropping files in the field below. ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.yml ================================================ name: "💡 Suggest an feature/idea" description: "💡 Suggest an feature/idea" labels: [enhancement] body: - type: markdown attributes: value: | This issue form is for reporting features or ideas only! If you have a bug/issue or a question, please use the other templates. - type: checkboxes attributes: label: Is there an existing issue for this? description: Please search to see if an issue already exists for your feature request or idea options: - label: I have searched the existing issues and no issue is describing my feature request or idea required: true - type: textarea attributes: label: Is your feature request related to a problem? description: > A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - type: textarea validations: required: true attributes: label: Suggested solution description: > A clear and concise description of what you want to happen. - type: textarea attributes: label: Api example request description: > If for your feature a sample requests exist, please paste it here. This speed things up, specially for new commands render: txt - type: textarea attributes: label: Alternatives you've considered description: > A clear and concise description of any alternative solutions or features you've considered. - type: textarea attributes: label: Additional information description: > If you have any additional information for us, use the field below. Please note, you can attach screenshots or screen recordings here, by dragging and dropping files in the field below. ================================================ FILE: .github/ISSUE_TEMPLATE/question.yml ================================================ name: "❓ Ask a Question" description: "❓ Ask a Question" labels: [question] body: - type: markdown attributes: value: | This issue form is for questions! If you have a bug/issue or a feature request, please use the other templates. - type: textarea attributes: label: Question description: > A clear and concise description - type: textarea attributes: label: Additional information description: > If you have any additional information for us, use the field below. Please note, you can attach screenshots or screen recordings here, by dragging and dropping files in the field below. ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: # Maintain dependencies for GitHub Actions - package-ecosystem: "github-actions" directory: "/" labels: - "pr: dependency-update" schedule: interval: "daily" # Maintain dependencies for pip - package-ecosystem: "pip" directory: "/" labels: - "pr: dependency-update" schedule: interval: "daily" ================================================ FILE: .github/release-drafter.yml ================================================ name-template: "$RESOLVED_VERSION" tag-template: "$RESOLVED_VERSION" change-template: "- #$NUMBER $TITLE @$AUTHOR" sort-direction: ascending filter-by-commitish: true categories: - title: ":boom: Breaking changes" label: "pr: Breaking Change" - title: ":sparkles: New features" label: "pr: new-feature" - title: ":zap: Enhancements" label: "pr: enhancement" - title: ":recycle: Refactor" label: "pr: refactor" - title: ":bug: Bug Fixes" label: "pr: bugfix" - title: ":arrow_up: Dependency Updates" labels: - "pr: dependency-update" - "dependencies" include-labels: - "pr: Breaking Change" - "pr: enhancement" - "pr: dependency-update" - "pr: new-feature" - "pr: bugfix" - "pr: refactor" version-resolver: major: labels: - "pr: Breaking Change" minor: labels: - "pr: enhancement" - "pr: dependency-update" - "pr: new-feature" patch: labels: - "pr: bugfix" default: patch template: | [![Downloads for this release](https://img.shields.io/github/downloads/DeebotUniverse/Deebot-4-Home-Assistant/$RESOLVED_VERSION/total.svg)](https://github.com/DeebotUniverse/Deebot-4-Home-Assistant/releases/$RESOLVED_VERSION) $CHANGES **Like my work and want to support me?** Buy Me A Coffee ================================================ FILE: .github/workflows/ci.yml ================================================ # This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: CI on: push: branches: - dev pull_request: ~ env: DEFAULT_PYTHON: "3.11" jobs: validate-hacs: runs-on: "ubuntu-latest" name: Validate with HACS steps: - uses: "actions/checkout@v4" - name: HACS validation uses: "hacs/action@main" with: category: "integration" validate-hassfest: runs-on: "ubuntu-latest" name: Validate with Hassfest steps: - uses: "actions/checkout@v4" - name: Hassfest validation uses: "home-assistant/actions/hassfest@master" code-quality: runs-on: "ubuntu-latest" name: Check code quality steps: - uses: "actions/checkout@v4" - name: Set up Python ${{ env.DEFAULT_PYTHON }} id: python uses: actions/setup-python@v5 with: python-version: ${{ env.DEFAULT_PYTHON }} cache: "pip" - name: Install dependencies run: | pip install -r requirements.txt # Following steps cannot run by pre-commit.ci as repo = local - name: Run mypy run: mypy custom_components/ - name: Pylint review run: pylint custom_components/ create_zip_file: name: Create zip file for testing permissions: # Required to upload/save artifact, otherwise you'll get # "Error: Resource not accessible by integration" contents: write # Required to post comment, otherwise you'll get # "Error: Resource not accessible by integration" pull-requests: write needs: - code-quality runs-on: ubuntu-latest if: github.event_name == 'pull_request' steps: - name: 📥 Checkout the repository uses: actions/checkout@v4 - name: 📦 Create zip file for the integration run: | cd "${{ github.workspace }}/custom_components/deebot" zip deebot.zip -r ./ mv deebot.zip "${{ github.workspace }}/" - name: 📤 Create comment with the artifiactory uses: gavv/pull-request-artifacts@v2 with: # Commit hash that triggered PR commit: ${{ github.event.pull_request.head.sha }} # Token for current repo (used to post PR comment) repo-token: ${{ secrets.GITHUB_TOKEN }} artifacts-branch: artifacts inter-link: false comment-title: | 🤖 Pull request artifacts For testing please download the zip file below and extract it in `[config folder]/custom_components/deebot`. # Whitespace-separated list of files to upload artifacts: | deebot.zip ================================================ FILE: .github/workflows/codeql-analysis.yml ================================================ # For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: - dev pull_request: # The branches below must be a subset of the branches above branches: - dev schedule: - cron: "20 10 * * 0" jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: ["python"] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] # Learn more: # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language # - run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 ================================================ FILE: .github/workflows/cron.yaml ================================================ name: Cron actions on: schedule: - cron: "0 0 * * *" jobs: validate: runs-on: "ubuntu-latest" name: Validate steps: - uses: "actions/checkout@v4" - name: HACS validation uses: "hacs/action@main" with: category: "integration" - name: Hassfest validation uses: "home-assistant/actions/hassfest@master" ================================================ FILE: .github/workflows/release-drafter.yml ================================================ name: Release Drafter on: push: branches: - dev jobs: update_release_draft: runs-on: ubuntu-latest permissions: contents: write steps: - uses: release-drafter/release-drafter@v5 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .github/workflows/release.yml ================================================ # This GitHub action workflow is meant to be copyable to any repo that have the same structure. # - Your integration exist under custom_components/{INTEGRATION_NAME}/[integration files] # - You are using GitHub releases to publish new versions # - You have a INTEGRATION_VERSION constant in custom_components/{INTEGRATION_NAME}/const.py name: Release Workflow on: release: types: [published] jobs: release: name: Release runs-on: ubuntu-latest permissions: contents: write deployments: write steps: - name: 📥 Checkout the repository uses: actions/checkout@v4 - name: 🔢 Get release version id: version uses: home-assistant/actions/helpers/version@master - name: ℹ️ Get integration information id: information run: | name=$(find custom_components/ -type d -maxdepth 1 | tail -n 1 | cut -d "/" -f2) echo "::set-output name=name::$name" min_ha_version=$(jq -r '.homeassistant' ${{ github.workspace }}/hacs.json) echo "::set-output name=min_ha_version::$min_ha_version" - name: 🖊️ Set version number run: | sed -i '/INTEGRATION_VERSION = /c\INTEGRATION_VERSION = "${{ steps.version.outputs.version }}"' \ "${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/const.py" jq '.version = "${{ steps.version.outputs.version }}"' \ "${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/manifest.json" > tmp \ && mv -f tmp "${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/manifest.json" - name: 🖊️ Set min required HA version run: | sed -i '/MIN_REQUIRED_HA_VERSION = /c\MIN_REQUIRED_HA_VERSION = "${{ steps.information.outputs.min_ha_version }}"' \ "${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/const.py" - name: 👀 Validate data run: | echo "Version found :${{ steps.version.outputs.version }}"; if [[ '${{ steps.version.outputs.version }}' == '""' ]]; then echo "Did not correctly identify version" exit 1 fi if ! grep -q 'INTEGRATION_VERSION = "${{ steps.version.outputs.version }}"' ${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/const.py; then echo "The version in custom_components/${{ steps.information.outputs.name }}/const.py was not correct" cat ${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/const.py | grep INTEGRATION_VERSION exit 1 fi manifestversion=$(jq -r '.version' ${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/manifest.json) if [ "$manifestversion" != "${{ steps.version.outputs.version }}" ]; then echo "The version in custom_components/${{ steps.information.outputs.name }}/manifest.json was not correct" echo "$manifestversion" exit 1 fi if ! grep -q 'MIN_REQUIRED_HA_VERSION = "${{ steps.information.outputs.min_ha_version }}"' ${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/const.py; then echo "The MIN_REQUIRED_HA_VERSION in custom_components/${{ steps.information.outputs.name }}/const.py was not correct" cat ${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/const.py | grep MIN_REQUIRED_HA_VERSION exit 1 fi - name: 📦 Create zip file for the integration run: | cd "${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}" zip ${{ steps.information.outputs.name }}.zip -r ./ - name: 📤 Upload the zip file as a release asset uses: actions/upload-release-asset@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ github.event.release.upload_url }} asset_path: "${{ github.workspace }}/custom_components/${{ steps.information.outputs.name }}/${{ steps.information.outputs.name }}.zip" asset_name: ${{ steps.information.outputs.name }}.zip asset_content_type: application/zip ================================================ FILE: .github/workflows/stale.yml ================================================ name: "Close stale issues" on: schedule: - cron: "0 0 * * *" issue_comment: types: - created jobs: stale: runs-on: ubuntu-latest permissions: issues: write steps: - uses: actions/stale@v9 with: days-before-stale: 7 days-before-close: 7 days-before-pr-stale: -1 stale-issue-message: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. stale-issue-label: stale only-labels: need-more-information ================================================ FILE: .gitignore ================================================ __pycache__ pythonenv* venv .venv .coverage .idea .mypy_cache .pytest_cache /config ================================================ FILE: .pre-commit-config.yaml ================================================ ci: skip: - mypy - pylint default_language_version: python: python3.11 repos: - repo: https://github.com/asottile/pyupgrade rev: v3.15.0 hooks: - id: pyupgrade args: [--py311-plus] - repo: https://github.com/psf/black rev: 23.11.0 hooks: - id: black args: - --quiet <<: &python-files-with-tests files: ^((custom_components|tests)/.+)?[^/]+\.py$ - repo: https://github.com/codespell-project/codespell rev: v2.2.6 hooks: - id: codespell args: - --ignore-words-list=hass,deebot - --skip="./.*,*.csv,*.json" - --quiet-level=2 exclude_types: [csv, json] - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 additional_dependencies: - flake8-docstrings==1.6.0 - pydocstyle==6.1.1 <<: &python-files files: ^(custom_components/.+)?[^/]+\.py$ - repo: https://github.com/PyCQA/bandit rev: 1.7.5 hooks: - id: bandit args: - --quiet - --format=custom - --configfile=bandit.yaml <<: *python-files-with-tests - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-executables-have-shebangs - id: check-merge-conflict - id: detect-private-key - id: no-commit-to-branch args: - -b - dev - id: requirements-txt-fixer - id: mixed-line-ending args: - --fix=lf stages: [manual] - id: pretty-format-json args: - --autofix - --no-ensure-ascii - --top-keys=domain,name files: manifest\.json$ - repo: https://github.com/pre-commit/mirrors-prettier rev: v3.1.0 hooks: - id: prettier additional_dependencies: - prettier@3.1.0 - prettier-plugin-sort-json@3.1.0 exclude_types: - python exclude: manifest\.json$ - repo: https://github.com/adrienverge/yamllint.git rev: v1.33.0 hooks: - id: yamllint - repo: local hooks: # Run mypy through our wrapper script in order to get the possible # pyenv and/or virtualenv activated; it may not have been e.g. if # committing from a GUI tool that was not launched from an activated # shell. - id: mypy name: Check with mypy entry: scripts/run-in-env.sh mypy language: script types: [python] <<: *python-files - id: pylint name: Check with pylint entry: scripts/run-in-env.sh pylint language: script types: [python] <<: *python-files - repo: https://github.com/pre-commit-ci/pre-commit-ci-config rev: v1.6.1 hooks: - id: check-pre-commit-ci-config - repo: https://github.com/python-jsonschema/check-jsonschema rev: 0.27.2 hooks: - id: check-github-workflows - id: check-dependabot - id: check-jsonschema name: Check translations files files: ^custom_components/deebot/translations/ types: - json args: - --schemafile - translations.schema.json ================================================ FILE: .prettierrc.js ================================================ /** @type {import("prettier").Config} */ module.exports = { plugins: [require.resolve("prettier-plugin-sort-json")], jsonRecursiveSort: true, }; ================================================ FILE: .vscode/launch.json ================================================ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 { "configurations": [ { "host": "localhost", "justMyCode": false, // Example of attaching to local debug server "name": "Python: Attach Local", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "." } ], "port": 5678, "request": "attach", "type": "python" }, { "host": "homeassistant.local", // Example of attaching to my production server "name": "Python: Attach Remote", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/usr/src/homeassistant" } ], "port": 5678, "request": "attach", "type": "python" } ], "version": "0.2.0" } ================================================ FILE: .vscode/settings.json ================================================ { "files.associations": { "*.yaml": "home-assistant" }, "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.pythonPath": "/usr/local/bin/python" } ================================================ FILE: .vscode/tasks.json ================================================ // See https://code.visualstudio.com/docs/editor/tasks { "tasks": [ { "command": "scripts/develop", "label": "Run Home Assistant", "problemMatcher": [], "type": "shell" }, { "command": "scripts/setup", "label": "Upgrade environment", "problemMatcher": [], "type": "shell" }, { "command": "scripts/test", "label": "Run tests", "problemMatcher": [], "type": "shell" }, { "command": "scripts/lint", "label": "Run lint checks", "problemMatcher": [], "type": "shell" } ], "version": "2.0.0" } ================================================ FILE: .yamllint ================================================ rules: braces: level: error min-spaces-inside: 0 max-spaces-inside: 1 min-spaces-inside-empty: -1 max-spaces-inside-empty: -1 brackets: level: error min-spaces-inside: 0 max-spaces-inside: 0 min-spaces-inside-empty: -1 max-spaces-inside-empty: -1 colons: level: error max-spaces-before: 0 max-spaces-after: 1 commas: level: error max-spaces-before: 0 min-spaces-after: 1 max-spaces-after: 1 comments: level: error require-starting-space: true min-spaces-from-content: 2 comments-indentation: level: error document-end: level: error present: false document-start: level: error present: false empty-lines: level: error max: 1 max-start: 0 max-end: 1 hyphens: level: error max-spaces-after: 1 indentation: level: error spaces: 2 indent-sequences: true check-multi-line-strings: false key-duplicates: level: error line-length: disable new-line-at-end-of-file: level: error new-lines: level: error type: unix trailing-spaces: level: error truthy: disable ================================================ FILE: CONTRIBUTING.md ================================================ # Contribution guidelines Contributing to this project should be as easy and transparent as possible, whether it's: - Reporting a bug - Discussing the current state of the code - Submitting a fix - Proposing new features ## Github is used for everything Github is used to host code, to track issues and feature requests, as well as accept pull requests. Pull requests are the best way to propose changes to the codebase. 1. Fork the repo and create your branch from `dev`. 2. Run `pip install -r requirements.txt` to install all requirements 3. Run `pre-commit install --install-hooks` to setup up pre-commit (used for code quality checks) 4. If you've changed something, update the documentation. 5. Make sure your code lints (using pre-commit). 6. Test you contribution. 7. Issue that pull request! ## Any contributions you make will be under project license In short, when you submit code changes, your submissions are understood to be under the same [License](../LICENSE) that covers the project. Feel free to contact the maintainers if that's a concern. ## Report bugs using Github's [issues](../../issues) GitHub issues are used to track public bugs. Report a bug by [opening a new issue](../../issues/new/choose); it's that easy! ## Write bug reports with detail, background, and sample code **Great Bug Reports** tend to have: - A quick summary and/or background - Steps to reproduce - Be specific! - Give sample code if you can. - What you expected would happen - What actually happens - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) People _love_ thorough bug reports. I'm not even kidding. ## Use a Consistent Coding Style Use [black](https://github.com/ambv/black) to make sure the code follows the style. ## Test your code modification This custom component is based on [integration_blueprint template](https://github.com/custom-components/integration_blueprint). It comes with development environment in a container, easy to launch if you use Visual Studio Code. With this container you will have a stand alone Home Assistant instance running and already configured with the included [`.devcontainer/configuration.yaml`](./.devcontainer/configuration.yaml) file. ## License By contributing, you agree that your contributions will be licensed under the projects License. ================================================ FILE: LICENSE ================================================ 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 . ================================================ FILE: README.md ================================================ # Home Assistant integration for deebot vacuums Buy Me A Coffee **This integration has been available directly in the Home Assistant core since version `2024.2.0`. For more information, please check out the [Ecovacs HA documentation](https://www.home-assistant.io/integrations/ecovacs/).** With this custom component you'll be able to - play/pause - locate - send to home - clean[auto|map|area] - track live map - sensors - and much more... ## Useful links - [Documentation](https://deebot.readthedocs.io/integrations/home-assistant/) - [FAQ](https://deebot.readthedocs.io/home/faq/) - [GitHub](https://github.com/DeebotUniverse/Deebot-4-Home-Assistant) - [BuyMe~~Coffee~~Beer? 🍺🙈](https://buymeacoffee.com/edenhaus) ## Thanks My heartfelt thanks to: - [Deebot-for-Home-Assistant](https://github.com/And3rsL/Deebot-for-Home-Assistant), After all, this is a Deebot-for-Home-Assistant fork :) - [integration template](https://github.com/custom-components/integration_blueprint), a template for HA integrations ================================================ FILE: bandit.yaml ================================================ # https://bandit.readthedocs.io/en/latest/config.html tests: - B103 - B108 - B306 - B307 - B313 - B314 - B315 - B316 - B317 - B318 - B319 - B320 - B601 - B602 - B604 - B608 - B609 ================================================ FILE: custom_components/__init__.py ================================================ """Custom components module.""" ================================================ FILE: custom_components/deebot/__init__.py ================================================ """Support for Deebot Vacuums.""" import asyncio import logging from typing import Any from awesomeversion import AwesomeVersion from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICES, CONF_USERNAME, CONF_VERIFY_SSL, Platform from homeassistant.const import __version__ as HA_VERSION from homeassistant.core import HomeAssistant from homeassistant.helpers.issue_registry import ( IssueSeverity, async_create_issue, async_delete_issue, ) from custom_components.deebot.controller import DeebotController from .const import ( CONF_BUMPER, CONF_CLIENT_DEVICE_ID, DOMAIN, INTEGRATION_VERSION, MIN_REQUIRED_HA_VERSION, STARTUP_MESSAGE, ) from .util import get_bumper_device_id _LOGGER = logging.getLogger(__name__) PLATFORMS = [ Platform.BINARY_SENSOR, Platform.BUTTON, Platform.IMAGE, Platform.NUMBER, Platform.SELECT, Platform.SENSOR, Platform.SWITCH, Platform.VACUUM, ] def is_ha_supported() -> bool: """Return True, if current HA version is supported.""" if AwesomeVersion(HA_VERSION) >= MIN_REQUIRED_HA_VERSION: return True _LOGGER.error( 'Unsupported HA version! Please upgrade home assistant at least to "%s"', MIN_REQUIRED_HA_VERSION, ) return False async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up this integration using UI.""" if DOMAIN not in hass.data: # Print startup message _LOGGER.info(STARTUP_MESSAGE) if not is_ha_supported(): return False if INTEGRATION_VERSION == "main": _LOGGER.warning("Beta-Version! Use this version only for testing.") if AwesomeVersion(HA_VERSION) >= "2024.2.0b0": async_create_issue( hass, DOMAIN, "deprecated_integration_issue", is_fixable=False, issue_domain=DOMAIN, severity=IssueSeverity.WARNING, translation_key="deprecated_integration_issue", translation_placeholders={ "config_url": "/config/integrations/dashboard/add?domain=ecovacs", "docs_url": "https://www.home-assistant.io/integrations/ecovacs/", }, ) # Store an instance of the "connecting" class that does the work of speaking # with your actual devices. controller = DeebotController(hass, {**entry.data, **entry.options}) await controller.initialize() hass.data.setdefault(DOMAIN, {})[entry.entry_id] = controller await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) # Reload entry when its updated. entry.async_on_unload(entry.add_update_listener(async_reload_entry)) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" # This is called when an entry/configured device is to be removed. The class # needs to unload itself, and remove callbacks. See the classes for further # details unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if unload_ok: await hass.data[DOMAIN][entry.entry_id].teardown() hass.data[DOMAIN].pop(entry.entry_id) if len(hass.data[DOMAIN]) == 0: hass.data.pop(DOMAIN) async_delete_issue( hass, DOMAIN, "deprecated_integration_issue", ) return unload_ok async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: """Reload the config entry when it changed.""" await hass.config_entries.async_reload(entry.entry_id) async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Migrate old entry.""" _LOGGER.debug("Migrating from version %d", config_entry.version) if config_entry.version == 1: new: dict[str, Any] = {**config_entry.data, CONF_VERIFY_SSL: True} device_id = "deviceid" devices = new.pop(device_id, {}) new.pop("show_color_rooms") new.pop("live_map") new[CONF_DEVICES] = devices.get(device_id, []) config_entry.data = {**new} config_entry.version = 2 if config_entry.version == 2: new = {**config_entry.data} if new.get(CONF_USERNAME) == CONF_BUMPER: new[CONF_CLIENT_DEVICE_ID] = get_bumper_device_id(hass) config_entry.data = {**new} config_entry.version = 3 if config_entry.version == 3: new = {**config_entry.data} devices = new.pop(CONF_DEVICES) config_entry.data = {**new} config_entry.options = {CONF_DEVICES: devices} config_entry.version = 4 _LOGGER.info("Migration to version %d successful", config_entry.version) return True ================================================ FILE: custom_components/deebot/binary_sensor.py ================================================ """Binary sensor module.""" from collections.abc import Callable from dataclasses import dataclass from typing import Generic from deebot_client.capabilities import CapabilityEvent from deebot_client.events.water_info import WaterInfoEvent from homeassistant.components.binary_sensor import ( BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN from .controller import DeebotController from .entity import DeebotEntity, DeebotEntityDescription, EventT @dataclass(kw_only=True, frozen=True) class DeebotBinarySensorEntityDescription( BinarySensorEntityDescription, # type: ignore DeebotEntityDescription, Generic[EventT], ): """Class describing Deebot binary sensor entity.""" value_fn: Callable[[EventT], bool | None] icon_fn: Callable[[bool | None], str | None] ENTITY_DESCRIPTIONS: tuple[DeebotBinarySensorEntityDescription, ...] = ( DeebotBinarySensorEntityDescription[WaterInfoEvent]( capability_fn=lambda caps: caps.water, value_fn=lambda e: e.mop_attached, icon_fn=lambda is_on: "mdi:water" if is_on else "mdi:water-off", key="mop_attached", translation_key="mop_attached", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add entities for passed config_entry in HA.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] controller.register_platform_add_entities( DeebotBinarySensor, ENTITY_DESCRIPTIONS, async_add_entities ) class DeebotBinarySensor(DeebotEntity[CapabilityEvent[EventT], DeebotBinarySensorEntityDescription], BinarySensorEntity): # type: ignore """Deebot binary sensor.""" async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_event(event: EventT) -> None: self._attr_is_on = self.entity_description.value_fn(event) self._attr_icon = self.entity_description.icon_fn(self._attr_is_on) self.async_write_ha_state() self._subscribe(self._capability.event, on_event) ================================================ FILE: custom_components/deebot/button.py ================================================ """Binary sensor module.""" from collections.abc import Sequence from dataclasses import dataclass from deebot_client.capabilities import CapabilityExecute from deebot_client.device import Device from deebot_client.events import LifeSpan from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN from .controller import DeebotController from .entity import DeebotEntity, DeebotEntityDescription @dataclass(kw_only=True, frozen=True) class DeebotButtonEntityDescription( ButtonEntityDescription, # type: ignore DeebotEntityDescription, ): """Class describing debbot button entity.""" ENTITY_DESCRIPTIONS: tuple[DeebotButtonEntityDescription, ...] = ( DeebotButtonEntityDescription( capability_fn=lambda caps: caps.map.relocation if caps.map else None, key="relocate", translation_key="relocate", icon="mdi:map-marker-question", entity_registry_enabled_default=True, # Can be enabled as they don't poll data entity_category=EntityCategory.DIAGNOSTIC, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add entities for passed config_entry in HA.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] controller.register_platform_add_entities( DeebotButtonEntity, ENTITY_DESCRIPTIONS, async_add_entities ) def generate_reset_life_span( device: Device, ) -> Sequence[DeebotResetLifeSpanButtonEntity]: return [ DeebotResetLifeSpanButtonEntity(device, component) for component in device.capabilities.life_span.types ] controller.register_platform_add_entities_generator( async_add_entities, generate_reset_life_span ) class DeebotResetLifeSpanButtonEntity( DeebotEntity[None, ButtonEntityDescription], ButtonEntity, # type: ignore ): """Deebot reset life span button entity.""" def __init__(self, device: Device, component: LifeSpan): key = f"life_span_{component.name.lower()}_reset" entity_description = ButtonEntityDescription( key=key, translation_key=key, icon="mdi:air-filter" if component == LifeSpan.FILTER else "mdi:broom", entity_registry_enabled_default=True, # Can be enabled as they don't poll data entity_category=EntityCategory.CONFIG, ) super().__init__(device, None, entity_description) self._command = device.capabilities.life_span.reset(component) async def async_press(self) -> None: """Press the button.""" await self._device.execute_command(self._command) class DeebotButtonEntity( DeebotEntity[CapabilityExecute, DeebotButtonEntityDescription], ButtonEntity, # type: ignore ): """Deebot button entity.""" async def async_press(self) -> None: """Press the button.""" await self._device.execute_command(self._capability.execute()) ================================================ FILE: custom_components/deebot/config_flow.py ================================================ """Config flow for Deebot integration.""" import logging import random import string from types import MappingProxyType from typing import Any import voluptuous as vol from aiohttp import ClientError from deebot_client.api_client import ApiClient from deebot_client.authentication import Authenticator, create_rest_config from deebot_client.exceptions import InvalidAuthenticationError from deebot_client.models import DeviceInfo from deebot_client.util import md5 from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow from homeassistant.const import ( CONF_DEVICES, CONF_MODE, CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant, callback from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers import aiohttp_client, selector from . import get_bumper_device_id from .const import ( BUMPER_CONFIGURATION, CONF_CLIENT_DEVICE_ID, CONF_CONTINENT, CONF_COUNTRY, CONF_MODE_BUMPER, CONF_MODE_CLOUD, DOMAIN, ) _LOGGER = logging.getLogger(__name__) # Generate a random device ID on each bootup DEEBOT_API_DEVICEID = "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(8) ) class DeebotConfigFlow(ConfigFlow, domain=DOMAIN): # type: ignore """Handle a config flow for Deebot.""" VERSION = 4 def __init__(self) -> None: self._data: dict[str, Any] = {} self._devices: list[DeviceInfo] = [] self._mode: str | None = None self._entry: ConfigEntry | None = None @staticmethod @callback # type: ignore[misc] def async_get_options_flow( config_entry: ConfigEntry, ) -> "DeebotOptionsFlowHandler": """Get the options flow for this handler.""" return DeebotOptionsFlowHandler(config_entry) async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle the initial step.""" errors = {} data = {} if user_input is not None: data.update(user_input) if len(data[CONF_COUNTRY]) != 2: errors[CONF_COUNTRY] = "invalid_country" if len(data[CONF_CONTINENT]) != 2: errors[CONF_CONTINENT] = "invalid_continent" if not errors: try: self._devices = await _retrieve_devices(self.hass, data) except ClientError: _LOGGER.debug("Cannot connect", exc_info=True) errors["base"] = "cannot_connect" except InvalidAuthenticationError: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.error("Unexpected exception", exc_info=True) errors["base"] = "unknown" if not errors: if self._entry: # reauthentication self.hass.config_entries.async_update_entry(self._entry, data=data) self.hass.async_create_task( self.hass.config_entries.async_reload(self._entry.entry_id) ) return self.async_abort(reason="reauth_successful") self._async_abort_entries_match( {CONF_USERNAME: user_input[CONF_USERNAME]} ) if len(self._devices) == 0: return self.async_abort(reason="no_supported_devices_found") self._data.update(data) return await self.async_step_options() if self._entry: data.update(self._entry.data) elif self.show_advanced_options and self._mode is None: return await self.async_step_user_advanced() return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required( CONF_USERNAME, default=data.get(CONF_USERNAME, vol.UNDEFINED), ): selector.TextSelector( selector.TextSelectorConfig(type=selector.TextSelectorType.TEXT) ), vol.Required(CONF_PASSWORD): selector.TextSelector( selector.TextSelectorConfig( type=selector.TextSelectorType.PASSWORD ) ), vol.Required( CONF_COUNTRY, default=data.get(CONF_COUNTRY, vol.UNDEFINED), ): selector.TextSelector( selector.TextSelectorConfig(type=selector.TextSelectorType.TEXT) ), vol.Required( CONF_CONTINENT, default=data.get(CONF_CONTINENT, vol.UNDEFINED), ): selector.TextSelector( selector.TextSelectorConfig(type=selector.TextSelectorType.TEXT) ), } ), errors=errors, ) async def async_step_user_advanced( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle an advanced mode flow initialized by the user.""" if user_input is not None: self._mode = user_input.get(CONF_MODE, CONF_MODE_CLOUD) if self._mode == CONF_MODE_BUMPER: config = { **BUMPER_CONFIGURATION, CONF_CLIENT_DEVICE_ID: get_bumper_device_id(self.hass), } return await self.async_step_user(user_input=config) return await self.async_step_user() return self.async_show_form( step_id="user_advanced", data_schema=vol.Schema( { vol.Required( CONF_MODE, default=CONF_MODE_CLOUD ): selector.SelectSelector( selector.SelectSelectorConfig( options=[ CONF_MODE_CLOUD, CONF_MODE_BUMPER, ] ) ) } ), ) async def async_step_options( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle the options step.""" errors = {} if user_input is not None: try: if len(user_input[CONF_DEVICES]) < 1: errors[CONF_DEVICES] = "select_robots" else: return self.async_create_entry( title=self._data[CONF_USERNAME], data=self._data, options=user_input, ) except Exception: # pylint: disable=broad-except _LOGGER.error("Unexpected exception", exc_info=True) errors["base"] = "unknown" # If there is no user input or there were errors, show the form again, including any errors that were found with the input. return self.async_show_form( step_id="options", data_schema=_get_options_schema(self._devices, {}), errors=errors, ) async def async_step_reauth(self, data: dict[str, Any]) -> FlowResult: """Handle initiation of re-authentication.""" self._entry = self.hass.config_entries.async_get_entry(self.context["entry_id"]) return await self.async_step_user(data) def _get_options_schema( devices: list[DeviceInfo], defaults: dict[str, Any] | MappingProxyType[str, Any] ) -> vol.Schema: """Return options schema.""" select_options = [] for entry in devices: api_info = entry.api_device_info label = api_info.get("nick", api_info["name"]) if not label: label = api_info["name"] select_options.append( selector.SelectOptionDict(value=api_info["name"], label=label) ) return vol.Schema( { vol.Required( CONF_DEVICES, default=defaults.get(CONF_DEVICES, vol.UNDEFINED) ): selector.SelectSelector( selector.SelectSelectorConfig( options=select_options, multiple=True, ) ) } ) async def _retrieve_devices( hass: HomeAssistant, domain_config: dict[str, Any] ) -> list[DeviceInfo]: verify_ssl = domain_config.get(CONF_VERIFY_SSL, True) deebot_config = create_rest_config( aiohttp_client.async_get_clientsession(hass, verify_ssl=verify_ssl), device_id=DEEBOT_API_DEVICEID, alpha_2_country=domain_config[CONF_COUNTRY].upper(), ) authenticator = Authenticator( deebot_config, domain_config[CONF_USERNAME], md5(domain_config[CONF_PASSWORD]), ) api_client = ApiClient(authenticator) devices = await api_client.get_devices() return [device for device in devices if isinstance(device, DeviceInfo)] class DeebotOptionsFlowHandler(OptionsFlow): # type: ignore[misc] """Handle deebot options.""" def __init__(self, config_entry: ConfigEntry) -> None: """Initialize options flow.""" self._config_entry = config_entry self._devices: list[DeviceInfo] | None = None async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Manage options.""" errors = {} if user_input is not None: try: if len(user_input[CONF_DEVICES]) < 1: errors[CONF_DEVICES] = "select_robots" else: return self.async_create_entry( title=self._config_entry.title, data=user_input, ) except Exception: # pylint: disable=broad-except _LOGGER.error("Unexpected exception", exc_info=True) errors["base"] = "unknown" if user_input is None: user_input = self._config_entry.options if not self._devices: try: self._devices = await _retrieve_devices( self.hass, self._config_entry.data ) except ClientError: _LOGGER.debug("Cannot connect", exc_info=True) return self.async_abort(reason="cannot_connect") except InvalidAuthenticationError: return self.async_abort(reason="invalid_auth") except Exception: # pylint: disable=broad-except _LOGGER.error("Unexpected exception on getting devices", exc_info=True) return self.async_abort(reason="unknown_get_devices") if len(self._devices) == 0: return self.async_abort(reason="no_supported_devices_found") return self.async_show_form( step_id="init", data_schema=_get_options_schema(self._devices, user_input), errors=errors, ) ================================================ FILE: custom_components/deebot/const.py ================================================ """Const module.""" from collections.abc import Mapping from deebot_client.events import ( BatteryEvent, CleanLogEvent, ErrorEvent, Event, FanSpeedEvent, LifeSpanEvent, RoomsEvent, StateEvent, StatsEvent, WaterInfoEvent, ) from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL ################################ # Do not change! Will be set by release workflow INTEGRATION_VERSION = "dev" # git tag will be used MIN_REQUIRED_HA_VERSION = "2024.1.0b0" # set min required version in hacs.json ################################ # Values below can be changed DOMAIN = "deebot" ISSUE_URL = "https://github.com/DeebotUniverse/Deebot-4-Home-Assistant/issues" STARTUP_MESSAGE = f""" ------------------------------------------------------------------- {DOMAIN} Version: {INTEGRATION_VERSION} This is a custom component If you have any issues with this you need to open an issue here: {ISSUE_URL} ------------------------------------------------------------------- """ CONF_COUNTRY = "country" CONF_CONTINENT = "continent" CONF_BUMPER = "Bumper" CONF_MODE_BUMPER = CONF_BUMPER CONF_MODE_CLOUD = "Cloud (recommended)" CONF_CLIENT_DEVICE_ID = "client_device_id" # Bumper has no auth and serves the urls for all countries/continents BUMPER_CONFIGURATION = { CONF_CONTINENT: "eu", CONF_COUNTRY: "it", CONF_PASSWORD: CONF_BUMPER, CONF_USERNAME: CONF_BUMPER, CONF_VERIFY_SSL: False, # required as bumper is using self signed certificates } DEEBOT_DEVICES = f"{DOMAIN}_devices" REFRESH_STR_TO_EVENT_DTO: Mapping[str, type[Event]] = { "battery": BatteryEvent, "clean_logs": CleanLogEvent, "error": ErrorEvent, "fan_speed": FanSpeedEvent, "life_spans": LifeSpanEvent, "rooms": RoomsEvent, "stats": StatsEvent, "status": StateEvent, "water": WaterInfoEvent, } REFRESH_MAP = "map" EVENT_CLEANING_JOB = "deebot_cleaning_job" EVENT_CUSTOM_COMMAND = "deebot_custom_command" ================================================ FILE: custom_components/deebot/controller.py ================================================ """Controller module.""" import logging import random import string from collections.abc import Callable, Mapping, Sequence from typing import Any from deebot_client.api_client import ApiClient from deebot_client.authentication import Authenticator, create_rest_config from deebot_client.const import UNDEFINED from deebot_client.device import Device from deebot_client.exceptions import InvalidAuthenticationError from deebot_client.models import ApiDeviceInfo, DeviceInfo from deebot_client.mqtt_client import MqttClient, create_mqtt_config from deebot_client.util import md5 from homeassistant.const import ( CONF_DEVICES, CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers import aiohttp_client from homeassistant.helpers.device_registry import DeviceEntry from homeassistant.helpers.entity import EntityDescription from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.ssl import get_default_no_verify_context from custom_components.deebot.entity import DeebotEntity, DeebotEntityDescription from .const import CONF_CLIENT_DEVICE_ID, CONF_COUNTRY _LOGGER = logging.getLogger(__name__) _EntityGeneratorType = Callable[ [Device], Sequence[DeebotEntity[Any, EntityDescription]] ] class DeebotController: """Deebot Controller.""" def __init__(self, hass: HomeAssistant, config: Mapping[str, Any]): self._hass_config: Mapping[str, Any] = config self._hass: HomeAssistant = hass self._devices: list[Device] = [] verify_ssl = config.get(CONF_VERIFY_SSL, True) device_id = config.get(CONF_CLIENT_DEVICE_ID) if not device_id: # Generate a random device ID on each bootup device_id = "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(12) ) country = config.get(CONF_COUNTRY, "it").upper() deebot_config = create_rest_config( aiohttp_client.async_get_clientsession(self._hass, verify_ssl=verify_ssl), device_id=device_id, alpha_2_country=country, ) self._authenticator = Authenticator( deebot_config, config.get(CONF_USERNAME, ""), md5(config.get(CONF_PASSWORD, "")), ) self._api_client = ApiClient(self._authenticator) mqtt_config = create_mqtt_config( device_id=device_id, country=country, ssl_context=UNDEFINED if verify_ssl else get_default_no_verify_context(), ) self._mqtt: MqttClient = MqttClient(mqtt_config, self._authenticator) async def initialize(self) -> None: """Init controller.""" try: await self.teardown() devices = await self._api_client.get_devices() await self._mqtt.connect() for device in devices: if not isinstance(device, DeviceInfo): # Legacy devices are not supported continue if device.api_device_info["name"] in self._hass_config.get( CONF_DEVICES, [] ): bot = Device(device, self._authenticator) _LOGGER.debug( "New vacbot found: %s", device.api_device_info["name"] ) await bot.initialize(self._mqtt) self._devices.append(bot) _LOGGER.debug("Controller initialize complete") except InvalidAuthenticationError as ex: raise ConfigEntryAuthFailed from ex except Exception as ex: msg = "Error during setup" _LOGGER.error(msg, exc_info=True) raise ConfigEntryNotReady(msg) from ex def register_platform_add_entities( self, entity_class: type[DeebotEntity], descriptions: tuple[DeebotEntityDescription, ...], async_add_entities: AddEntitiesCallback, ) -> None: """Create entities from descriptions and add them.""" new_entites: list[DeebotEntity] = [] for device in self._devices: for description in descriptions: if capability := description.capability_fn(device.capabilities): new_entites.append(entity_class(device, capability, description)) if new_entites: async_add_entities(new_entites) def register_platform_add_entities_generator( self, async_add_entities: AddEntitiesCallback, functions: _EntityGeneratorType | tuple[_EntityGeneratorType, ...], ) -> None: """Add entities generated through the provided function.""" new_entites: list[DeebotEntity[Any, EntityDescription]] = [] for device in self._devices: if callable(functions): functions = (functions,) for func in functions: new_entites.extend(func(device)) if new_entites: async_add_entities(new_entites) def get_device_info(self, device: DeviceEntry) -> ApiDeviceInfo | dict[str, str]: """Get the device info for the given entry.""" for bot in self._devices: for identifier in device.identifiers: if bot.device_info.did == identifier[1]: return bot.device_info.api_device_info _LOGGER.error("Could not find the device with entry: %s", device.json_repr) return {"error": "Could not find the device"} async def teardown(self) -> None: """Disconnect controller.""" for bot in self._devices: await bot.teardown() await self._mqtt.disconnect() await self._authenticator.teardown() ================================================ FILE: custom_components/deebot/diagnostics.py ================================================ """Diagnostics support for deebot.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICES, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntry from . import DOMAIN from .controller import DeebotController REDACT_CONFIG = {CONF_USERNAME, CONF_PASSWORD, CONF_DEVICES, "title"} REDACT_DEVICE = {"did", "name", "homeId"} async def async_get_device_diagnostics( hass: HomeAssistant, config_entry: ConfigEntry, device: DeviceEntry ) -> dict[str, Any]: """Return diagnostics for a device.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] diag: dict[str, Any] = { "config": async_redact_data(config_entry.as_dict(), REDACT_CONFIG) } diag["device"] = async_redact_data( controller.get_device_info(device), REDACT_DEVICE ) return diag ================================================ FILE: custom_components/deebot/entity.py ================================================ """Deebot entity module.""" from collections.abc import Callable, Coroutine from dataclasses import dataclass from typing import Any, Generic, TypeVar from deebot_client.capabilities import Capabilities from deebot_client.device import Device from deebot_client.events import AvailabilityEvent from deebot_client.events.base import Event from homeassistant.helpers import device_registry as dr from homeassistant.helpers.entity import DeviceInfo, Entity, EntityDescription from .const import DOMAIN _EntityDescriptionT = TypeVar("_EntityDescriptionT", bound=EntityDescription) CapabilityT = TypeVar("CapabilityT") EventT = TypeVar("EventT", bound=Event) @dataclass(kw_only=True, frozen=True) class DeebotEntityDescription( EntityDescription, # type: ignore Generic[CapabilityT], ): """Deebot Entity Description.""" capability_fn: Callable[[Capabilities], CapabilityT | None] class DeebotEntity(Entity, Generic[CapabilityT, _EntityDescriptionT]): # type: ignore """Deebot entity.""" entity_description: _EntityDescriptionT _attr_should_poll = False _attr_has_entity_name = True _always_available: bool = False _subscribed_events: set[type[Event]] = set() def __init__( self, device: Device, capability: CapabilityT, entity_description: _EntityDescriptionT | None = None, **kwargs: Any, ): """Initialize entity.""" super().__init__(**kwargs) if entity_description: self.entity_description = entity_description elif not hasattr(self, "entity_description"): raise ValueError( '"entity_description" must be either set as class variable or passed on init!' ) self._device = device self._capability = capability self._attr_unique_id = self._device.device_info.did if self.entity_description.key: self._attr_unique_id += f"_{self.entity_description.key}" @property def device_info(self) -> DeviceInfo | None: """Return device specific attributes.""" device_info = self._device.device_info info = DeviceInfo( identifiers={(DOMAIN, device_info.did)}, manufacturer="Ecovacs", sw_version=self._device.fw_version, serial_number=device_info.name, ) if nick := device_info.api_device_info.get("nick"): info["name"] = nick if model := device_info.api_device_info.get("deviceName"): info["model"] = model if mac := self._device.mac: info["connections"] = {(dr.CONNECTION_NETWORK_MAC, mac)} return info async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() if not self._always_available: async def on_available(event: AvailabilityEvent) -> None: self._attr_available = event.available self.async_write_ha_state() self._subscribe(AvailabilityEvent, on_available) def _subscribe( self, event_type: type[EventT], callback: Callable[[EventT], Coroutine[Any, Any, None]], ) -> None: """Subscribe to events.""" self._subscribed_events.add(event_type) self.async_on_remove(self._device.events.subscribe(event_type, callback)) async def async_update(self) -> None: """Update the entity. Only used by the generic entity update service. """ for event_type in self._subscribed_events: self._device.events.request_refresh(event_type) ================================================ FILE: custom_components/deebot/image.py ================================================ """Support for Deebot image entities.""" from collections.abc import MutableMapping, Sequence from typing import Any from deebot_client.capabilities import CapabilityMap from deebot_client.device import Device from deebot_client.events.map import CachedMapInfoEvent, MapChangedEvent from homeassistant.components.image import ImageEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import EntityDescription from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN from .controller import DeebotController from .entity import DeebotEntity async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add entities for passed config_entry in HA.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] def image_entity_generator( device: Device, ) -> Sequence[DeebotMap]: new_entities = [] if caps := device.capabilities.map: new_entities.append(DeebotMap(hass, device, caps)) return new_entities controller.register_platform_add_entities_generator( async_add_entities, image_entity_generator ) class DeebotMap( DeebotEntity[CapabilityMap, EntityDescription], ImageEntity, # type: ignore ): """Deebot map.""" _attr_content_type = "image/svg+xml" def __init__(self, hass: HomeAssistant, device: Device, capability: CapabilityMap): super().__init__( device, capability, EntityDescription( key="map", translation_key="map", entity_registry_enabled_default=False, ), hass=hass, ) self._attr_extra_state_attributes: MutableMapping[str, Any] = {} def image(self) -> bytes | None: """Return bytes of image or None.""" if svg := self._device.map.get_svg_map(): return svg.encode() return None async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_info(event: CachedMapInfoEvent) -> None: self._attr_extra_state_attributes["map_name"] = event.name async def on_changed(event: MapChangedEvent) -> None: self._attr_image_last_updated = event.when self.async_write_ha_state() self._subscribe(self._capability.chached_info.event, on_info) self._subscribe(self._capability.changed.event, on_changed) async def async_update(self) -> None: """Update the entity. Only used by the generic entity update service. """ await super().async_update() self._device.map.refresh() ================================================ FILE: custom_components/deebot/manifest.json ================================================ { "domain": "deebot", "name": "Deebot 4 Home Assistant", "codeowners": [ "@DeebotUniverse", "@edenhaus" ], "config_flow": true, "documentation": "https://deebot.readthedocs.io/integrations/home-assistant", "iot_class": "cloud_polling", "issue_tracker": "https://github.com/DeebotUniverse/Deebot-4-Home-Assistant/issues", "loggers": [ "custom_components.deebot", "deebot_client" ], "requirements": [ "deebot-client==5.1.0", "numpy>=1.23.2" ], "version": "v0.0.0" } ================================================ FILE: custom_components/deebot/number.py ================================================ """Number module.""" from collections.abc import Callable from dataclasses import dataclass from typing import Generic from deebot_client.capabilities import CapabilitySet from homeassistant.components.number import NumberEntity, NumberEntityDescription from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback from numpy import array_split from .const import DOMAIN from .controller import DeebotController from .entity import DeebotEntity, DeebotEntityDescription, EventT @dataclass(kw_only=True, frozen=True) class DeebotNumberEntityDescription( NumberEntityDescription, # type: ignore DeebotEntityDescription, Generic[EventT], ): """Deebot number entity description.""" icon_fn: Callable[["DeebotNumberEntity"], str | None] = lambda _: None native_max_value_fn: Callable[[EventT], float | None] = lambda _: None value_fn: Callable[[EventT], float | None] def _volume_icon(instance: "DeebotNumberEntity") -> str | None: """Return the icon for the volume number.""" value = instance.native_value if value is not None: min_value = instance.native_min_value arrays = array_split(range(min_value + 1, instance.native_max_value + 1), 3) if value == min_value: return "mdi:volume-off" if value in arrays[0]: return "mdi:volume-low" if value in arrays[1]: return "mdi:volume-medium" if value in arrays[2]: return "mdi:volume-high" return "mdi:volume-medium" ENTITY_DESCRIPTIONS: tuple[DeebotNumberEntityDescription, ...] = ( DeebotNumberEntityDescription( capability_fn=lambda caps: caps.settings.volume, value_fn=lambda e: e.volume, native_max_value_fn=lambda e: e.maximum if e.maximum else None, key="volume", translation_key="volume", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, native_min_value=0, native_max_value=10, native_step=1.0, icon_fn=_volume_icon, ), DeebotNumberEntityDescription( capability_fn=lambda caps: caps.clean.count, value_fn=lambda e: e.count, key="clean_count", translation_key="clean_count", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, native_min_value=1, native_max_value=4, native_step=1.0, icon="mdi:counter", ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add entities for passed config_entry in HA.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] controller.register_platform_add_entities( DeebotNumberEntity, ENTITY_DESCRIPTIONS, async_add_entities ) class DeebotNumberEntity( DeebotEntity[CapabilitySet[EventT, int], DeebotNumberEntityDescription], NumberEntity, # type: ignore ): """Deebot number entity.""" async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_event(event: EventT) -> None: self._attr_native_value = self.entity_description.value_fn(event) if maximum := self.entity_description.native_max_value_fn(event): self._attr_native_max_value = maximum if icon := self.entity_description.icon_fn(self): self._attr_icon = icon self.async_write_ha_state() self._subscribe(self._capability.event, on_event) async def async_set_native_value(self, value: float) -> None: """Set new value.""" await self._device.execute_command(self._capability.set(int(value))) ================================================ FILE: custom_components/deebot/select.py ================================================ """Select module.""" from collections.abc import Callable from dataclasses import dataclass from typing import Any, Generic from deebot_client.capabilities import CapabilitySetTypes from deebot_client.device import Device from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN from .controller import DeebotController from .entity import DeebotEntity, DeebotEntityDescription, EventT @dataclass(kw_only=True, frozen=True) class DeebotSelectEntityDescription( SelectEntityDescription, # type: ignore DeebotEntityDescription, Generic[EventT], ): """Deebot select entity description.""" current_option_fn: Callable[[EventT], str | None] options_fn: Callable[[CapabilitySetTypes], list[str]] ENTITY_DESCRIPTIONS: tuple[DeebotSelectEntityDescription, ...] = ( DeebotSelectEntityDescription( capability_fn=lambda caps: caps.water, current_option_fn=lambda e: e.amount.display_name, options_fn=lambda water: [amount.display_name for amount in water.types], key="water_amount", translation_key="water_amount", entity_registry_enabled_default=False, icon="mdi:water", entity_category=EntityCategory.CONFIG, ), DeebotSelectEntityDescription( capability_fn=lambda caps: caps.clean.work_mode, current_option_fn=lambda e: e.mode.display_name, options_fn=lambda cap: [mode.display_name for mode in cap.types], key="work_mode", translation_key="work_mode", entity_registry_enabled_default=False, icon="mdi:cog", entity_category=EntityCategory.CONFIG, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add entities for passed config_entry in HA.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] controller.register_platform_add_entities( DeebotSelectEntity, ENTITY_DESCRIPTIONS, async_add_entities ) class DeebotSelectEntity( DeebotEntity[CapabilitySetTypes[EventT, str], DeebotSelectEntityDescription], SelectEntity, # type: ignore ): """Deebot select entity.""" _attr_current_option: str | None = None def __init__( self, device: Device, capability: CapabilitySetTypes[EventT, str], entity_description: DeebotSelectEntityDescription | None = None, **kwargs: Any, ): super().__init__(device, capability, entity_description, **kwargs) self._attr_options = self.entity_description.options_fn(capability) async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_event(event: EventT) -> None: self._attr_current_option = self.entity_description.current_option_fn(event) self.async_write_ha_state() self._subscribe(self._capability.event, on_event) async def async_select_option(self, option: str) -> None: """Change the selected option.""" await self._device.execute_command(self._capability.set(option)) ================================================ FILE: custom_components/deebot/sensor.py ================================================ """Sensor module.""" from collections.abc import Callable, MutableMapping, Sequence from dataclasses import dataclass from math import floor from typing import Any, Generic, TypeVar from deebot_client.capabilities import CapabilityEvent, CapabilityLifeSpan from deebot_client.device import Device from deebot_client.events import ( BatteryEvent, CleanLogEvent, ErrorEvent, Event, LifeSpan, LifeSpanEvent, NetworkInfoEvent, StatsEvent, TotalStatsEvent, ) from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( AREA_SQUARE_METERS, ATTR_BATTERY_LEVEL, CONF_DESCRIPTION, PERCENTAGE, EntityCategory, UnitOfTime, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import StateType from .const import DOMAIN from .controller import DeebotController from .entity import DeebotEntity, DeebotEntityDescription, EventT @dataclass(kw_only=True, frozen=True) class DeebotSensorEntityDescription( SensorEntityDescription, # type: ignore DeebotEntityDescription, Generic[EventT], ): """Deebot sensor entity description.""" extra_state_attributes_fn: Callable[ [EventT], MutableMapping[str, Any] ] | None = None value_fn: Callable[[EventT], StateType] def _clean_log_event_value(event: CleanLogEvent) -> str | None: if event.logs: log = event.logs[0] return log.stop_reason.display_name return None def _clean_log_event_attributes(event: CleanLogEvent) -> MutableMapping[str, Any]: if event.logs: log = event.logs[0] return { "timestamp": log.timestamp, "image_url": log.image_url, "type": log.type, "area": log.area, "duration": log.duration / 60, } return {} ENTITY_DESCRIPTIONS: tuple[DeebotSensorEntityDescription, ...] = ( # Stats DeebotSensorEntityDescription[StatsEvent]( key="stats_area", capability_fn=lambda caps: caps.stats.clean, value_fn=lambda e: e.area, translation_key="stats_area", icon="mdi:floor-plan", native_unit_of_measurement=AREA_SQUARE_METERS, entity_registry_enabled_default=False, ), DeebotSensorEntityDescription[StatsEvent]( key="stats_time", capability_fn=lambda caps: caps.stats.clean, value_fn=lambda e: round(e.time / 60) if e.time else None, translation_key="stats_time", icon="mdi:timer-outline", native_unit_of_measurement=UnitOfTime.MINUTES, entity_registry_enabled_default=False, ), DeebotSensorEntityDescription[StatsEvent]( capability_fn=lambda caps: caps.stats.clean, value_fn=lambda e: e.type, key="stats_type", translation_key="stats_type", icon="mdi:cog", entity_registry_enabled_default=False, ), # TotalStats DeebotSensorEntityDescription[TotalStatsEvent]( capability_fn=lambda caps: caps.stats.total, value_fn=lambda e: e.area, key="stats_total_area", translation_key="stats_total_area", icon="mdi:floor-plan", native_unit_of_measurement=AREA_SQUARE_METERS, entity_registry_enabled_default=False, state_class=SensorStateClass.TOTAL_INCREASING, ), DeebotSensorEntityDescription[TotalStatsEvent]( capability_fn=lambda caps: caps.stats.total, value_fn=lambda e: round(e.time / 3600), key="stats_total_time", translation_key="stats_total_time", icon="mdi:timer-outline", native_unit_of_measurement=UnitOfTime.HOURS, entity_registry_enabled_default=False, state_class=SensorStateClass.TOTAL_INCREASING, ), DeebotSensorEntityDescription[TotalStatsEvent]( capability_fn=lambda caps: caps.stats.total, value_fn=lambda e: e.cleanings, key="stats_total_cleanings", translation_key="stats_total_cleanings", icon="mdi:counter", entity_registry_enabled_default=False, state_class=SensorStateClass.TOTAL_INCREASING, ), DeebotSensorEntityDescription[BatteryEvent]( capability_fn=lambda caps: caps.battery, value_fn=lambda e: e.value, key=ATTR_BATTERY_LEVEL, translation_key=ATTR_BATTERY_LEVEL, native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, entity_category=EntityCategory.DIAGNOSTIC, ), DeebotSensorEntityDescription[NetworkInfoEvent]( capability_fn=lambda caps: caps.network, value_fn=lambda e: e.ip, key="wifi_ip", translation_key="wifi_ip", icon="mdi:ip-network-outline", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), DeebotSensorEntityDescription[NetworkInfoEvent]( capability_fn=lambda caps: caps.network, value_fn=lambda e: e.rssi, key="wifi_rssi", translation_key="wifi_rssi", icon="mdi:signal-variant", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), DeebotSensorEntityDescription[NetworkInfoEvent]( capability_fn=lambda caps: caps.network, value_fn=lambda e: e.ssid, key="wifi_ssid", translation_key="wifi_ssid", icon="mdi:wifi", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), ) @dataclass(kw_only=True, frozen=True) class DeebotLifeSpanSensorEntityDescription( SensorEntityDescription, # type: ignore ): """Class describing Deebot sensor entity.""" component: LifeSpan LIFE_SPAN_DESCRIPTIONS: tuple[DeebotLifeSpanSensorEntityDescription, ...] = ( DeebotLifeSpanSensorEntityDescription( component=LifeSpan.BRUSH, key="life_span_brush", translation_key="life_span_brush", icon="mdi:broom", entity_registry_enabled_default=False, native_unit_of_measurement="%", entity_category=EntityCategory.DIAGNOSTIC, ), DeebotLifeSpanSensorEntityDescription( component=LifeSpan.FILTER, key="life_span_filter", translation_key="life_span_filter", icon="mdi:air-filter", entity_registry_enabled_default=False, native_unit_of_measurement="%", entity_category=EntityCategory.DIAGNOSTIC, ), DeebotLifeSpanSensorEntityDescription( component=LifeSpan.SIDE_BRUSH, key="life_span_side_brush", translation_key="life_span_side_brush", icon="mdi:broom", entity_registry_enabled_default=False, native_unit_of_measurement="%", entity_category=EntityCategory.DIAGNOSTIC, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add entities for passed config_entry in HA.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] controller.register_platform_add_entities( DeebotSensor, ENTITY_DESCRIPTIONS, async_add_entities ) def last_error_entity_generator( device: Device, ) -> Sequence[LastErrorSensor]: if capability := device.capabilities.error: return [(LastErrorSensor(device, capability))] return [] def last_cleaning_entity_generator( device: Device, ) -> Sequence[LastCleaningSensor]: if capability := device.capabilities.clean.log: return [(LastCleaningSensor(device, capability))] return [] def life_span_entity_generator(device: Device) -> Sequence[LifeSpanSensor]: new_entities = [] capability = device.capabilities.life_span for description in LIFE_SPAN_DESCRIPTIONS: if description.component in capability.types: new_entities.append(LifeSpanSensor(device, capability, description)) return new_entities controller.register_platform_add_entities_generator( async_add_entities, ( life_span_entity_generator, last_error_entity_generator, last_cleaning_entity_generator, ), ) class DeebotSensor( DeebotEntity[CapabilityEvent, DeebotSensorEntityDescription], SensorEntity, # type: ignore ): """Deebot sensor.""" async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_event(event: Event) -> None: value = self.entity_description.value_fn(event) if value is None: return self._attr_native_value = value if attr_fn := self.entity_description.extra_state_attributes_fn: self._attr_extra_state_attributes = attr_fn(event) self.async_write_ha_state() self._subscribe(self._capability.event, on_event) T = TypeVar("T", bound=Event) class LifeSpanSensor( DeebotEntity[CapabilityLifeSpan, DeebotLifeSpanSensorEntityDescription], SensorEntity, # type: ignore ): """Life span sensor.""" async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_event(event: LifeSpanEvent) -> None: if event.type == self.entity_description.component: self._attr_native_value = event.percent self._attr_extra_state_attributes = { "remaining": floor(event.remaining / 60) } self.async_write_ha_state() self._subscribe(self._capability.event, on_event) class LastErrorSensor( DeebotEntity[CapabilityEvent[ErrorEvent], SensorEntityDescription], SensorEntity, # type: ignore ): """Last error sensor.""" _always_available: bool = True _unrecorded_attributes = frozenset({CONF_DESCRIPTION}) entity_description: SensorEntityDescription = SensorEntityDescription( key="last_error", translation_key="last_error", icon="mdi:alert-circle", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ) async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_event(event: ErrorEvent) -> None: self._attr_native_value = event.code self._attr_extra_state_attributes = {CONF_DESCRIPTION: event.description} self.async_write_ha_state() self._subscribe(self._capability.event, on_event) class LastCleaningSensor( DeebotEntity[CapabilityEvent[CleanLogEvent], SensorEntityDescription], SensorEntity, # type: ignore ): """Last cleaning sensor.""" _always_available: bool = True entity_description: SensorEntityDescription = SensorEntityDescription( key="last_cleaning", translation_key="last_cleaning", icon="mdi:history", entity_registry_enabled_default=False, ) async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_event(event: CleanLogEvent) -> None: if event.logs: log = event.logs[0] self._attr_native_value = log.stop_reason.display_name self._attr_extra_state_attributes = { "timestamp": log.timestamp, "image_url": log.image_url, "type": log.type, "area": log.area, "duration": log.duration / 60, } self.async_write_ha_state() self._subscribe(self._capability.event, on_event) ================================================ FILE: custom_components/deebot/services.yaml ================================================ # Must be kept in sync with vacuum.py refresh: target: entity: integration: deebot domain: vacuum fields: category: required: true advanced: false example: "status" default: "status" selector: select: translation_key: "refresh_category" sort: true options: - "battery" - "clean_logs" - "error" - "fan_speed" - "life_spans" - "map" - "rooms" - "stats" - "status" - "water" ================================================ FILE: custom_components/deebot/switch.py ================================================ """Switch module.""" from dataclasses import dataclass from typing import Any from deebot_client.capabilities import CapabilitySetEnable from deebot_client.events import EnableEvent from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN from .controller import DeebotController from .entity import DeebotEntity, DeebotEntityDescription @dataclass(kw_only=True, frozen=True) class DeebotSwitchEntityDescription( SwitchEntityDescription, # type: ignore DeebotEntityDescription, ): """Deebot switch entity description.""" ENTITY_DESCRIPTIONS: tuple[DeebotSwitchEntityDescription, ...] = ( DeebotSwitchEntityDescription( capability_fn=lambda c: c.settings.advanced_mode, key="advanced_mode", translation_key="advanced_mode", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, icon="mdi:tune", ), DeebotSwitchEntityDescription( capability_fn=lambda c: c.clean.continuous, key="continuous_cleaning", translation_key="continuous_cleaning", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, icon="mdi:refresh-auto", ), DeebotSwitchEntityDescription( capability_fn=lambda c: c.settings.carpet_auto_fan_boost, key="carpet_auto_fan_speed_boost", translation_key="carpet_auto_fan_speed_boost", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, icon="mdi:fan-auto", ), DeebotSwitchEntityDescription( capability_fn=lambda c: c.clean.preference, key="clean_preference", translation_key="clean_preference", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, icon="mdi:broom", ), DeebotSwitchEntityDescription( capability_fn=lambda c: c.settings.true_detect, key="true_detect", translation_key="true_detect", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, icon="mdi:laser-pointer", ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add entities for passed config_entry in HA.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] controller.register_platform_add_entities( DeebotSwitchEntity, ENTITY_DESCRIPTIONS, async_add_entities ) class DeebotSwitchEntity( DeebotEntity[CapabilitySetEnable, DeebotSwitchEntityDescription], SwitchEntity, # type: ignore ): """Deebot switch entity.""" _attr_is_on = False async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_event(event: EnableEvent) -> None: self._attr_is_on = event.enable self.async_write_ha_state() self._subscribe(self._capability.event, on_event) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the entity on.""" await self._device.execute_command(self._capability.set(True)) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the entity off.""" await self._device.execute_command(self._capability.set(False)) ================================================ FILE: custom_components/deebot/translations/de.json ================================================ { "config": { "abort": { "already_configured": "Bereits konfiguriert", "no_supported_devices_found": "Keine unterstützten Geräte gefunden", "reauth_successful": "Die erneute Authentifizierung war erfolgreich" }, "error": { "cannot_connect": "Verbindung fehlgeschlagen. Weitere Infos in den Logs", "invalid_auth": "Ungültige Authentifizierung", "invalid_continent": "Ungültiger Kontinent! Code muss aus 2 Zeichen bestehen!", "invalid_country": "Ungültiges Land! Ländercode muss aus 2 Zeichen bestehen!", "select_robots": "Bitte wähle mindestens 1 Roboter aus", "unknown": "Unerwarteter Fehler. Weitere Infos in den Logs" }, "step": { "options": { "data": { "devices": "Geräte" } }, "user": { "data": { "continent": "Kontinent", "country": "Land", "password": "Passwort", "username": "E-mail oder ShortID" }, "data_description": { "continent": "2-stelliger Kontinentcode Bsp.: eu, ww. Wenn der Kontinentcode nicht funktioniert, verwende ww", "country": "2-stelliger Ländercode. Bsp.: de, it, uk" } }, "user_advanced": { "description": "Wähle \"Bumper\" nur, falls du eine funktionierende Bumper-Instanz hast. Ansonsten wähle bitte die empfohlene Variante \"Cloud\"." } } }, "entity": { "binary_sensor": { "mop_attached": { "name": "Wischmopp montiert" } }, "button": { "life_span_brush_reset": { "name": "Hauptbürste zurücksetzen" }, "life_span_filter_reset": { "name": "Filter zurücksetzen" }, "life_span_side_brush_reset": { "name": "Seitenbürsten zurücksetzen" }, "relocate": { "name": "Position aktualisieren" } }, "image": { "map": { "name": "Karte" } }, "number": { "volume": { "name": "Lautstärke" } }, "select": { "water_amount": { "name": "Wasserdurchflussrate", "state": { "high": "Hoch", "low": "Niedrig", "medium": "Mittel", "ultrahigh": "Sehr hoch" } } }, "sensor": { "battery_level": { "name": "Batterie" }, "last_cleaning": { "name": "Letzte Reinigung" }, "last_error": { "name": "Letzter Fehler" }, "life_span_brush": { "name": "Hauptbürste" }, "life_span_filter": { "name": "Filter" }, "life_span_side_brush": { "name": "Seitenbürsten" }, "stats_area": { "name": "Reinigungsfläche" }, "stats_time": { "name": "Reinigungsdauer" }, "stats_total_area": { "name": "Gesamtreinigungsfläche" }, "stats_total_cleanings": { "name": "Gesamtanzahl Reinigunen" }, "stats_total_time": { "name": "Gesamtreinigungsdauer" }, "stats_type": { "name": "Reinigungsmodus" } }, "switch": { "advanced_mode": { "name": "Erweiterter Modus" }, "carpet_auto_fan_speed_boost": { "name": "Auto-Saugkraftverstärkung" }, "continuous_cleaning": { "name": "Wiederaufnahme der Reinigung" } }, "vacuum": { "bot": { "state_attributes": { "fan_speed": { "state": { "max": "Maximal", "max_plus": "Maximal+", "normal": "Standard", "quiet": "Leise" } }, "last_error": { "name": "Letzter Fehler" }, "rooms": { "name": "Räume" } } } } }, "options": { "abort": { "cannot_connect": "Verbindung fehlgeschlagen. Weitere Infos in den Logs", "invalid_auth": "Ungültige Authentifizierung. Bitte vorher neu konfigurieren", "no_supported_devices_found": "Keine unterstützten Geräte gefunden", "unknown_get_devices": "Unerwarteter Fehler beim Abholen aller Geräte. Weitere Infos in den Logs" }, "error": { "select_robots": "Bitte wähle mindestens 1 Roboter aus", "unknown": "Unerwarteter Fehler. Weitere Infos in den Logs" }, "step": { "init": { "data": { "devices": "Geräte" }, "data_description": { "devices": "Bitte wähle alle Geräte aus, welche du im HA verwenden willst." } } } }, "selector": { "refresh_category": { "options": { "battery": "Batterie", "clean_logs": "Reinungsprotokoll", "error": "Fehler", "fan_speed": "Lüftergeschwindigkeit", "life_spans": "Komponentenabnutzung", "map": "Karte", "rooms": "Räume", "stats": "Statistik", "status": "Status", "water": "Wasser" } } }, "services": { "refresh": { "description": "Manuelle Aktualisierung der selektierten Kategorie.", "fields": { "category": { "description": "Was soll aktualisiert werden?", "name": "Kategorie" } }, "name": "Manuelle Aktualisierung" } } } ================================================ FILE: custom_components/deebot/translations/en.json ================================================ { "config": { "abort": { "already_configured": "Already configured", "no_supported_devices_found": "No supported devices found", "reauth_successful": "Re-authentication was successful" }, "error": { "cannot_connect": "Can't connect to the ecovacs API. Please check the logs", "invalid_auth": "Invalid username or password", "invalid_continent": "Continent code should be two letter code", "invalid_country": "Country code should be two letter code", "select_robots": "Please select at least 1 robot", "unknown": "Unknown error. Please check the logs" }, "step": { "options": { "data": { "devices": "Devices" }, "data_description": { "devices": "Please select all devices, which you want to use in HA." } }, "user": { "data": { "continent": "Continent", "country": "Country", "password": "Password", "username": "E-mail or ShortID" }, "data_description": { "continent": "The two letter continent code. Ex.: ww, eu. If your country code is not working try ww", "country": "The two letter country code. Ex.: us, uk" } }, "user_advanced": { "description": "Please select \"Bumper\" ONLY if you already have a working bumper instance. Otherwise, select \"Cloud\" please." } } }, "entity": { "binary_sensor": { "mop_attached": { "name": "Mop attached" } }, "button": { "life_span_brush_reset": { "name": "Reset brush" }, "life_span_filter_reset": { "name": "Reset filter" }, "life_span_side_brush_reset": { "name": "Reset side brush" }, "relocate": { "name": "Relocate" } }, "image": { "map": { "name": "Map" } }, "number": { "clean_count": { "name": "Clean count" }, "volume": { "name": "Volume" } }, "select": { "water_amount": { "name": "Water amount", "state": { "high": "high", "low": "low", "medium": "medium", "ultrahigh": "ultrahigh" } }, "work_mode": { "name": "Work mode", "state": { "mop": "Mop", "mop_after_vacuum": "Mop after vacuum", "vacuum": "Vacuum", "vacuum_and_mop": "Vacuum & mop" } } }, "sensor": { "battery_level": { "name": "Battery level" }, "last_cleaning": { "name": "Last cleaning" }, "last_error": { "name": "Last error" }, "life_span_brush": { "name": "Brush" }, "life_span_filter": { "name": "Filter" }, "life_span_side_brush": { "name": "Side brush" }, "stats_area": { "name": "Stats area" }, "stats_time": { "name": "Stats time" }, "stats_total_area": { "name": "Stats total area" }, "stats_total_cleanings": { "name": "Stats total cleanings" }, "stats_total_time": { "name": "Stats total time" }, "stats_type": { "name": "Stats type" }, "wifi_ip": { "name": "Ip" }, "wifi_rssi": { "name": "Wifi rssi" }, "wifi_ssid": { "name": "Wifi ssid" } }, "switch": { "advanced_mode": { "name": "Advanced mode" }, "carpet_auto_fan_speed_boost": { "name": "Carpet auto fan speed boost" }, "clean_preference": { "name": "Clean preference" }, "continuous_cleaning": { "name": "Continuous cleaning" }, "true_detect": { "name": "True detect" } }, "vacuum": { "bot": { "state_attributes": { "fan_speed": { "state": { "max": "Max", "max_plus": "Max+", "normal": "Normal", "quiet": "Quiet" } }, "last_error": { "name": "Last error" }, "rooms": { "name": "Rooms" } } } } }, "issues": { "deprecated_integration_issue": { "description": "I migrated the custom component `Deebot 4 Home Assistant` to the core and merged it with the existing `Ecovacs` integration.\n\nThe custom component is no longer needed and will be archived in the future.\n\nEverything was migrated except:\n- The events `cleaning_job` and `custom_command`.\n- The last cleaning and stats type sensors\n- Deprecated services\n\nMigration steps:\n1: Remove all `Deebot 4 Home Assistant` config entries\n2: Uninstall `Deebot 4 Home Assistant` via HACS\n3: Restart Home Assistant\n4: Setup the [Ecovacs integration]({docs_url}) by clicking [here]({config_url})", "title": "Time to migrate!" }, "deprecated_service_refresh": { "fix_flow": { "step": { "confirm": { "description": "The service `deebot.refresh` is deprecated and will be removed.\nTo refresh an entity please use `homeassistant.update_entity` on the respective entity instead.\n\nPlease remove this service from your automations and scripts and select **submit** to close this issue.", "title": "Deebot refresh service is being removed" } } }, "title": "Deebot refresh service is being removed" } }, "options": { "abort": { "cannot_connect": "Can't connect to the ecovacs API. Please check the logs", "invalid_auth": "Authentication failed. Please reauthenticate first", "no_supported_devices_found": "No supported devices found", "unknown_get_devices": "Unknown error on getting all devices. Please check the logs" }, "error": { "select_robots": "Please select at least 1 robot", "unknown": "Unknown error. Please check the logs" }, "step": { "init": { "data": { "devices": "Devices" }, "data_description": { "devices": "Please select all devices, which you want to use in HA." } } } }, "selector": { "refresh_category": { "options": { "battery": "Battery", "clean_logs": "Clean logs", "error": "Error", "fan_speed": "Fan speed", "life_spans": "Life spans", "map": "Map", "rooms": "Rooms", "stats": "Stats", "status": "Status", "water": "Water" } } }, "services": { "refresh": { "description": "Manually request a refresh for the selected category.", "fields": { "category": { "description": "Which category should be refreshed?", "name": "Category" } }, "name": "Manually refresh" } } } ================================================ FILE: custom_components/deebot/translations/fr.json ================================================ { "config": { "abort": { "already_configured": "Déjà configuré", "no_supported_devices_found": "Aucun appareil pris en charge trouvé", "reauth_successful": "Réauthentification réussie" }, "error": { "cannot_connect": "Connection impossible à l'API Ecovacs. Veuillez consulter les journaux.", "invalid_auth": "Nom d’utilisateur ou mot de passe incorrect", "invalid_continent": "Le code du continent doit être en deux lettres, ex: eu, as, na, ww", "invalid_country": "Le code du pays doit être en deux lettres, ex: fr, be, us, ... ", "select_robots": "Sélectionnez au moins 1 robot", "unknown": "Erreur inconnue. Veuillez consulter les journaux." }, "step": { "options": { "data": { "devices": "Appareils" }, "data_description": { "devices": "Veuillez sélectionner tous les appareils que vous souhaitez utiliser dans HA." } }, "user": { "data": { "continent": "Continent", "country": "Pays", "password": "Mot de passe", "username": "E-mail ou Ecovacs ID" }, "data_description": { "continent": "Le code à deux lettres du continent. Ex : eu, as, na. Si le code de votre continent ne fonctionne pas, essayez ww", "country": "Le code à deux lettres du pays. Ex : fr, be" } }, "user_advanced": { "description": "Sélectionnez \"Bumper\" SEULEMENT si vous avez déjà une instance bumper fonctionnelle. Sinon, sélectionnez \"Cloud\" s'il vous plait." } } }, "entity": { "binary_sensor": { "mop_attached": { "name": "Serpillière attachée" } }, "button": { "life_span_brush_reset": { "name": "Réinitialiser rouleau" }, "life_span_filter_reset": { "name": "Réinitialiser filtre" }, "life_span_side_brush_reset": { "name": "Réinitialiser brosses latérales" }, "relocate": { "name": "Relocalisation" } }, "image": { "map": { "name": "Carte" } }, "number": { "clean_count": { "name": "Compte de nettoyage" }, "volume": { "name": "Volume" } }, "select": { "water_amount": { "name": "Quantité d'eau", "state": { "high": "haute", "low": "faible", "medium": "moyenne", "ultrahigh": "très élevée" } } }, "sensor": { "battery_level": { "name": "Niveau de batterie" }, "last_cleaning": { "name": "Dernier nettoyage" }, "last_error": { "name": "Dernière erreur" }, "life_span_brush": { "name": "Rouleau" }, "life_span_filter": { "name": "Filtre" }, "life_span_side_brush": { "name": "Brosses latérales" }, "stats_area": { "name": "Surface" }, "stats_time": { "name": "Durée" }, "stats_total_area": { "name": "Surface totale" }, "stats_total_cleanings": { "name": "Nombre de nettoyages" }, "stats_total_time": { "name": "Durée totale" }, "stats_type": { "name": "Mode" } }, "switch": { "advanced_mode": { "name": "Mode avancé" }, "carpet_auto_fan_speed_boost": { "name": "Vitesse du ventilateur automatique sur moquette" }, "clean_preference": { "name": "Preference de nettoyage par pièce" }, "continuous_cleaning": { "name": "Nettoyage continu" }, "true_detect": { "name": "TrueDetect 3D" } }, "vacuum": { "bot": { "state_attributes": { "fan_speed": { "state": { "max": "Fort", "max_plus": "Max+", "normal": "Standard", "quiet": "Silencieux" } }, "last_error": { "name": "Dernière erreur" }, "rooms": { "name": "Pièces" } } } } }, "options": { "abort": { "cannot_connect": "Connection impossible à l'API Ecovacs. Veuillez consulter les journaux.", "invalid_auth": "Echec de l'authentification. Veuillez d'abord vous réauthentifier.", "no_supported_devices_found": "Aucun appareil pris en charge trouvé", "unknown_get_devices": "Erreur inconnue lors de l'obtention des appareils. Veuillez consulter les journaux." }, "error": { "select_robots": "Sélectionnez au moins 1 robot", "unknown": "Erreur inconnue. Veuillez consulter les journaux." }, "step": { "init": { "data": { "devices": "Appareils" }, "data_description": { "devices": "Veuillez sélectionner tous les appareils que vous souhaitez utiliser dans HA." } } } }, "selector": { "refresh_category": { "options": { "battery": "Batterie", "clean_logs": "Journal des nettoyages", "error": "Erreur", "fan_speed": "Vitesse d'aspiration", "life_spans": "Durée de vie", "map": "Carte", "rooms": "Pièces", "stats": "Stats", "status": "Statut", "water": "Eau" } } }, "services": { "refresh": { "description": "Demander manuellement une actualisation pour la catégorie sélectionnée.", "fields": { "category": { "description": "Quelle catégorie doit être rafraîchie ?", "name": "Catégorie" } }, "name": "Actualisation manuelle" } } } ================================================ FILE: custom_components/deebot/translations/it.json ================================================ { "config": { "abort": { "already_configured": "Già configurato", "no_supported_devices_found": "Non sono stati trovati dispositivi supportati", "reauth_successful": "Ri-autenticazione avvenuta con successo" }, "error": { "cannot_connect": "Non riesco a connettermi con le API di ecovacs", "invalid_auth": "Utente o password errati", "invalid_continent": "La sigla contiente code deve essere di due lettere, es: eu, ww ecc...", "invalid_country": "La sigla paese code deve essere di due lettere, es: it, us, uk ecc...", "select_robots": "Seleziona almeno 1 robot", "unknown": "Errore sconosciuto" }, "step": { "options": { "data": { "devices": "Dispositivi" } }, "user": { "data": { "continent": "Continente", "country": "Paese", "username": "E-mail o ShortID" }, "data_description": { "continent": "Sigla del continente. Ex.: eu, ww. Se la tua sigla paese non funziona prova con ww", "country": "Sigla del paese. Es.: it, us, uk" } }, "user_advanced": { "description": "Seleziona \"Bumper\" SOLO se hai già un'istanza Bumper. Altrimenti, seleziona \"Cloud\"." } } } } ================================================ FILE: custom_components/deebot/translations/ko.json ================================================ { "config": { "abort": { "already_configured": "이미 구성됨", "no_supported_devices_found": "지원되는 기기가 없음", "reauth_successful": "재인증 성공" }, "error": { "cannot_connect": "ecovacs API에 연결할 수 없습니다. 로그를 확인하세요", "invalid_auth": "잘못된 사용자 이름 또는 암호", "invalid_continent": "대륙 코드는 2자리 코드여야 합니다", "invalid_country": "국가 코드는 2자리 코드여야 합니다", "select_robots": "적어도 하나 이상의 로봇청소기를 선택하세요", "unknown": "알 수 없는 오류. 로그를 확인하세요" }, "step": { "options": { "data": { "devices": "기기" }, "data_description": { "devices": "HA에서 사용하려는 모든 기기를 선택하십시오" } }, "user": { "data": { "continent": "대륙", "country": "국가", "password": "암호", "username": "이메일 또는 ShortID" }, "data_description": { "continent": "두 자리 대륙 코드. 예: ww, eu. 국가 코드가 작동하지 않는다면 ww로 시도하세요", "country": "두자리 국가코드. 예: us, uk" } }, "user_advanced": { "description": "이미 작동 중인 범퍼 인스턴스가 있는 경우에만 \"Bumper\"를 선택하세요. 그렇지 않으면, \"Cloud\"를 선택하세요" } } }, "entity": { "binary_sensor": { "mop_attached": { "name": "물걸레 장착됨" } }, "button": { "life_span_brush_reset": { "name": "메인 브러시 재설정" }, "life_span_filter_reset": { "name": "필터 재설정" }, "life_span_side_brush_reset": { "name": "사이드 브러시 재설정" }, "relocate": { "name": "재배치" } }, "image": { "map": { "name": "지도" } }, "number": { "clean_count": { "name": "청소 횟수" }, "volume": { "name": "볼륨" } }, "select": { "water_amount": { "name": "출수량", "state": { "high": "많음", "low": "적음", "medium": "중간", "ultrahigh": "매우 많음" } } }, "sensor": { "battery_level": { "name": "배터리 레벨" }, "last_cleaning": { "name": "마지막 청소" }, "last_error": { "name": "마지막 에러" }, "life_span_brush": { "name": "메인 브러시" }, "life_span_filter": { "name": "필터" }, "life_span_side_brush": { "name": "사이드 브러시" }, "stats_area": { "name": "면적 통계" }, "stats_time": { "name": "시간 통계" }, "stats_total_area": { "name": "총 면적 통계" }, "stats_total_cleanings": { "name": "총 청소 통계" }, "stats_total_time": { "name": "총 시간 통계" }, "stats_type": { "name": "유형 통계" } }, "switch": { "advanced_mode": { "name": "고급 모드" }, "carpet_auto_fan_speed_boost": { "name": "카페트 인식 흡입속도 부스트" }, "clean_preference": { "name": "청소 환경 설정" }, "continuous_cleaning": { "name": "연속 청소" }, "true_detect": { "name": "트루 디텍트" } }, "vacuum": { "bot": { "state_attributes": { "fan_speed": { "state": { "max": "맥스", "max_plus": "맥스+", "normal": "보통", "quiet": "저소음" } }, "last_error": { "name": "마지막 에러" }, "rooms": { "name": "방" } } } } }, "options": { "abort": { "cannot_connect": "ecovacs API에 연결할 수 없습니다. 로그를 확인하십시오", "invalid_auth": "인증 실패. 먼저 재인증하세요", "no_supported_devices_found": "지원되는 기기가 없음", "unknown_get_devices": "모든 장치를 가져오는 중 알 수 없는 오류가 발생했습니다. 로그를 확인하세요" }, "error": { "select_robots": "적어도 하나 이상의 로봇청소기를 선택하세요", "unknown": "알 수 없는 오류. 로그를 확인하세요" }, "step": { "init": { "data": { "devices": "기기" }, "data_description": { "devices": "HA에서 사용하려는 모든 기기를 선택하십시오" } } } }, "selector": { "refresh_category": { "options": { "battery": "배터리", "clean_logs": "로그 삭제", "error": "에러", "fan_speed": "흡입 속도", "life_spans": "메인 브러시 수명", "map": "지도", "rooms": "방", "stats": "통계", "status": "상태", "water": "물" } } }, "services": { "refresh": { "description": "선택한 카테고리에 대한 새로고침을 수동으로 요청합니다", "fields": { "category": { "description": "어떤 카테고리를 새로고침해야 합니까?", "name": "카테고리" } }, "name": "수동 새로고침" } } } ================================================ FILE: custom_components/deebot/translations/pt-BR.json ================================================ { "config": { "abort": { "already_configured": "Já está configurado", "no_supported_devices_found": "Nenhum dispositivo compatível encontrado", "reauth_successful": "A reautenticação foi bem-sucedida" }, "error": { "cannot_connect": "Não é possível conectar à API ecovacs. Por favor, verifique os registros", "invalid_auth": "nome de usuário ou senha inválidos", "invalid_continent": "O código do continente deve ser um código de duas letras", "invalid_country": "O código do país deve ser um código de duas letras", "select_robots": "Selecione pelo menos 1 robô", "unknown": "Erro desconhecido. Por favor, verifique os registros" }, "step": { "options": { "data": { "devices": "Dispositivos" } }, "user": { "data": { "continent": "Continente", "country": "País", "password": "Senha", "username": "E-mail ou ShortID" }, "data_description": { "continent": "O código do continente de duas letras. Ex.: ww, eu. Se o código do seu país não estiver funcionando, tente ww", "country": "O código do país de duas letras. Ex.: us, uk" } }, "user_advanced": { "description": "Selecione \"Bumper\" SOMENTE se você já tiver uma instância de bumper em funcionamento. Caso contrário, selecione \"Cloud\" por favor." } } } } ================================================ FILE: custom_components/deebot/translations/ru.json ================================================ { "config": { "abort": { "already_configured": "Уже настроено" }, "error": { "cannot_connect": "Не удается подключиться к API ecovacs", "invalid_auth": "Неверное имя пользователя или пароль", "invalid_continent": "Код континента должен быть двухбуквенным, например: eu, ww, итд ", "invalid_country": "Код страны должен быть двухбуквенным, например: ru, us, итд ", "select_robots": "Выберите хотя бы 1 робота", "unknown": "Неизвестная ошибка" }, "step": { "options": { "data": { "devices": "Устройства" } }, "user": { "data": { "continent": "Континент", "country": "Страна", "password": "Пароль", "username": "E-mail или Ecovacs ID" } }, "user_advanced": { "description": "Выберите \"Bumper\" ТОЛЬКО, если у вас уже есть работающий экземпляр bumper. В противном случае выберайте \"Cloud\"." } } } } ================================================ FILE: custom_components/deebot/translations/zh-Hans.json ================================================ { "config": { "abort": { "already_configured": "已存在现有配置", "no_supported_devices_found": "未找到支持的设备", "reauth_successful": "重新认证成功" }, "error": { "cannot_connect": "无法连接科沃斯API,请检查日志", "invalid_auth": "用户名或密码错误", "invalid_continent": "地区代码应是两个字母组成", "invalid_country": "国家代码应是两个字母组成", "select_robots": "请至少选择1个机器人", "unknown": "未知错误。请检查日志" }, "step": { "options": { "data": { "devices": "设备" }, "data_description": { "devices": "请选择您要在 HA 中使用的所有设备。" } }, "user": { "data": { "continent": "地区", "country": "国家", "password": "密码", "username": "电子邮件地址或科沃斯ID" }, "data_description": { "continent": "2位地区代码。例如: ww, eu, as.如果您的国家代码不起作用请尝试使用 ww", "country": "2位地区代码。例如: us, uk, cn" } }, "user_advanced": { "description": "只有当你有一个有效的缓冲器实例时,才推荐选择\"Bumper\" 。否则,请选择\"Cloud\"。" } } }, "options": { "abort": { "cannot_connect": "无法连接科沃斯API。 请检查日志", "invalid_auth": "认证失败。 请先重新认证", "no_supported_devices_found": "未找到支持的设备", "unknown_get_devices": "获取所有设备时出现未知错误。 请检查日志" }, "error": { "select_robots": "请至少选择1个机器人", "unknown": "未知错误。请检查日志" }, "step": { "init": { "data": { "devices": "设备" }, "data_description": { "devices": "请选择您要在 HA 中使用的所有设备。" } } } } } ================================================ FILE: custom_components/deebot/util.py ================================================ """Util module.""" import dataclasses from enum import Enum from typing import Any from deebot_client.util import DisplayNameIntEnum from homeassistant.core import HomeAssistant from homeassistant.util import uuid def get_bumper_device_id(hass: HomeAssistant) -> str: """Return bumper device id.""" try: location_name = hass.config.location_name.strip().replace(" ", "_") except Exception: # pylint: disable=broad-except location_name = "" return f"Deebot-4-HA_{location_name}_{uuid.random_uuid_hex()[:4]}" def dataclass_to_dict(obj: Any) -> dict[str, Any]: """Convert dataclass to dict and remove None fields.""" dic = dataclasses.asdict(obj) for key, value in dic.copy().items(): if value is None: dic.pop(key) elif isinstance(value, Enum): if isinstance(value, DisplayNameIntEnum): dic[key] = value.display_name else: dic[key] = value.value return dic ================================================ FILE: custom_components/deebot/vacuum.py ================================================ """Support for Deebot Vacuums.""" import logging from collections.abc import Mapping, Sequence from typing import Any import voluptuous as vol from deebot_client.capabilities import Capabilities from deebot_client.device import Device from deebot_client.events import ( BatteryEvent, CustomCommandEvent, FanSpeedEvent, ReportStatsEvent, RoomsEvent, StateEvent, ) from deebot_client.models import CleanAction, CleanMode, Room, State from homeassistant.components.vacuum import ( STATE_CLEANING, STATE_DOCKED, STATE_ERROR, STATE_IDLE, STATE_PAUSED, STATE_RETURNING, StateVacuumEntity, StateVacuumEntityDescription, VacuumEntityFeature, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_platform from homeassistant.helpers.config_validation import make_entity_service_schema from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue from homeassistant.util import slugify from .const import ( DOMAIN, EVENT_CLEANING_JOB, EVENT_CUSTOM_COMMAND, REFRESH_MAP, REFRESH_STR_TO_EVENT_DTO, ) from .controller import DeebotController from .entity import DeebotEntity from .util import dataclass_to_dict _LOGGER = logging.getLogger(__name__) _STATE_TO_VACUUM_STATE = { State.IDLE: STATE_IDLE, State.CLEANING: STATE_CLEANING, State.RETURNING: STATE_RETURNING, State.DOCKED: STATE_DOCKED, State.ERROR: STATE_ERROR, State.PAUSED: STATE_PAUSED, } # Must be kept in sync with services.yaml SERVICE_REFRESH = "refresh" SERVICE_REFRESH_CATEGORY = "category" SERVICE_REFRESH_SCHEMA = make_entity_service_schema( { vol.Required(SERVICE_REFRESH_CATEGORY): vol.In( [*REFRESH_STR_TO_EVENT_DTO.keys(), REFRESH_MAP] ) } ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add entities for passed config_entry in HA.""" controller: DeebotController = hass.data[DOMAIN][config_entry.entry_id] def vacuum_entity_generator( device: Device, ) -> Sequence[DeebotVacuum]: return [DeebotVacuum(device)] controller.register_platform_add_entities_generator( async_add_entities, vacuum_entity_generator ) platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_REFRESH, SERVICE_REFRESH_SCHEMA, "service_refresh", ) _ATTR_ROOMS = "rooms" class DeebotVacuum( DeebotEntity[Capabilities, StateVacuumEntityDescription], StateVacuumEntity, # type: ignore ): """Deebot Vacuum.""" _unrecorded_attributes = frozenset({_ATTR_ROOMS}) _attr_supported_features = ( VacuumEntityFeature.PAUSE | VacuumEntityFeature.STOP | VacuumEntityFeature.RETURN_HOME | VacuumEntityFeature.FAN_SPEED | VacuumEntityFeature.BATTERY | VacuumEntityFeature.SEND_COMMAND | VacuumEntityFeature.LOCATE | VacuumEntityFeature.STATE | VacuumEntityFeature.START ) def __init__(self, device: Device): """Initialize the Deebot Vacuum.""" capabilities = device.capabilities super().__init__( device, capabilities, StateVacuumEntityDescription(key="", translation_key="bot", name=None), ) self._rooms: list[Room] = [] self._attr_fan_speed_list = [ level.display_name for level in capabilities.fan_speed.types ] async def async_added_to_hass(self) -> None: """Set up the event listeners now that hass is ready.""" await super().async_added_to_hass() async def on_battery(event: BatteryEvent) -> None: self._attr_battery_level = event.value self.async_write_ha_state() async def on_custom_command(event: CustomCommandEvent) -> None: self.hass.bus.fire(EVENT_CUSTOM_COMMAND, dataclass_to_dict(event)) async def on_fan_speed(event: FanSpeedEvent) -> None: self._attr_fan_speed = event.speed.display_name self.async_write_ha_state() async def on_report_stats(event: ReportStatsEvent) -> None: self.hass.bus.fire(EVENT_CLEANING_JOB, dataclass_to_dict(event)) async def on_rooms(event: RoomsEvent) -> None: self._rooms = event.rooms self.async_write_ha_state() async def on_status(event: StateEvent) -> None: self._attr_state = _STATE_TO_VACUUM_STATE[event.state] self.async_write_ha_state() self._subscribe(self._capability.battery.event, on_battery) self._subscribe(self._capability.fan_speed.event, on_fan_speed) self._subscribe(self._capability.stats.report.event, on_report_stats) self._subscribe(self._capability.state.event, on_status) if custom := self._capability.custom: self._subscribe(custom.event, on_custom_command) if map_caps := self._capability.map: self._subscribe(map_caps.rooms.event, on_rooms) @property def extra_state_attributes(self) -> Mapping[str, Any] | None: """Return entity specific state attributes. Implemented by platform classes. Convention for attribute names is lowercase snake_case. """ attributes: dict[str, Any] = {} rooms: dict[str, Any] = {} for room in self._rooms: # convert room name to snake_case to meet the convention room_name = slugify(room.name) room_values = rooms.get(room_name) if room_values is None: rooms[room_name] = room.id elif isinstance(room_values, list): room_values.append(room.id) else: # Convert from int to list rooms[room_name] = [room_values, room.id] if rooms: attributes[_ATTR_ROOMS] = rooms return attributes async def async_set_fan_speed(self, fan_speed: str, **kwargs: Any) -> None: """Set fan speed.""" await self._device.execute_command(self._capability.fan_speed.set(fan_speed)) async def async_return_to_base(self, **kwargs: Any) -> None: """Set the vacuum cleaner to return to the dock.""" await self._device.execute_command(self._capability.charge.execute()) async def async_stop(self, **kwargs: Any) -> None: """Stop the vacuum cleaner.""" await self._clean_command(CleanAction.STOP) async def async_pause(self) -> None: """Pause the vacuum cleaner.""" await self._clean_command(CleanAction.PAUSE) async def async_start(self) -> None: """Start the vacuum cleaner.""" await self._clean_command(CleanAction.START) async def _clean_command(self, action: CleanAction) -> None: await self._device.execute_command( self._capability.clean.action.command(action) ) async def async_locate(self, **kwargs: Any) -> None: """Locate the vacuum cleaner.""" await self._device.execute_command(self._capability.play_sound.execute()) async def async_send_command( self, command: str, params: dict[str, Any] | None = None, **kwargs: Any ) -> None: """Send a command to a vacuum cleaner.""" _LOGGER.debug("async_send_command %s with %s", command, params) if command in ["spot_area", "custom_area"]: if params is None: raise RuntimeError("Params are required!") if command in "spot_area": await self._device.execute_command( self._capability.clean.action.area( CleanMode.SPOT_AREA, str(params["rooms"]), params.get("cleanings", 1), ) ) elif command == "custom_area": await self._device.execute_command( self._capability.clean.action.area( CleanMode.CUSTOM_AREA, str(params["coordinates"]), params.get("cleanings", 1), ) ) else: await self._device.execute_command( self._capability.custom.set(command, params) ) async def service_refresh(self, category: str) -> None: """Service to manually refresh.""" _LOGGER.warning( 'Service "deebot.refresh" is deprecated. To refresh an entity please use "homeassistant.update_entity" on the respective entity instead' ) async_create_issue( self.hass, DOMAIN, "deprecated_service_refresh", is_fixable=True, severity=IssueSeverity.WARNING, translation_key="deprecated_service_refresh", ) _LOGGER.debug("Manually refresh %s", category) event = REFRESH_STR_TO_EVENT_DTO.get(category, None) if event: self._device.events.request_refresh(event) elif category == REFRESH_MAP: self._device.map.refresh() else: _LOGGER.warning( 'Service "refresh" called with unknown category: %s', category ) ================================================ FILE: hacs.json ================================================ { "filename": "deebot.zip", "homeassistant": "2024.1.0b0", "name": "Deebot 4 Home Assistant", "render_readme": true, "zip_release": true } ================================================ FILE: mypy.ini ================================================ [mypy] python_version = 3.11 show_error_codes = true follow_imports = silent ignore_missing_imports = true strict_equality = true warn_incomplete_stub = true warn_redundant_casts = true warn_unused_configs = true warn_unused_ignores = true check_untyped_defs = true disallow_incomplete_defs = true disallow_subclassing_any = true disallow_untyped_calls = true disallow_untyped_decorators = true disallow_untyped_defs = true no_implicit_optional = true warn_return_any = true warn_unreachable = true ================================================ FILE: pylintrc ================================================ [MASTER] ignore=tests # Use a conservative default here; 2 should speed up most setups and not hurt # any too bad. Override on command line as appropriate. jobs=2 # Return non-zero exit code if any of these messages/categories are detected, # even if score is above --fail-under value. Syntax same as enable. Messages # specified are enabled, while categories only check already-enabled messages. fail-on= useless-suppression, # Specify a score threshold to be exceeded before program exits with error. fail-under=10.0 # List of plugins (as comma separated values of python module names) to load, # usually to register additional checkers. # load-plugins= # Pickle collected data for later comparisons. persistent=no # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. (This is an alternative name to extension-pkg-allow-list # for backward compatibility.) extension-pkg-whitelist=ciso8601, cv2 [BASIC] good-names=i,j,k,ex,_,T,x,y,id [MESSAGES CONTROL] # Reasons disabled: # format - handled by black # duplicate-code - unavoidable # cyclic-import - doesn't test if both import on load # too-many-* - are not enforced for the sake of readability # abstract-method - with intro of async there are always methods missing # inconsistent-return-statements - doesn't handle raise # wrong-import-order - isort guards this # unexpected-keyword-arg - to many false positives disable= format, abstract-method, cyclic-import, duplicate-code, inconsistent-return-statements, too-many-instance-attributes, wrong-import-order, too-few-public-methods, unexpected-keyword-arg # enable useless-suppression temporarily every now and then to clean them up enable= useless-suppression, use-symbolic-message-instead, [REPORTS] score=no [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit,argparse.parse_error [FORMAT] expected-line-ending-format=LF [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "BaseException, Exception". overgeneral-exceptions=builtins.BaseException, builtins.Exception ================================================ FILE: pyproject.toml ================================================ [tool.black] target-version = ['py311'] safe = true ================================================ FILE: requirements.txt ================================================ # if code from specific branch is needed #git+https://github.com/DeebotUniverse/client.py@dev#deebot-client==4.2.0dev0 deebot-client==5.1.0 homeassistant>=2024.1.0b0 mypy==1.8.0 numpy>=1.23.2 pre-commit==3.6.0 pylint==3.0.3 #pytest-homeassistant-custom-component==0.4.4 # uses in deebbot-client, adding for mypi types-cachetools ================================================ FILE: scripts/coverage ================================================ #!/usr/bin/env bash set -e cd "$(dirname "$0")/.." bash scripts/test > /dev/null python3 -m \ coverage \ report \ --skip-covered ================================================ FILE: scripts/develop ================================================ #!/usr/bin/env bash set -e cd "$(dirname "$0")/.." if [ ! -f "${PWD}/config/configuration.yaml" ]; then mkdir -p "${PWD}/config" hass --config "${PWD}/config" --script ensure_config echo "Creating default configuration." echo " default_config: logger: default: info logs: homeassistant.components.vacuum: debug custom_components.deebot: debug deebot_client: debug # If you need to debug uncomment the line below (doc: https://www.home-assistant.io/integrations/debugpy/) debugpy: # wait: true " >> "${PWD}/config/configuration.yaml" fi # Set the python path to include our custom_components directory export PYTHONPATH="${PYTHONPATH}:${PWD}/custom_components" # Start Home Assistant hass --config "${PWD}/config" --debug ================================================ FILE: scripts/install/pip_packages ================================================ #!/usr/bin/env bash set -e python3 -m pip \ install \ --upgrade \ --disable-pip-version-check \ "${@}" ================================================ FILE: scripts/lint ================================================ #!/usr/bin/env bash set -e cd "$(dirname "$0")/.." pre-commit install-hooks; pre-commit run --hook-stage manual --all-files; #bellybutton lint #vulture . --min-confidence 75 --ignore-names policy ================================================ FILE: scripts/run-in-env.sh ================================================ #!/usr/bin/env bash set -eu # Activate pyenv and virtualenv if present, then run the specified command # pyenv, pyenv-virtualenv if [ -s .python-version ]; then PYENV_VERSION=$(head -n 1 .python-version) export PYENV_VERSION fi # other common virtualenvs my_path=$(git rev-parse --show-toplevel) for venv in venv .venv .; do if [ -f "${my_path}/${venv}/bin/activate" ]; then . "${my_path}/${venv}/bin/activate" fi done exec "$@" ================================================ FILE: scripts/setup ================================================ #!/usr/bin/env bash set -e cd "$(dirname "$0")/.." scripts/install/pip_packages "pip" scripts/install/pip_packages setuptools wheel scripts/install/pip_packages --requirement requirements.txt pre-commit install ================================================ FILE: scripts/test ================================================ #!/usr/bin/env bash set -e cd "$(dirname "$0")/.." python3 -m \ pytest \ tests \ -rxf -x -v -l \ --cov=./ \ --cov-report=xml ================================================ FILE: setup.cfg ================================================ [flake8] exclude = .venv,.git,.tox,docs,venv,bin,lib,deps,build doctests = True # To work with Black max-line-length = 88 # E501: line too long # W503: Line break occurred before a binary operator # E203: Whitespace before ':' # D202 No blank lines allowed after function docstring # D107 Missing docstring in __init__ ignore = E501, W503, E203, D202, D107 [isort] # https://github.com/timothycrosley/isort # https://github.com/timothycrosley/isort/wiki/isort-Settings profile = black ================================================ FILE: tests/README.md ================================================ # Why? While tests aren't required to publish a custom component for Home Assistant, they will generally make development easier because good tests will expose when changes you want to make to the component logic will break expected functionality. Home Assistant uses [`pytest`](https://docs.pytest.org/en/latest/) for its tests, and the tests that have been included are modeled after tests that are written for core Home Assistant integrations. These tests pass with 100% coverage (unless something has changed ;) ) and have comments to help you understand the purpose of different parts of the test. # Getting Started To begin, it is recommended to create a virtual environment to install dependencies: ```bash python3 -m venv venv source venv/bin/activate ``` You can then install the dependencies that will allow you to run tests: `pip3 install -r requirements_test.txt.` This will install `homeassistant`, `pytest`, and `pytest-homeassistant-custom-component`, a plugin which allows you to leverage helpers that are available in Home Assistant for core integration tests. # Useful commands | Command | Description | | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pytest tests/` | This will run all tests in `tests/` and tell you how many passed/failed | | `pytest --durations=10 --cov-report term-missing --cov=custom_components.integration_blueprint tests` | This tells `pytest` that your target module to test is `custom_components.integration_blueprint` so that it can give you a [code coverage](https://en.wikipedia.org/wiki/Code_coverage) summary, including % of code that was executed and the line numbers of missed executions. | | `pytest tests/test_init.py -k test_setup_unload_and_reload_entry` | Runs the `test_setup_unload_and_reload_entry` test function located in `tests/test_init.py` | ================================================ FILE: tests/__init__.py ================================================ """Tests for deebot integration.""" ================================================ FILE: tests/conftest.py ================================================ """Global fixtures for integration_blueprint integration.""" # Fixtures allow you to replace functions with a Mock object. You can perform # many options via the Mock to reflect a particular behavior from the original # function that you want to see without going through the function's actual logic. # Fixtures can either be passed into tests as parameters, or if autouse=True, they # will automatically be used across all tests. # # Fixtures that are defined in conftest.py are available across all tests. You can also # define fixtures within a particular test file to scope them locally. # # pytest_homeassistant_custom_component provides some fixtures that are provided by # Home Assistant core. You can find those fixture definitions here: # https://github.com/MatthewFlamm/pytest-homeassistant-custom-component/blob/master/pytest_homeassistant_custom_component/common.py # # See here for more info: https://docs.pytest.org/en/latest/fixture.html (note that # pytest includes fixtures OOB which you can use as defined on this page) from unittest.mock import patch import pytest pytest_plugins = "pytest_homeassistant_custom_component" # This fixture enables loading custom integrations in all tests. # Remove to enable selective use of this fixture @pytest.fixture(autouse=True) def auto_enable_custom_integrations(enable_custom_integrations): yield # This fixture is used to prevent HomeAssistant from attempting to create and dismiss persistent # notifications. These calls would fail without this fixture since the persistent_notification # integration is never loaded during a test. @pytest.fixture(name="skip_notifications", autouse=True) def skip_notifications_fixture(): """Skip notification calls.""" with patch("homeassistant.components.persistent_notification.async_create"), patch( "homeassistant.components.persistent_notification.async_dismiss" ): yield # This fixture, when used, will result in calls to async_get_data to return None. To have the call # return a value, we would add the `return_value=` parameter to the patch call. @pytest.fixture(name="bypass_get_data") def bypass_get_data_fixture(): """Skip calls to get data from API.""" with patch( "custom_components.integration_blueprint.IntegrationBlueprintApiClient.async_get_data" ): yield # In this fixture, we are forcing calls to async_get_data to raise an Exception. This is useful # for exception handling. @pytest.fixture(name="error_on_get_data") def error_get_data_fixture(): """Simulate error when retrieving data from API.""" with patch( "custom_components.integration_blueprint.IntegrationBlueprintApiClient.async_get_data", side_effect=Exception, ): yield ================================================ FILE: translations.schema.json ================================================ { "$schema": "http://json-schema.org/draft-04/schema#", "additionalProperties": false, "definitions": { "translation_name": { "additionalProperties": false, "properties": { "name": { "type": "string" } }, "type": "object" } }, "properties": { "config": { "additionalProperties": false, "properties": { "abort": { "additionalProperties": false, "properties": { "already_configured": { "type": "string" }, "no_supported_devices_found": { "type": "string" }, "reauth_successful": { "type": "string" } }, "type": "object" }, "error": { "additionalProperties": false, "properties": { "cannot_connect": { "type": "string" }, "invalid_auth": { "type": "string" }, "invalid_continent": { "type": "string" }, "invalid_country": { "type": "string" }, "select_robots": { "type": "string" }, "unknown": { "type": "string" } }, "type": "object" }, "step": { "additionalProperties": false, "properties": { "options": { "additionalProperties": false, "properties": { "data": { "additionalProperties": false, "properties": { "devices": { "type": "string" } }, "type": "object" }, "data_description": { "additionalProperties": false, "properties": { "devices": { "type": "string" } }, "type": "object" } }, "type": "object" }, "user": { "additionalProperties": false, "properties": { "data": { "additionalProperties": false, "properties": { "continent": { "type": "string" }, "country": { "type": "string" }, "password": { "type": "string" }, "username": { "type": "string" } }, "type": "object" }, "data_description": { "additionalProperties": false, "properties": { "continent": { "type": "string" }, "country": { "type": "string" } }, "type": "object" } }, "type": "object" }, "user_advanced": { "additionalProperties": false, "properties": { "description": { "type": "string" } }, "type": "object" } }, "type": "object" } }, "type": "object" }, "entity": { "additionalProperties": false, "properties": { "binary_sensor": { "additionalProperties": false, "properties": { "mop_attached": { "$ref": "#/definitions/translation_name" } }, "type": "object" }, "button": { "additionalProperties": false, "properties": { "life_span_brush_reset": { "$ref": "#/definitions/translation_name" }, "life_span_filter_reset": { "$ref": "#/definitions/translation_name" }, "life_span_side_brush_reset": { "$ref": "#/definitions/translation_name" }, "relocate": { "$ref": "#/definitions/translation_name" } }, "type": "object" }, "image": { "additionalProperties": false, "properties": { "map": { "$ref": "#/definitions/translation_name" } }, "type": "object" }, "number": { "additionalProperties": false, "properties": { "clean_count": { "$ref": "#/definitions/translation_name" }, "volume": { "$ref": "#/definitions/translation_name" } }, "type": "object" }, "select": { "additionalProperties": false, "properties": { "water_amount": { "additionalProperties": false, "properties": { "name": { "type": "string" }, "state": { "additionalProperties": false, "properties": { "high": { "type": "string" }, "low": { "type": "string" }, "medium": { "type": "string" }, "ultrahigh": { "type": "string" } }, "type": "object" } }, "type": "object" }, "work_mode": { "additionalProperties": false, "properties": { "name": { "type": "string" }, "state": { "additionalProperties": false, "properties": { "mop": { "type": "string" }, "mop_after_vacuum": { "type": "string" }, "vacuum": { "type": "string" }, "vacuum_and_mop": { "type": "string" } }, "type": "object" } }, "type": "object" } }, "type": "object" }, "sensor": { "additionalProperties": false, "properties": { "battery_level": { "$ref": "#/definitions/translation_name" }, "last_cleaning": { "$ref": "#/definitions/translation_name" }, "last_error": { "$ref": "#/definitions/translation_name" }, "life_span_brush": { "$ref": "#/definitions/translation_name" }, "life_span_filter": { "$ref": "#/definitions/translation_name" }, "life_span_side_brush": { "$ref": "#/definitions/translation_name" }, "stats_area": { "$ref": "#/definitions/translation_name" }, "stats_time": { "$ref": "#/definitions/translation_name" }, "stats_total_area": { "$ref": "#/definitions/translation_name" }, "stats_total_cleanings": { "$ref": "#/definitions/translation_name" }, "stats_total_time": { "$ref": "#/definitions/translation_name" }, "stats_type": { "$ref": "#/definitions/translation_name" }, "wifi_ip": { "$ref": "#/definitions/translation_name" }, "wifi_rssi": { "$ref": "#/definitions/translation_name" }, "wifi_ssid": { "$ref": "#/definitions/translation_name" } }, "type": "object" }, "switch": { "additionalProperties": false, "properties": { "advanced_mode": { "$ref": "#/definitions/translation_name" }, "carpet_auto_fan_speed_boost": { "$ref": "#/definitions/translation_name" }, "clean_preference": { "$ref": "#/definitions/translation_name" }, "continuous_cleaning": { "$ref": "#/definitions/translation_name" }, "true_detect": { "$ref": "#/definitions/translation_name" } }, "type": "object" }, "vacuum": { "additionalProperties": false, "properties": { "bot": { "additionalProperties": false, "properties": { "state_attributes": { "additionalProperties": false, "properties": { "fan_speed": { "additionalProperties": false, "properties": { "state": { "additionalProperties": false, "properties": { "max": { "type": "string" }, "max_plus": { "type": "string" }, "normal": { "type": "string" }, "quiet": { "type": "string" } }, "type": "object" } }, "type": "object" }, "last_error": { "$ref": "#/definitions/translation_name" }, "rooms": { "$ref": "#/definitions/translation_name" } }, "type": "object" } }, "type": "object" }, "carpet_auto_fan_speed_boost": { "$ref": "#/definitions/translation_name" }, "clean_preference": { "$ref": "#/definitions/translation_name" }, "continuous_cleaning": { "$ref": "#/definitions/translation_name" }, "true_detect": { "$ref": "#/definitions/translation_name" } }, "type": "object" } }, "type": "object" }, "issues": { "additionalProperties": false, "properties": { "deprecated_integration_issue": { "additionalProperties": false, "properties": { "description": { "type": "string" }, "title": { "type": "string" } }, "type": "object" }, "deprecated_service_refresh": { "additionalProperties": false, "properties": { "fix_flow": { "additionalProperties": false, "properties": { "step": { "additionalProperties": false, "properties": { "confirm": { "additionalProperties": false, "properties": { "description": { "type": "string" }, "title": { "type": "string" } }, "type": "object" } }, "type": "object" } }, "type": "object" }, "title": { "type": "string" } }, "type": "object" } }, "type": "object" }, "options": { "additionalProperties": false, "properties": { "abort": { "additionalProperties": false, "properties": { "cannot_connect": { "type": "string" }, "invalid_auth": { "type": "string" }, "no_supported_devices_found": { "type": "string" }, "unknown_get_devices": { "type": "string" } }, "type": "object" }, "error": { "additionalProperties": false, "properties": { "select_robots": { "type": "string" }, "unknown": { "type": "string" } }, "type": "object" }, "step": { "additionalProperties": false, "properties": { "init": { "additionalProperties": false, "properties": { "data": { "additionalProperties": false, "properties": { "devices": { "type": "string" } }, "type": "object" }, "data_description": { "additionalProperties": false, "properties": { "devices": { "type": "string" } }, "type": "object" } }, "type": "object" } }, "type": "object" } }, "type": "object" }, "selector": { "additionalProperties": false, "properties": { "refresh_category": { "additionalProperties": false, "properties": { "options": { "additionalProperties": false, "properties": { "battery": { "type": "string" }, "clean_logs": { "type": "string" }, "error": { "type": "string" }, "fan_speed": { "type": "string" }, "life_spans": { "type": "string" }, "map": { "type": "string" }, "rooms": { "type": "string" }, "stats": { "type": "string" }, "status": { "type": "string" }, "water": { "type": "string" } }, "type": "object" } }, "type": "object" } }, "type": "object" }, "services": { "additionalProperties": false, "properties": { "refresh": { "additionalProperties": false, "properties": { "description": { "type": "string" }, "fields": { "additionalProperties": false, "properties": { "category": { "additionalProperties": false, "properties": { "description": { "type": "string" }, "name": { "type": "string" } }, "type": "object" } }, "type": "object" }, "name": { "type": "string" } }, "type": "object" } }, "type": "object" } }, "type": "object" }