├── .yamllint ├── esphome └── components │ └── emporia_vue │ ├── __init__.py │ ├── automation.h │ ├── emporia_vue.h │ ├── emporia_vue.cpp │ └── sensor.py ├── .coveragerc ├── .gitattributes ├── script ├── unit_test ├── component_test ├── quicklint ├── lint-cpp ├── fulltest ├── setup ├── test ├── devcontainer-post-create ├── ci-suggest-changes ├── bump-version.py ├── build_codeowners.py ├── clang-format ├── lint-python ├── helpers.py ├── clang-tidy ├── ci-custom.py ├── api_protobuf │ └── api_protobuf.py └── build_language_schema.py ├── .editorconfig ├── pylintrc ├── .vscode └── tasks.json ├── README.md ├── .pre-commit-config.yaml ├── .dockerignore ├── .gitignore ├── CODE_OF_CONDUCT.md ├── .clang-format ├── .clang-tidy ├── README.old.md └── LICENSE /.yamllint: -------------------------------------------------------------------------------- 1 | --- 2 | ignore: | 3 | venv/ 4 | -------------------------------------------------------------------------------- /esphome/components/emporia_vue/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = esphome/components/* 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Normalize line endings to LF in the repository 2 | * text eol=lf 3 | -------------------------------------------------------------------------------- /script/unit_test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | set -x 8 | 9 | pytest tests/unit_tests 10 | -------------------------------------------------------------------------------- /script/component_test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | set -x 8 | 9 | pytest tests/component_tests 10 | -------------------------------------------------------------------------------- /script/quicklint: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | set -x 8 | 9 | script/ci-custom.py -c 10 | script/lint-python -c 11 | script/lint-cpp -c 12 | -------------------------------------------------------------------------------- /script/lint-cpp: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | set -x 8 | 9 | script/clang-tidy $@ --fix --all-headers 10 | script/clang-format $@ -i 11 | -------------------------------------------------------------------------------- /script/fulltest: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | set -x 8 | 9 | script/ci-custom.py 10 | script/lint-python 11 | script/lint-cpp 12 | script/unit_test 13 | script/component_test 14 | script/test 15 | -------------------------------------------------------------------------------- /script/setup: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Set up ESPHome dev environment 3 | 4 | set -e 5 | 6 | cd "$(dirname "$0")/.." 7 | pip3 install -r requirements.txt -r requirements_optional.txt -r requirements_test.txt 8 | pip3 install --no-use-pep517 -e . 9 | 10 | pre-commit install 11 | -------------------------------------------------------------------------------- /script/test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | set -x 8 | 9 | esphome compile tests/test1.yaml 10 | esphome compile tests/test2.yaml 11 | esphome compile tests/test3.yaml 12 | esphome compile tests/test4.yaml 13 | esphome compile tests/test5.yaml 14 | -------------------------------------------------------------------------------- /script/devcontainer-post-create: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | # set -x 5 | 6 | mkdir -p config 7 | script/setup 8 | 9 | cpp_json=.vscode/c_cpp_properties.json 10 | if [ ! -f $cpp_json ]; then 11 | echo "Initializing PlatformIO..." 12 | pio init --ide vscode --silent 13 | sed -i "/\\/workspaces\/esphome\/include/d" $cpp_json 14 | else 15 | echo "Cpp environment already configured. To reconfigure it you can run one the following commands:" 16 | echo " pio init --ide vscode" 17 | fi 18 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | # general 4 | [*] 5 | end_of_line = lf 6 | insert_final_newline = true 7 | charset = utf-8 8 | 9 | # python 10 | [*.py] 11 | indent_style = space 12 | indent_size = 4 13 | 14 | # C++ 15 | [*.{cpp,h,tcc}] 16 | indent_style = space 17 | indent_size = 2 18 | 19 | # Web 20 | [*.{js,html,css}] 21 | indent_style = space 22 | indent_size = 2 23 | 24 | # YAML 25 | [*.{yaml,yml}] 26 | indent_style = space 27 | indent_size = 2 28 | quote_type = double 29 | 30 | # JSON 31 | [*.json] 32 | indent_style = space 33 | indent_size = 2 34 | -------------------------------------------------------------------------------- /esphome/components/emporia_vue/automation.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #ifdef USE_ESP32 4 | 5 | #include "emporia_vue.h" 6 | 7 | #include "esphome/core/automation.h" 8 | 9 | namespace esphome { 10 | namespace emporia_vue { 11 | 12 | // Trigger for after statistics sensors are updated 13 | class EmporiaVueUpdateTrigger : public Trigger<> { 14 | public: 15 | explicit EmporiaVueUpdateTrigger(EmporiaVueComponent *parent) { 16 | parent->add_on_update_callback([this]() { this->trigger(); }); 17 | } 18 | }; 19 | 20 | } // namespace statistics 21 | } // namespace esphome 22 | 23 | #endif // ifdef USE_ESP32 -------------------------------------------------------------------------------- /script/ci-suggest-changes: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | if git diff-index --quiet HEAD --; then 6 | echo "No changes detected, formatting is correct!" 7 | exit 0 8 | else 9 | echo "=========================================================" 10 | echo "Your formatting is not correct, ESPHome uses clang-format to format" 11 | echo "all source files in a unified way. Please apply the changes listed below" 12 | echo 13 | echo "The following files need to be changed:" 14 | git diff HEAD --name-only | sed 's/^/ /' 15 | echo 16 | echo 17 | echo "=========================================================" 18 | echo 19 | git diff HEAD 20 | exit 1 21 | fi 22 | -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | reports=no 3 | ignore=api_pb2.py 4 | 5 | disable= 6 | format, 7 | missing-docstring, 8 | fixme, 9 | unused-argument, 10 | global-statement, 11 | too-few-public-methods, 12 | too-many-lines, 13 | too-many-locals, 14 | too-many-ancestors, 15 | too-many-branches, 16 | too-many-statements, 17 | too-many-arguments, 18 | too-many-return-statements, 19 | too-many-instance-attributes, 20 | duplicate-code, 21 | invalid-name, 22 | cyclic-import, 23 | redefined-builtin, 24 | undefined-loop-variable, 25 | useless-object-inheritance, 26 | stop-iteration-return, 27 | import-outside-toplevel, 28 | # Broken 29 | unsupported-membership-test, 30 | unsubscriptable-object, 31 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "run", 6 | "type": "shell", 7 | "command": "python3 -m esphome dashboard config/", 8 | "problemMatcher": [] 9 | }, 10 | { 11 | "label": "clang-tidy", 12 | "type": "shell", 13 | "command": "./script/clang-tidy", 14 | "problemMatcher": [ 15 | { 16 | "owner": "clang-tidy", 17 | "fileLocation": "absolute", 18 | "pattern": [ 19 | { 20 | "regexp": "^(.*):(\\d+):(\\d+):\\s+(error):\\s+(.*) \\[([a-z0-9,\\-]+)\\]\\s*$", 21 | "file": 1, 22 | "line": 2, 23 | "column": 3, 24 | "severity": 4, 25 | "message": 5 26 | } 27 | ] 28 | } 29 | ] 30 | } 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Unofficial ESPHome-based local control for your Emporia Vue energy monitor. 2 | 3 | - **Rapid response**: Data updates every five seconds. This allows for quick-responding automations and rapid feedback when your consumption changes. 4 | - **Totally offline**: Everything is completely local, and nothing leaves your network. No internet? No problem, everything still works fine. 5 | - **You're in control**: All the source code and configuration is available for you to use and modify to fit your particular situation. Data feeds into Home Assistant, where it can be visualized and acted upon. 6 | 7 | See [the new website for installation instructions](https://emporia-vue-local.github.io/docs/tutorial/intro). Please leave any feedback or questions in the discussion section. 8 | 9 | The older README that was previously here [is still available](https://github.com/emporia-vue-local/esphome/blob/dev/README.old.md). 10 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # See https://pre-commit.com for more information 3 | # See https://pre-commit.com/hooks.html for more hooks 4 | repos: 5 | - repo: https://github.com/ambv/black 6 | rev: 22.12.0 7 | hooks: 8 | - id: black 9 | args: 10 | - --safe 11 | - --quiet 12 | files: ^((esphome|script|tests)/.+)?[^/]+\.py$ 13 | - repo: https://github.com/PyCQA/flake8 14 | rev: 6.0.0 15 | hooks: 16 | - id: flake8 17 | additional_dependencies: 18 | - flake8-docstrings==1.5.0 19 | - pydocstyle==5.1.1 20 | files: ^(esphome|tests)/.+\.py$ 21 | - repo: https://github.com/pre-commit/pre-commit-hooks 22 | rev: v3.4.0 23 | hooks: 24 | - id: no-commit-to-branch 25 | args: 26 | - --branch=dev 27 | - --branch=release 28 | - --branch=beta 29 | - repo: https://github.com/asottile/pyupgrade 30 | rev: v3.3.0 31 | hooks: 32 | - id: pyupgrade 33 | args: [--py39-plus] 34 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # PlatformIO 107 | .pio/ 108 | 109 | # ESPHome 110 | config/ 111 | examples/ 112 | Dockerfile 113 | .git/ 114 | tests/build/ 115 | -------------------------------------------------------------------------------- /script/bump-version.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import re 5 | import subprocess 6 | from dataclasses import dataclass 7 | import sys 8 | 9 | 10 | @dataclass 11 | class Version: 12 | major: int 13 | minor: int 14 | patch: int 15 | beta: int = 0 16 | dev: bool = False 17 | 18 | def __str__(self): 19 | return f"{self.major}.{self.minor}.{self.full_patch}" 20 | 21 | @property 22 | def full_patch(self): 23 | res = f"{self.patch}" 24 | if self.beta > 0: 25 | res += f"b{self.beta}" 26 | if self.dev: 27 | res += "-dev" 28 | return res 29 | 30 | @classmethod 31 | def parse(cls, value): 32 | match = re.match(r"(\d+).(\d+).(\d+)(b\d+)?(-dev)?", value) 33 | assert match is not None 34 | major = int(match[1]) 35 | minor = int(match[2]) 36 | patch = int(match[3]) 37 | beta = int(match[4][1:]) if match[4] else 0 38 | dev = bool(match[5]) 39 | return Version(major=major, minor=minor, patch=patch, beta=beta, dev=dev) 40 | 41 | 42 | def sub(path, pattern, repl, expected_count=1): 43 | with open(path) as fh: 44 | content = fh.read() 45 | content, count = re.subn(pattern, repl, content, flags=re.MULTILINE) 46 | if expected_count is not None: 47 | assert count == expected_count, f"Pattern {pattern} replacement failed!" 48 | with open(path, "wt") as fh: 49 | fh.write(content) 50 | 51 | 52 | def write_version(version: Version): 53 | sub( 54 | "esphome/const.py", 55 | r"^__version__ = .*$", 56 | f'__version__ = "{version}"', 57 | ) 58 | 59 | 60 | def main(): 61 | parser = argparse.ArgumentParser() 62 | parser.add_argument("new_version", type=str) 63 | args = parser.parse_args() 64 | 65 | version = Version.parse(args.new_version) 66 | print(f"Bumping to {version}") 67 | write_version(version) 68 | return 0 69 | 70 | 71 | if __name__ == "__main__": 72 | sys.exit(main() or 0) 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Hide sublime text stuff 10 | *.sublime-project 11 | *.sublime-workspace 12 | 13 | # Intellij Idea 14 | .idea 15 | 16 | # Vim 17 | *.swp 18 | 19 | # Hide some OS X stuff 20 | .DS_Store 21 | .AppleDouble 22 | .LSOverride 23 | Icon 24 | 25 | # Thumbnails 26 | ._* 27 | 28 | # Distribution / packaging 29 | .Python 30 | build/ 31 | develop-eggs/ 32 | dist/ 33 | downloads/ 34 | eggs/ 35 | .eggs/ 36 | lib/ 37 | lib64/ 38 | parts/ 39 | sdist/ 40 | var/ 41 | wheels/ 42 | *.egg-info/ 43 | .installed.cfg 44 | *.egg 45 | MANIFEST 46 | 47 | # Installer logs 48 | pip-log.txt 49 | pip-delete-this-directory.txt 50 | 51 | # Unit test / coverage reports 52 | htmlcov/ 53 | .tox/ 54 | .coverage 55 | .coverage.* 56 | .cache 57 | .esphome 58 | nosetests.xml 59 | coverage.xml 60 | cov.xml 61 | *.cover 62 | .hypothesis/ 63 | .pytest_cache/ 64 | 65 | # Translations 66 | *.mo 67 | *.pot 68 | 69 | # pyenv 70 | .python-version 71 | 72 | # Environments 73 | .env 74 | .venv 75 | env/ 76 | venv/ 77 | ENV/ 78 | env.bak/ 79 | venv.bak/ 80 | venv-*/ 81 | 82 | # mypy 83 | .mypy_cache/ 84 | 85 | .pioenvs 86 | .piolibdeps 87 | .pio 88 | .vscode/ 89 | !.vscode/tasks.json 90 | CMakeListsPrivate.txt 91 | CMakeLists.txt 92 | 93 | # User-specific stuff: 94 | .idea/**/workspace.xml 95 | .idea/**/tasks.xml 96 | .idea/dictionaries 97 | 98 | # Sensitive or high-churn files: 99 | .idea/**/dataSources/ 100 | .idea/**/dataSources.ids 101 | .idea/**/dataSources.xml 102 | .idea/**/dataSources.local.xml 103 | .idea/**/dynamic.xml 104 | 105 | # CMake 106 | cmake-build-*/ 107 | 108 | CMakeCache.txt 109 | CMakeFiles 110 | CMakeScripts 111 | Testing 112 | Makefile 113 | cmake_install.cmake 114 | install_manifest.txt 115 | compile_commands.json 116 | CTestTestfile.cmake 117 | /*.cbp 118 | 119 | .clang_complete 120 | .gcc-flags.json 121 | 122 | config/ 123 | tests/build/ 124 | tests/.esphome/ 125 | /.temp-clang-tidy.cpp 126 | /.temp/ 127 | .pio/ 128 | 129 | sdkconfig.* 130 | !sdkconfig.defaults 131 | 132 | .tests/ -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at esphome@nabucasa.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /script/build_codeowners.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from pathlib import Path 3 | import sys 4 | import argparse 5 | from collections import defaultdict 6 | 7 | from esphome.helpers import write_file_if_changed 8 | from esphome.config import get_component, get_platform 9 | from esphome.core import CORE 10 | 11 | parser = argparse.ArgumentParser() 12 | parser.add_argument( 13 | "--check", help="Check if the CODEOWNERS file is up to date.", action="store_true" 14 | ) 15 | args = parser.parse_args() 16 | 17 | # The root directory of the repo 18 | root = Path(__file__).parent.parent 19 | components_dir = root / "esphome" / "components" 20 | 21 | BASE = """ 22 | # This file is generated by script/build_codeowners.py 23 | # People marked here will be automatically requested for a review 24 | # when the code that they own is touched. 25 | # 26 | # Every time an issue is created with a label corresponding to an integration, 27 | # the integration's code owner is automatically notified. 28 | 29 | # Core Code 30 | setup.py @esphome/core 31 | esphome/*.py @esphome/core 32 | esphome/core/* @esphome/core 33 | 34 | # Integrations 35 | """.strip() 36 | 37 | parts = [BASE] 38 | 39 | # Fake some directory so that get_component works 40 | CORE.config_path = str(root) 41 | 42 | codeowners = defaultdict(list) 43 | 44 | for path in components_dir.iterdir(): 45 | if not path.is_dir(): 46 | continue 47 | if not (path / "__init__.py").is_file(): 48 | continue 49 | 50 | name = path.name 51 | comp = get_component(name) 52 | if comp is None: 53 | print( 54 | f"Cannot find component {name}. Make sure current path is pip installed ESPHome" 55 | ) 56 | sys.exit(1) 57 | 58 | codeowners[f"esphome/components/{name}/*"].extend(comp.codeowners) 59 | 60 | for platform_path in path.iterdir(): 61 | platform_name = platform_path.stem 62 | platform = get_platform(platform_name, name) 63 | if platform is None: 64 | continue 65 | 66 | if platform_path.is_dir(): 67 | # Sub foldered platforms get their own line 68 | if not (platform_path / "__init__.py").is_file(): 69 | continue 70 | codeowners[f"esphome/components/{name}/{platform_name}/*"].extend( 71 | platform.codeowners 72 | ) 73 | continue 74 | 75 | # Non-subfoldered platforms add to codeowners at component level 76 | if not platform_path.is_file() or platform_path.name == "__init__.py": 77 | continue 78 | codeowners[f"esphome/components/{name}/*"].extend(platform.codeowners) 79 | 80 | 81 | for path, owners in sorted(codeowners.items()): 82 | owners = sorted(set(owners)) 83 | if not owners: 84 | continue 85 | for owner in owners: 86 | if not owner.startswith("@"): 87 | print( 88 | f"Codeowner {owner} for integration {path} must start with an '@' symbol!" 89 | ) 90 | sys.exit(1) 91 | parts.append(f"{path} {' '.join(owners)}") 92 | 93 | 94 | # End newline 95 | parts.append("") 96 | content = "\n".join(parts) 97 | codeowners_file = root / "CODEOWNERS" 98 | 99 | if args.check: 100 | if codeowners_file.read_text() != content: 101 | print("CODEOWNERS file is not up to date.") 102 | print("Please run `script/build_codeowners.py`") 103 | sys.exit(1) 104 | print("CODEOWNERS file is up to date") 105 | else: 106 | write_file_if_changed(codeowners_file, content) 107 | print("Wrote CODEOWNERS") 108 | -------------------------------------------------------------------------------- /script/clang-format: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from helpers import print_error_for_file, get_output, git_ls_files, filter_changed 4 | import argparse 5 | import click 6 | import colorama 7 | import multiprocessing 8 | import os 9 | import queue 10 | import re 11 | import subprocess 12 | import sys 13 | import threading 14 | 15 | 16 | def run_format(args, queue, lock, failed_files): 17 | """Takes filenames out of queue and runs clang-format on them.""" 18 | while True: 19 | path = queue.get() 20 | invocation = ["clang-format-11"] 21 | if args.inplace: 22 | invocation.append("-i") 23 | else: 24 | invocation.extend(["--dry-run", "-Werror"]) 25 | invocation.append(path) 26 | 27 | proc = subprocess.run(invocation, capture_output=True, encoding="utf-8") 28 | if proc.returncode != 0: 29 | with lock: 30 | print_error_for_file(path, proc.stderr) 31 | failed_files.append(path) 32 | queue.task_done() 33 | 34 | 35 | def progress_bar_show(value): 36 | return value if value is not None else "" 37 | 38 | 39 | def main(): 40 | colorama.init() 41 | 42 | parser = argparse.ArgumentParser() 43 | parser.add_argument( 44 | "-j", 45 | "--jobs", 46 | type=int, 47 | default=multiprocessing.cpu_count(), 48 | help="number of format instances to be run in parallel.", 49 | ) 50 | parser.add_argument( 51 | "files", nargs="*", default=[], help="files to be processed (regex on path)" 52 | ) 53 | parser.add_argument( 54 | "-i", "--inplace", action="store_true", help="reformat files in-place" 55 | ) 56 | parser.add_argument( 57 | "-c", "--changed", action="store_true", help="only run on changed files" 58 | ) 59 | args = parser.parse_args() 60 | 61 | try: 62 | get_output("clang-format-11", "-version") 63 | except: 64 | print( 65 | """ 66 | Oops. It looks like clang-format is not installed. 67 | 68 | Please check you can run "clang-format-11 -version" in your terminal and install 69 | clang-format (v11) if necessary. 70 | 71 | Note you can also upload your code as a pull request on GitHub and see the CI check 72 | output to apply clang-format. 73 | """ 74 | ) 75 | return 1 76 | 77 | files = [] 78 | for path in git_ls_files(["*.cpp", "*.h", "*.tcc"]): 79 | files.append(os.path.relpath(path, os.getcwd())) 80 | 81 | if args.files: 82 | # Match against files specified on command-line 83 | file_name_re = re.compile("|".join(args.files)) 84 | files = [p for p in files if file_name_re.search(p)] 85 | 86 | if args.changed: 87 | files = filter_changed(files) 88 | 89 | files.sort() 90 | 91 | failed_files = [] 92 | try: 93 | task_queue = queue.Queue(args.jobs) 94 | lock = threading.Lock() 95 | for _ in range(args.jobs): 96 | t = threading.Thread( 97 | target=run_format, args=(args, task_queue, lock, failed_files) 98 | ) 99 | t.daemon = True 100 | t.start() 101 | 102 | # Fill the queue with files. 103 | with click.progressbar( 104 | files, width=30, file=sys.stderr, item_show_func=progress_bar_show 105 | ) as bar: 106 | for name in bar: 107 | task_queue.put(name) 108 | 109 | # Wait for all threads to be done. 110 | task_queue.join() 111 | 112 | except KeyboardInterrupt: 113 | print() 114 | print("Ctrl-C detected, goodbye.") 115 | os.kill(0, 9) 116 | 117 | sys.exit(len(failed_files)) 118 | 119 | 120 | if __name__ == "__main__": 121 | main() 122 | -------------------------------------------------------------------------------- /script/lint-python: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from helpers import ( 4 | styled, 5 | print_error_for_file, 6 | get_output, 7 | get_err, 8 | git_ls_files, 9 | filter_changed, 10 | ) 11 | import argparse 12 | import colorama 13 | import os 14 | import re 15 | import sys 16 | 17 | curfile = None 18 | 19 | 20 | def print_error(file, lineno, msg): 21 | global curfile 22 | 23 | if curfile != file: 24 | print_error_for_file(file, None) 25 | curfile = file 26 | 27 | if lineno is not None: 28 | print(f"{styled(colorama.Style.BRIGHT, f'{file}:{lineno}:')} {msg}") 29 | else: 30 | print(f"{styled(colorama.Style.BRIGHT, f'{file}:')} {msg}") 31 | 32 | 33 | def main(): 34 | colorama.init() 35 | 36 | parser = argparse.ArgumentParser() 37 | parser.add_argument( 38 | "files", nargs="*", default=[], help="files to be processed (regex on path)" 39 | ) 40 | parser.add_argument( 41 | "-c", "--changed", action="store_true", help="Only run on changed files" 42 | ) 43 | parser.add_argument( 44 | "-a", 45 | "--apply", 46 | action="store_true", 47 | help="Apply changes to files where possible", 48 | ) 49 | args = parser.parse_args() 50 | 51 | files = [] 52 | for path in git_ls_files(): 53 | filetypes = (".py",) 54 | ext = os.path.splitext(path)[1] 55 | if ext in filetypes and path.startswith("esphome"): 56 | path = os.path.relpath(path, os.getcwd()) 57 | files.append(path) 58 | # Match against re 59 | file_name_re = re.compile("|".join(args.files)) 60 | files = [p for p in files if file_name_re.search(p)] 61 | 62 | if args.changed: 63 | files = filter_changed(files) 64 | 65 | files.sort() 66 | if not files: 67 | sys.exit(0) 68 | 69 | errors = 0 70 | 71 | cmd = ["black", "--verbose"] + ([] if args.apply else ["--check"]) + files 72 | print("Running black...") 73 | print() 74 | log = get_err(*cmd) 75 | for line in log.splitlines(): 76 | WOULD_REFORMAT = "would reformat" 77 | if line.startswith(WOULD_REFORMAT): 78 | file_ = line[len(WOULD_REFORMAT) + 1 :] 79 | print_error(file_, None, "Please format this file with the black formatter") 80 | errors += 1 81 | 82 | cmd = ["flake8"] + files 83 | print() 84 | print("Running flake8...") 85 | print() 86 | log = get_output(*cmd) 87 | for line in log.splitlines(): 88 | line = line.split(":", 4) 89 | if len(line) < 4: 90 | continue 91 | file_ = line[0] 92 | linno = line[1] 93 | msg = (":".join(line[3:])).strip() 94 | print_error(file_, linno, msg) 95 | errors += 1 96 | 97 | cmd = ["pylint", "-f", "parseable", "--persistent=n"] + files 98 | print() 99 | print("Running pylint...") 100 | print() 101 | log = get_output(*cmd) 102 | for line in log.splitlines(): 103 | line = line.split(":", 3) 104 | if len(line) < 3: 105 | continue 106 | file_ = line[0] 107 | linno = line[1] 108 | msg = (":".join(line[2:])).strip() 109 | print_error(file_, linno, msg) 110 | errors += 1 111 | 112 | PYUPGRADE_TARGET = "--py39-plus" 113 | cmd = ["pyupgrade", PYUPGRADE_TARGET] + files 114 | print() 115 | print("Running pyupgrade...") 116 | print() 117 | log = get_err(*cmd) 118 | for line in log.splitlines(): 119 | REWRITING = "Rewriting" 120 | if line.startswith(REWRITING): 121 | file_ = line[len(REWRITING) + 1 :] 122 | print_error( 123 | file_, None, f"Please run pyupgrade {PYUPGRADE_TARGET} on this file" 124 | ) 125 | errors += 1 126 | 127 | sys.exit(errors) 128 | 129 | 130 | if __name__ == "__main__": 131 | main() 132 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | Language: Cpp 2 | AccessModifierOffset: -1 3 | AlignAfterOpenBracket: Align 4 | AlignConsecutiveAssignments: false 5 | AlignConsecutiveDeclarations: false 6 | AlignEscapedNewlines: DontAlign 7 | AlignOperands: true 8 | AlignTrailingComments: true 9 | AllowAllParametersOfDeclarationOnNextLine: true 10 | AllowShortBlocksOnASingleLine: false 11 | AllowShortCaseLabelsOnASingleLine: false 12 | AllowShortFunctionsOnASingleLine: All 13 | AllowShortIfStatementsOnASingleLine: false 14 | AllowShortLoopsOnASingleLine: false 15 | AlwaysBreakAfterReturnType: None 16 | AlwaysBreakBeforeMultilineStrings: false 17 | AlwaysBreakTemplateDeclarations: MultiLine 18 | BinPackArguments: true 19 | BinPackParameters: true 20 | BraceWrapping: 21 | AfterClass: false 22 | AfterControlStatement: false 23 | AfterEnum: false 24 | AfterFunction: false 25 | AfterNamespace: false 26 | AfterObjCDeclaration: false 27 | AfterStruct: false 28 | AfterUnion: false 29 | AfterExternBlock: false 30 | BeforeCatch: false 31 | BeforeElse: false 32 | IndentBraces: false 33 | SplitEmptyFunction: true 34 | SplitEmptyRecord: true 35 | SplitEmptyNamespace: true 36 | BreakBeforeBinaryOperators: None 37 | BreakBeforeBraces: Attach 38 | BreakBeforeInheritanceComma: false 39 | BreakInheritanceList: BeforeColon 40 | BreakBeforeTernaryOperators: true 41 | BreakConstructorInitializersBeforeComma: false 42 | BreakConstructorInitializers: BeforeColon 43 | BreakAfterJavaFieldAnnotations: false 44 | BreakStringLiterals: true 45 | ColumnLimit: 120 46 | CommentPragmas: '^ IWYU pragma:' 47 | CompactNamespaces: false 48 | ConstructorInitializerAllOnOneLineOrOnePerLine: true 49 | ConstructorInitializerIndentWidth: 4 50 | ContinuationIndentWidth: 4 51 | Cpp11BracedListStyle: true 52 | DerivePointerAlignment: false 53 | DisableFormat: false 54 | ExperimentalAutoDetectBinPacking: false 55 | FixNamespaceComments: true 56 | ForEachMacros: 57 | - foreach 58 | - Q_FOREACH 59 | - BOOST_FOREACH 60 | IncludeBlocks: Preserve 61 | IncludeCategories: 62 | - Regex: '^' 63 | Priority: 2 64 | - Regex: '^<.*\.h>' 65 | Priority: 1 66 | - Regex: '^<.*' 67 | Priority: 2 68 | - Regex: '.*' 69 | Priority: 3 70 | IncludeIsMainRegex: '([-_](test|unittest))?$' 71 | IndentCaseLabels: true 72 | IndentPPDirectives: None 73 | IndentWidth: 2 74 | IndentWrappedFunctionNames: false 75 | KeepEmptyLinesAtTheStartOfBlocks: false 76 | MacroBlockBegin: '' 77 | MacroBlockEnd: '' 78 | MaxEmptyLinesToKeep: 1 79 | NamespaceIndentation: None 80 | PenaltyBreakAssignment: 2 81 | PenaltyBreakBeforeFirstCallParameter: 1 82 | PenaltyBreakComment: 300 83 | PenaltyBreakFirstLessLess: 120 84 | PenaltyBreakString: 1000 85 | PenaltyBreakTemplateDeclaration: 10 86 | PenaltyExcessCharacter: 1000000 87 | PenaltyReturnTypeOnItsOwnLine: 2000 88 | PointerAlignment: Right 89 | RawStringFormats: 90 | - Language: Cpp 91 | Delimiters: 92 | - cc 93 | - CC 94 | - cpp 95 | - Cpp 96 | - CPP 97 | - 'c++' 98 | - 'C++' 99 | CanonicalDelimiter: '' 100 | BasedOnStyle: google 101 | - Language: TextProto 102 | Delimiters: 103 | - pb 104 | - PB 105 | - proto 106 | - PROTO 107 | EnclosingFunctions: 108 | - EqualsProto 109 | - EquivToProto 110 | - PARSE_PARTIAL_TEXT_PROTO 111 | - PARSE_TEST_PROTO 112 | - PARSE_TEXT_PROTO 113 | - ParseTextOrDie 114 | - ParseTextProtoOrDie 115 | CanonicalDelimiter: '' 116 | BasedOnStyle: google 117 | ReflowComments: true 118 | SortIncludes: false 119 | SortUsingDeclarations: false 120 | SpaceAfterCStyleCast: true 121 | SpaceAfterTemplateKeyword: false 122 | SpaceBeforeAssignmentOperators: true 123 | SpaceBeforeCpp11BracedList: false 124 | SpaceBeforeCtorInitializerColon: true 125 | SpaceBeforeInheritanceColon: true 126 | SpaceBeforeParens: ControlStatements 127 | SpaceBeforeRangeBasedForLoopColon: true 128 | SpaceInEmptyParentheses: false 129 | SpacesBeforeTrailingComments: 2 130 | SpacesInAngles: false 131 | SpacesInContainerLiterals: false 132 | SpacesInCStyleCastParentheses: false 133 | SpacesInParentheses: false 134 | SpacesInSquareBrackets: false 135 | Standard: Auto 136 | TabWidth: 2 137 | UseTab: Never 138 | -------------------------------------------------------------------------------- /esphome/components/emporia_vue/emporia_vue.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #ifdef USE_ESP32 4 | 5 | #include 6 | #include 7 | 8 | #include "esphome/core/component.h" 9 | #include "esphome/components/i2c/i2c.h" 10 | #include "esphome/components/sensor/sensor.h" 11 | 12 | namespace esphome { 13 | namespace emporia_vue { 14 | 15 | struct __attribute__((__packed__)) ReadingPowerEntry { 16 | int32_t phase_black; 17 | int32_t phase_red; 18 | int32_t phase_blue; 19 | }; 20 | 21 | struct __attribute__((__packed__)) SensorReading { 22 | bool is_unread; 23 | uint8_t checksum; 24 | uint8_t unknown; 25 | uint8_t sequence_num; 26 | 27 | ReadingPowerEntry power[19]; 28 | 29 | uint16_t voltage[3]; 30 | uint16_t frequency; 31 | uint16_t degrees[2]; 32 | 33 | uint16_t current[19]; 34 | 35 | uint16_t end; 36 | }; 37 | 38 | class PhaseConfig; 39 | class CTClampConfig; 40 | 41 | class EmporiaVueComponent : public PollingComponent, public i2c::I2CDevice { 42 | public: 43 | void dump_config() override; 44 | 45 | float get_setup_priority() const override { return esphome::setup_priority::HARDWARE; } 46 | 47 | void set_phases(std::vector phases) { this->phases_ = std::move(phases); } 48 | void set_ct_clamps(std::vector ct_clamps) { this->ct_clamps_ = std::move(ct_clamps); } 49 | 50 | void update() override; 51 | 52 | void add_on_update_callback(std::function &&callback); 53 | 54 | protected: 55 | uint8_t last_sequence_num_ = 0; 56 | std::vector phases_; 57 | std::vector ct_clamps_; 58 | CallbackManager callback_; 59 | }; 60 | 61 | enum PhaseInputWire : uint8_t { 62 | BLACK = 0, 63 | RED = 1, 64 | BLUE = 2, 65 | }; 66 | 67 | class PhaseConfig { 68 | public: 69 | void set_input_wire(PhaseInputWire input_wire) { this->input_wire_ = input_wire; } 70 | PhaseInputWire get_input_wire() const { return this->input_wire_; } 71 | void set_calibration(float calibration) { this->calibration_ = calibration; } 72 | float get_calibration() const { return this->calibration_; } 73 | void set_voltage_sensor(sensor::Sensor *voltage_sensor) { this->voltage_sensor_ = voltage_sensor; } 74 | sensor::Sensor *get_voltage_sensor() const { return this->voltage_sensor_; } 75 | void set_frequency_sensor(sensor::Sensor *frequency_sensor) { this->frequency_sensor_ = frequency_sensor; } 76 | sensor::Sensor *get_frequency_sensor() const { return this->frequency_sensor_; } 77 | void set_phase_angle_sensor(sensor::Sensor *phase_angle_sensor) { this->phase_angle_sensor_ = phase_angle_sensor; } 78 | sensor::Sensor *get_phase_angle_sensor() const { return this->phase_angle_sensor_; } 79 | 80 | void update_from_reading(const SensorReading &sensor_reading); 81 | 82 | int32_t extract_power_for_phase(const ReadingPowerEntry &power_entry); 83 | 84 | protected: 85 | PhaseInputWire input_wire_; 86 | float calibration_; 87 | sensor::Sensor *voltage_sensor_{nullptr}; 88 | sensor::Sensor *frequency_sensor_{nullptr}; 89 | sensor::Sensor *phase_angle_sensor_{nullptr}; 90 | }; 91 | 92 | enum CTInputPort : uint8_t { 93 | #if defined(EMPORIA_VUE_VARIANT_VUE3) 94 | A = 2, 95 | B = 1, 96 | C = 0, 97 | #else 98 | A = 0, 99 | B = 1, 100 | C = 2, 101 | #endif 102 | ONE = 3, 103 | TWO = 4, 104 | THREE = 5, 105 | FOUR = 6, 106 | FIVE = 7, 107 | SIX = 8, 108 | SEVEN = 9, 109 | EIGHT = 10, 110 | NINE = 11, 111 | TEN = 12, 112 | ELEVEN = 13, 113 | TWELVE = 14, 114 | THIRTEEN = 15, 115 | FOURTEEN = 16, 116 | FIFTEEN = 17, 117 | SIXTEEN = 18, 118 | }; 119 | 120 | class CTClampConfig : public sensor::Sensor { 121 | public: 122 | void set_phase(PhaseConfig *phase) { this->phase_ = phase; }; 123 | const PhaseConfig *get_phase() const { return this->phase_; } 124 | void set_input_port(CTInputPort input_port) { this->input_port_ = input_port; }; 125 | CTInputPort get_input_port() const { return this->input_port_; } 126 | void set_power_sensor(sensor::Sensor *power_sensor) { this->power_sensor_ = power_sensor; } 127 | sensor::Sensor *get_power_sensor() const { return this->power_sensor_; } 128 | void set_current_sensor(sensor::Sensor *current_sensor) { this->current_sensor_ = current_sensor; } 129 | sensor::Sensor *get_current_sensor() const { return this->current_sensor_; } 130 | 131 | void update_from_reading(const SensorReading &sensor_reading); 132 | float get_calibrated_power(int32_t raw_power) const; 133 | 134 | protected: 135 | PhaseConfig *phase_; 136 | CTInputPort input_port_; 137 | sensor::Sensor *power_sensor_{nullptr}; 138 | sensor::Sensor *current_sensor_{nullptr}; 139 | }; 140 | 141 | } // namespace emporia_vue 142 | } // namespace esphome 143 | 144 | #endif // ifdef USE_ESP32 145 | -------------------------------------------------------------------------------- /script/helpers.py: -------------------------------------------------------------------------------- 1 | import colorama 2 | import os.path 3 | import re 4 | import subprocess 5 | import json 6 | from pathlib import Path 7 | 8 | root_path = os.path.abspath(os.path.normpath(os.path.join(__file__, "..", ".."))) 9 | basepath = os.path.join(root_path, "esphome") 10 | temp_folder = os.path.join(root_path, ".temp") 11 | temp_header_file = os.path.join(temp_folder, "all-include.cpp") 12 | 13 | 14 | def styled(color, msg, reset=True): 15 | prefix = "".join(color) if isinstance(color, tuple) else color 16 | suffix = colorama.Style.RESET_ALL if reset else "" 17 | return prefix + msg + suffix 18 | 19 | 20 | def print_error_for_file(file, body): 21 | print( 22 | styled(colorama.Fore.GREEN, "### File ") 23 | + styled((colorama.Fore.GREEN, colorama.Style.BRIGHT), file) 24 | ) 25 | print() 26 | if body is not None: 27 | print(body) 28 | print() 29 | 30 | 31 | def build_all_include(): 32 | # Build a cpp file that includes all header files in this repo. 33 | # Otherwise header-only integrations would not be tested by clang-tidy 34 | headers = [] 35 | for path in walk_files(basepath): 36 | filetypes = (".h",) 37 | ext = os.path.splitext(path)[1] 38 | if ext in filetypes: 39 | path = os.path.relpath(path, root_path) 40 | include_p = path.replace(os.path.sep, "/") 41 | headers.append(f'#include "{include_p}"') 42 | headers.sort() 43 | headers.append("") 44 | content = "\n".join(headers) 45 | p = Path(temp_header_file) 46 | p.parent.mkdir(exist_ok=True) 47 | p.write_text(content) 48 | 49 | 50 | def walk_files(path): 51 | for root, _, files in os.walk(path): 52 | for name in files: 53 | yield os.path.join(root, name) 54 | 55 | 56 | def get_output(*args): 57 | proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 58 | output, err = proc.communicate() 59 | return output.decode("utf-8") 60 | 61 | 62 | def get_err(*args): 63 | proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 64 | output, err = proc.communicate() 65 | return err.decode("utf-8") 66 | 67 | 68 | def splitlines_no_ends(string): 69 | return [s.strip() for s in string.splitlines()] 70 | 71 | 72 | def changed_files(): 73 | check_remotes = ["upstream", "origin"] 74 | check_remotes.extend(splitlines_no_ends(get_output("git", "remote"))) 75 | for remote in check_remotes: 76 | command = ["git", "merge-base", f"refs/remotes/{remote}/dev", "HEAD"] 77 | try: 78 | merge_base = splitlines_no_ends(get_output(*command))[0] 79 | break 80 | # pylint: disable=bare-except 81 | except: 82 | pass 83 | else: 84 | raise ValueError("Git not configured") 85 | command = ["git", "diff", merge_base, "--name-only"] 86 | changed = splitlines_no_ends(get_output(*command)) 87 | changed = [os.path.relpath(f, os.getcwd()) for f in changed] 88 | changed.sort() 89 | return changed 90 | 91 | 92 | def filter_changed(files): 93 | changed = changed_files() 94 | files = [f for f in files if f in changed] 95 | print("Changed files:") 96 | if not files: 97 | print(" No changed files!") 98 | for c in files: 99 | print(f" {c}") 100 | return files 101 | 102 | 103 | def filter_grep(files, value): 104 | matched = [] 105 | for file in files: 106 | with open(file) as handle: 107 | contents = handle.read() 108 | if value in contents: 109 | matched.append(file) 110 | return matched 111 | 112 | 113 | def git_ls_files(patterns=None): 114 | command = ["git", "ls-files", "-s"] 115 | if patterns is not None: 116 | command.extend(patterns) 117 | proc = subprocess.Popen(command, stdout=subprocess.PIPE) 118 | output, err = proc.communicate() 119 | lines = [x.split() for x in output.decode("utf-8").splitlines()] 120 | return {s[3].strip(): int(s[0]) for s in lines} 121 | 122 | 123 | def load_idedata(environment): 124 | platformio_ini = Path(root_path) / "platformio.ini" 125 | temp_idedata = Path(temp_folder) / f"idedata-{environment}.json" 126 | changed = False 127 | if not platformio_ini.is_file() or not temp_idedata.is_file(): 128 | changed = True 129 | elif platformio_ini.stat().st_mtime >= temp_idedata.stat().st_mtime: 130 | changed = True 131 | 132 | if "idf" in environment: 133 | # remove full sdkconfig when the defaults have changed so that it is regenerated 134 | default_sdkconfig = Path(root_path) / "sdkconfig.defaults" 135 | temp_sdkconfig = Path(temp_folder) / f"sdkconfig-{environment}" 136 | 137 | if not temp_sdkconfig.is_file(): 138 | changed = True 139 | elif default_sdkconfig.stat().st_mtime >= temp_sdkconfig.stat().st_mtime: 140 | temp_sdkconfig.unlink() 141 | changed = True 142 | 143 | if not changed: 144 | return json.loads(temp_idedata.read_text()) 145 | 146 | # ensure temp directory exists before running pio, as it writes sdkconfig to it 147 | Path(temp_folder).mkdir(exist_ok=True) 148 | 149 | stdout = subprocess.check_output(["pio", "run", "-t", "idedata", "-e", environment]) 150 | match = re.search(r'{\s*".*}', stdout.decode("utf-8")) 151 | data = json.loads(match.group()) 152 | 153 | temp_idedata.write_text(json.dumps(data, indent=2) + "\n") 154 | return data 155 | -------------------------------------------------------------------------------- /esphome/components/emporia_vue/emporia_vue.cpp: -------------------------------------------------------------------------------- 1 | #include "emporia_vue.h" 2 | #include "esphome/core/hal.h" 3 | #include "esphome/core/log.h" 4 | 5 | namespace esphome { 6 | namespace emporia_vue { 7 | 8 | static const char *const TAG = "emporia_vue"; 9 | 10 | #if defined(EMPORIA_VUE_VARIANT_VUE3) 11 | static constexpr float EMPORIA_VUE_FREQUENCY_CONSTANT = 19610.0f; 12 | #else 13 | static constexpr float EMPORIA_VUE_FREQUENCY_CONSTANT = 25310.0f; 14 | #endif 15 | 16 | void EmporiaVueComponent::dump_config() { 17 | ESP_LOGCONFIG(TAG, "Emporia Vue"); 18 | #if defined(EMPORIA_VUE_VARIANT_VUE3) 19 | ESP_LOGCONFIG(TAG, " Variant: Vue 3"); 20 | #else 21 | ESP_LOGCONFIG(TAG, " Variant: Vue 2"); 22 | #endif 23 | LOG_I2C_DEVICE(this); 24 | 25 | for (auto *phase : this->phases_) { 26 | std::string wire; 27 | switch (phase->get_input_wire()) { 28 | case PhaseInputWire::BLACK: 29 | wire = "BLACK"; 30 | break; 31 | case PhaseInputWire::RED: 32 | wire = "RED"; 33 | break; 34 | case PhaseInputWire::BLUE: 35 | wire = "BLUE"; 36 | break; 37 | } 38 | ESP_LOGCONFIG(TAG, " Phase"); 39 | ESP_LOGCONFIG(TAG, " Wire: %s", wire.c_str()); 40 | ESP_LOGCONFIG(TAG, " Calibration: %f", phase->get_calibration()); 41 | LOG_SENSOR(" ", "Voltage", phase->get_voltage_sensor()); 42 | } 43 | 44 | for (auto *ct_clamp : this->ct_clamps_) { 45 | ESP_LOGCONFIG(TAG, " CT Clamp"); 46 | ESP_LOGCONFIG(TAG, " Phase Calibration: %f", ct_clamp->get_phase()->get_calibration()); 47 | ESP_LOGCONFIG(TAG, " CT Port Index: %d", ct_clamp->get_input_port()); 48 | LOG_SENSOR(" ", "Power", ct_clamp->get_power_sensor()); 49 | LOG_SENSOR(" ", "Current", ct_clamp->get_current_sensor()); 50 | } 51 | } 52 | 53 | void EmporiaVueComponent::update() { 54 | SensorReading sensor_reading; 55 | 56 | i2c::ErrorCode err = read(reinterpret_cast(&sensor_reading), sizeof(sensor_reading)); 57 | 58 | if (err != i2c::ErrorCode::ERROR_OK) { 59 | ESP_LOGE(TAG, "Failed to read from sensor due to I2C error %d", err); 60 | return; 61 | } 62 | 63 | if (sensor_reading.end != 0) { 64 | ESP_LOGE(TAG, "Failed to read from sensor due to a malformed reading, should end in null bytes but is %d", 65 | sensor_reading.end); 66 | return; 67 | } 68 | 69 | if (!sensor_reading.is_unread) { 70 | ESP_LOGV(TAG, "Ignoring sensor reading that is marked as read"); 71 | return; 72 | } 73 | 74 | ESP_LOGV(TAG, "Received sensor reading with sequence #%d", sensor_reading.sequence_num); 75 | 76 | if (this->last_sequence_num_ && sensor_reading.sequence_num > this->last_sequence_num_ + 1) { 77 | ESP_LOGW(TAG, "Detected %d missing reading(s), data may not be accurate!", 78 | sensor_reading.sequence_num - this->last_sequence_num_ - 1); 79 | } 80 | 81 | for (auto *phase : this->phases_) { 82 | phase->update_from_reading(sensor_reading); 83 | } 84 | for (auto *ct_clamp : this->ct_clamps_) { 85 | ct_clamp->update_from_reading(sensor_reading); 86 | } 87 | 88 | this->last_sequence_num_ = sensor_reading.sequence_num; 89 | 90 | this->callback_.call(); 91 | } 92 | 93 | void EmporiaVueComponent::add_on_update_callback(std::function &&callback) { 94 | this->callback_.add(std::move(callback)); 95 | } 96 | 97 | static inline bool is_mains_port(CTInputPort port) { 98 | return port == CTInputPort::A || port == CTInputPort::B || port == CTInputPort::C; 99 | } 100 | 101 | void PhaseConfig::update_from_reading(const SensorReading &sensor_reading) { 102 | if (this->voltage_sensor_) { 103 | float calibrated_voltage = sensor_reading.voltage[this->input_wire_] * this->calibration_; 104 | this->voltage_sensor_->publish_state(calibrated_voltage); 105 | } 106 | 107 | uint16_t raw_frequency = sensor_reading.frequency; 108 | // validation that these sensors are allowed on this phase is done in the codegen stage 109 | if (this->frequency_sensor_) { 110 | // see https://github.com/emporia-vue-local/esphome/pull/88 for constant explanation 111 | float frequency = EMPORIA_VUE_FREQUENCY_CONSTANT / static_cast(raw_frequency); 112 | this->frequency_sensor_->publish_state(frequency); 113 | } 114 | if (this->phase_angle_sensor_) { 115 | uint16_t raw_phase_angle = sensor_reading.degrees[((uint8_t) this->input_wire_) - 1]; 116 | float phase_angle = ((float) raw_phase_angle) * 360.0f / ((float) raw_frequency); 117 | // this is truncated to a uint16_t on the vue 2 118 | this->phase_angle_sensor_->publish_state(phase_angle); 119 | } 120 | } 121 | 122 | int32_t PhaseConfig::extract_power_for_phase(const ReadingPowerEntry &power_entry) { 123 | switch (this->input_wire_) { 124 | case PhaseInputWire::BLACK: 125 | return power_entry.phase_black; 126 | case PhaseInputWire::RED: 127 | return power_entry.phase_red; 128 | case PhaseInputWire::BLUE: 129 | return power_entry.phase_blue; 130 | default: 131 | ESP_LOGE(TAG, "Unsupported phase input wire, this should never happen"); 132 | return -1; 133 | } 134 | } 135 | 136 | void CTClampConfig::update_from_reading(const SensorReading &sensor_reading) { 137 | if (this->power_sensor_) { 138 | ReadingPowerEntry power_entry = sensor_reading.power[this->input_port_]; 139 | int32_t raw_power = this->phase_->extract_power_for_phase(power_entry); 140 | float calibrated_power = this->get_calibrated_power(raw_power); 141 | this->power_sensor_->publish_state(calibrated_power); 142 | } 143 | if (this->current_sensor_) { 144 | uint16_t raw_current = sensor_reading.current[this->input_port_]; 145 | double raw_current_d = (double) raw_current; 146 | double scalar; 147 | if (is_mains_port(this->input_port_)) { 148 | scalar = 775.0 / 42624.0; 149 | } else { 150 | scalar = 775.0 / 170496.0; 151 | } 152 | this->current_sensor_->publish_state(raw_current_d * scalar); 153 | } 154 | } 155 | 156 | float CTClampConfig::get_calibrated_power(int32_t raw_power) const { 157 | float calibration = this->phase_->get_calibration(); 158 | 159 | float correction_factor = (this->input_port_ < 3) ? 5.5 : 22; 160 | 161 | return (raw_power * calibration) / correction_factor; 162 | } 163 | 164 | } // namespace emporia_vue 165 | } // namespace esphome 166 | -------------------------------------------------------------------------------- /.clang-tidy: -------------------------------------------------------------------------------- 1 | --- 2 | Checks: >- 3 | *, 4 | -abseil-*, 5 | -altera-*, 6 | -android-*, 7 | -boost-*, 8 | -bugprone-narrowing-conversions, 9 | -bugprone-signed-char-misuse, 10 | -cert-dcl50-cpp, 11 | -cert-err58-cpp, 12 | -cert-oop57-cpp, 13 | -cert-str34-c, 14 | -clang-analyzer-optin.cplusplus.UninitializedObject, 15 | -clang-analyzer-osx.*, 16 | -clang-diagnostic-delete-abstract-non-virtual-dtor, 17 | -clang-diagnostic-delete-non-abstract-non-virtual-dtor, 18 | -clang-diagnostic-shadow-field, 19 | -clang-diagnostic-unused-const-variable, 20 | -clang-diagnostic-unused-parameter, 21 | -concurrency-*, 22 | -cppcoreguidelines-avoid-c-arrays, 23 | -cppcoreguidelines-avoid-magic-numbers, 24 | -cppcoreguidelines-init-variables, 25 | -cppcoreguidelines-macro-usage, 26 | -cppcoreguidelines-narrowing-conversions, 27 | -cppcoreguidelines-non-private-member-variables-in-classes, 28 | -cppcoreguidelines-pro-bounds-array-to-pointer-decay, 29 | -cppcoreguidelines-pro-bounds-constant-array-index, 30 | -cppcoreguidelines-pro-bounds-pointer-arithmetic, 31 | -cppcoreguidelines-pro-type-const-cast, 32 | -cppcoreguidelines-pro-type-cstyle-cast, 33 | -cppcoreguidelines-pro-type-member-init, 34 | -cppcoreguidelines-pro-type-reinterpret-cast, 35 | -cppcoreguidelines-pro-type-static-cast-downcast, 36 | -cppcoreguidelines-pro-type-union-access, 37 | -cppcoreguidelines-pro-type-vararg, 38 | -cppcoreguidelines-special-member-functions, 39 | -fuchsia-multiple-inheritance, 40 | -fuchsia-overloaded-operator, 41 | -fuchsia-statically-constructed-objects, 42 | -fuchsia-default-arguments-declarations, 43 | -fuchsia-default-arguments-calls, 44 | -google-build-using-namespace, 45 | -google-explicit-constructor, 46 | -google-readability-braces-around-statements, 47 | -google-readability-casting, 48 | -google-readability-namespace-comments, 49 | -google-readability-todo, 50 | -google-runtime-references, 51 | -hicpp-*, 52 | -llvm-else-after-return, 53 | -llvm-header-guard, 54 | -llvm-include-order, 55 | -llvm-qualified-auto, 56 | -llvmlibc-*, 57 | -misc-non-private-member-variables-in-classes, 58 | -misc-no-recursion, 59 | -misc-unused-parameters, 60 | -modernize-avoid-c-arrays, 61 | -modernize-avoid-bind, 62 | -modernize-concat-nested-namespaces, 63 | -modernize-return-braced-init-list, 64 | -modernize-use-auto, 65 | -modernize-use-default-member-init, 66 | -modernize-use-equals-default, 67 | -modernize-use-trailing-return-type, 68 | -modernize-use-nodiscard, 69 | -mpi-*, 70 | -objc-*, 71 | -readability-convert-member-functions-to-static, 72 | -readability-else-after-return, 73 | -readability-function-cognitive-complexity, 74 | -readability-implicit-bool-conversion, 75 | -readability-isolate-declaration, 76 | -readability-magic-numbers, 77 | -readability-make-member-function-const, 78 | -readability-redundant-string-init, 79 | -readability-uppercase-literal-suffix, 80 | -readability-use-anyofallof, 81 | WarningsAsErrors: '*' 82 | AnalyzeTemporaryDtors: false 83 | FormatStyle: google 84 | CheckOptions: 85 | - key: google-readability-braces-around-statements.ShortStatementLines 86 | value: '1' 87 | - key: google-readability-function-size.StatementThreshold 88 | value: '800' 89 | - key: google-runtime-int.TypeSuffix 90 | value: '_t' 91 | - key: llvm-namespace-comment.ShortNamespaceLines 92 | value: '10' 93 | - key: llvm-namespace-comment.SpacesBeforeComments 94 | value: '2' 95 | - key: modernize-loop-convert.MaxCopySize 96 | value: '16' 97 | - key: modernize-loop-convert.MinConfidence 98 | value: reasonable 99 | - key: modernize-loop-convert.NamingStyle 100 | value: CamelCase 101 | - key: modernize-pass-by-value.IncludeStyle 102 | value: llvm 103 | - key: modernize-replace-auto-ptr.IncludeStyle 104 | value: llvm 105 | - key: modernize-use-nullptr.NullMacros 106 | value: 'NULL' 107 | - key: modernize-make-unique.MakeSmartPtrFunction 108 | value: 'make_unique' 109 | - key: modernize-make-unique.MakeSmartPtrFunctionHeader 110 | value: 'esphome/core/helpers.h' 111 | - key: readability-braces-around-statements.ShortStatementLines 112 | value: 2 113 | - key: readability-identifier-naming.LocalVariableCase 114 | value: 'lower_case' 115 | - key: readability-identifier-naming.ClassCase 116 | value: 'CamelCase' 117 | - key: readability-identifier-naming.StructCase 118 | value: 'CamelCase' 119 | - key: readability-identifier-naming.EnumCase 120 | value: 'CamelCase' 121 | - key: readability-identifier-naming.EnumConstantCase 122 | value: 'UPPER_CASE' 123 | - key: readability-identifier-naming.StaticConstantCase 124 | value: 'UPPER_CASE' 125 | - key: readability-identifier-naming.StaticVariableCase 126 | value: 'lower_case' 127 | - key: readability-identifier-naming.GlobalConstantCase 128 | value: 'UPPER_CASE' 129 | - key: readability-identifier-naming.ParameterCase 130 | value: 'lower_case' 131 | - key: readability-identifier-naming.PrivateMemberCase 132 | value: 'lower_case' 133 | - key: readability-identifier-naming.PrivateMemberSuffix 134 | value: '_' 135 | - key: readability-identifier-naming.PrivateMethodCase 136 | value: 'lower_case' 137 | - key: readability-identifier-naming.PrivateMethodSuffix 138 | value: '_' 139 | - key: readability-identifier-naming.ClassMemberCase 140 | value: 'lower_case' 141 | - key: readability-identifier-naming.ClassMemberCase 142 | value: 'lower_case' 143 | - key: readability-identifier-naming.ProtectedMemberCase 144 | value: 'lower_case' 145 | - key: readability-identifier-naming.ProtectedMemberSuffix 146 | value: '_' 147 | - key: readability-identifier-naming.FunctionCase 148 | value: 'lower_case' 149 | - key: readability-identifier-naming.ClassMethodCase 150 | value: 'lower_case' 151 | - key: readability-identifier-naming.ProtectedMethodCase 152 | value: 'lower_case' 153 | - key: readability-identifier-naming.ProtectedMethodSuffix 154 | value: '_' 155 | - key: readability-identifier-naming.VirtualMethodCase 156 | value: 'lower_case' 157 | - key: readability-identifier-naming.VirtualMethodSuffix 158 | value: '' 159 | - key: readability-qualified-auto.AddConstToQualified 160 | value: 0 161 | -------------------------------------------------------------------------------- /esphome/components/emporia_vue/sensor.py: -------------------------------------------------------------------------------- 1 | from esphome.components import sensor, i2c 2 | from esphome import automation 3 | import esphome.config_validation as cv 4 | import esphome.codegen as cg 5 | from esphome.const import ( 6 | CONF_CALIBRATION, 7 | CONF_CURRENT, 8 | CONF_ID, 9 | CONF_INPUT, 10 | CONF_POWER, 11 | CONF_TRIGGER_ID, 12 | CONF_VOLTAGE, 13 | CONF_FREQUENCY, 14 | CONF_PHASE_ANGLE, 15 | DEVICE_CLASS_CURRENT, 16 | DEVICE_CLASS_FREQUENCY, 17 | DEVICE_CLASS_POWER, 18 | DEVICE_CLASS_VOLTAGE, 19 | STATE_CLASS_MEASUREMENT, 20 | UNIT_AMPERE, 21 | UNIT_WATT, 22 | UNIT_VOLT, 23 | UNIT_HERTZ, 24 | UNIT_DEGREES, 25 | ) 26 | 27 | CONF_CT_CLAMPS = "ct_clamps" 28 | CONF_PHASES = "phases" 29 | CONF_PHASE_ID = "phase_id" 30 | CONF_VARIANT = "variant" 31 | 32 | CONF_ON_UPDATE = "on_update" 33 | 34 | CODEOWNERS = ["@flaviut", "@Maelstrom96", "@krconv"] 35 | ESP_PLATFORMS = ["esp-idf"] 36 | DEPENDENCIES = ["i2c"] 37 | AUTO_LOAD = ["sensor"] 38 | 39 | emporia_vue_ns = cg.esphome_ns.namespace("emporia_vue") 40 | EmporiaVueComponent = emporia_vue_ns.class_( 41 | "EmporiaVueComponent", cg.PollingComponent, i2c.I2CDevice 42 | ) 43 | PhaseConfig = emporia_vue_ns.class_("PhaseConfig") 44 | CTClampConfig = emporia_vue_ns.class_("CTClampConfig") 45 | 46 | # Trigger for after statistics sensors are updated 47 | EmporiaVueUpdateTrigger = emporia_vue_ns.class_( 48 | "EmporiaVueUpdateTrigger", automation.Trigger.template() 49 | ) 50 | 51 | 52 | PhaseInputWire = emporia_vue_ns.enum("PhaseInputWire") 53 | PHASE_INPUT = { 54 | "BLACK": PhaseInputWire.BLACK, 55 | "RED": PhaseInputWire.RED, 56 | "BLUE": PhaseInputWire.BLUE, 57 | } 58 | 59 | CTInputPort = emporia_vue_ns.enum("CTInputPort") 60 | CT_INPUT = { 61 | "A": CTInputPort.A, 62 | "B": CTInputPort.B, 63 | "C": CTInputPort.C, 64 | "1": CTInputPort.ONE, 65 | "2": CTInputPort.TWO, 66 | "3": CTInputPort.THREE, 67 | "4": CTInputPort.FOUR, 68 | "5": CTInputPort.FIVE, 69 | "6": CTInputPort.SIX, 70 | "7": CTInputPort.SEVEN, 71 | "8": CTInputPort.EIGHT, 72 | "9": CTInputPort.NINE, 73 | "10": CTInputPort.TEN, 74 | "11": CTInputPort.ELEVEN, 75 | "12": CTInputPort.TWELVE, 76 | "13": CTInputPort.THIRTEEN, 77 | "14": CTInputPort.FOURTEEN, 78 | "15": CTInputPort.FIFTEEN, 79 | "16": CTInputPort.SIXTEEN, 80 | } 81 | 82 | SCHEMA_CT_CLAMP = { 83 | cv.GenerateID(): cv.declare_id(CTClampConfig), 84 | cv.Required(CONF_PHASE_ID): cv.use_id(PhaseConfig), 85 | cv.Required(CONF_INPUT): cv.enum(CT_INPUT), 86 | cv.Optional(CONF_POWER): sensor.sensor_schema( 87 | unit_of_measurement=UNIT_WATT, 88 | device_class=DEVICE_CLASS_POWER, 89 | state_class=STATE_CLASS_MEASUREMENT, 90 | accuracy_decimals=1, 91 | ), 92 | cv.Optional(CONF_CURRENT): sensor.sensor_schema( 93 | unit_of_measurement=UNIT_AMPERE, 94 | device_class=DEVICE_CLASS_CURRENT, 95 | state_class=STATE_CLASS_MEASUREMENT, 96 | accuracy_decimals=2, 97 | ), 98 | } 99 | 100 | 101 | def validate_phases(val): 102 | base_validated = cv.Schema( 103 | cv.ensure_list( 104 | { 105 | cv.Required(CONF_ID): cv.declare_id(PhaseConfig), 106 | cv.Required(CONF_INPUT): cv.enum(PHASE_INPUT), 107 | cv.Optional(CONF_CALIBRATION, default=0.022): cv.zero_to_one_float, 108 | cv.Optional(CONF_VOLTAGE): sensor.sensor_schema( 109 | unit_of_measurement=UNIT_VOLT, 110 | device_class=DEVICE_CLASS_VOLTAGE, 111 | state_class=STATE_CLASS_MEASUREMENT, 112 | accuracy_decimals=1, 113 | ), 114 | cv.Optional(CONF_FREQUENCY): sensor.sensor_schema( 115 | unit_of_measurement=UNIT_HERTZ, 116 | device_class=DEVICE_CLASS_FREQUENCY, 117 | state_class=STATE_CLASS_MEASUREMENT, 118 | accuracy_decimals=1, 119 | ), 120 | cv.Optional(CONF_PHASE_ANGLE): sensor.sensor_schema( 121 | unit_of_measurement=UNIT_DEGREES, 122 | state_class=STATE_CLASS_MEASUREMENT, 123 | accuracy_decimals=0, 124 | ), 125 | } 126 | ) 127 | )(val) 128 | 129 | if len(base_validated) > 3: 130 | raise cv.Invalid("No more than 3 phases are supported") 131 | 132 | inputs = [phase[CONF_INPUT] for phase in base_validated] 133 | if len(inputs) != len(set(inputs)): 134 | raise cv.Invalid("Only one entry per input color is allowed") 135 | 136 | for i, phase in enumerate(base_validated): 137 | input_wire = phase[CONF_INPUT] 138 | if input_wire == "BLACK": 139 | if CONF_PHASE_ANGLE in phase: 140 | raise cv.Invalid( 141 | "Phase angle is not supported for the black wire, only for the " 142 | "red and blue wires", 143 | path=[i, CONF_PHASE_ANGLE], 144 | ) 145 | elif input_wire in {"RED", "BLUE"}: 146 | if CONF_FREQUENCY in phase: 147 | raise cv.Invalid( 148 | "Frequency is not supported for the red and blue wires, only for " 149 | "the black wire", 150 | path=[i, CONF_FREQUENCY], 151 | ) 152 | 153 | return base_validated 154 | 155 | 156 | CONFIG_SCHEMA = cv.All( 157 | cv.Schema( 158 | { 159 | cv.GenerateID(): cv.declare_id(EmporiaVueComponent), 160 | cv.Required(CONF_PHASES): validate_phases, 161 | cv.Required(CONF_CT_CLAMPS): cv.ensure_list(SCHEMA_CT_CLAMP), 162 | cv.Optional(CONF_VARIANT, default="vue2"): cv.one_of("vue2", "vue3", lower=True), 163 | cv.Optional(CONF_ON_UPDATE): automation.validate_automation( 164 | { 165 | cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id( 166 | EmporiaVueUpdateTrigger 167 | ), 168 | } 169 | ), 170 | }, 171 | ) 172 | .extend(cv.polling_component_schema("0ms")) 173 | .extend(i2c.i2c_device_schema(0x64)), 174 | cv.only_with_esp_idf, 175 | cv.only_on_esp32, 176 | ) 177 | 178 | 179 | async def to_code(config): 180 | var = cg.new_Pvariable(config[CONF_ID]) 181 | await cg.register_component(var, config) 182 | await i2c.register_i2c_device(var, config) 183 | 184 | if config.get(CONF_VARIANT, "vue2") == "vue3": 185 | cg.add_define("EMPORIA_VUE_VARIANT_VUE3") 186 | else: 187 | cg.add_define("EMPORIA_VUE_VARIANT_VUE2") 188 | 189 | phases = [] 190 | for phase_config in config[CONF_PHASES]: 191 | phase_var = cg.new_Pvariable(phase_config[CONF_ID], PhaseConfig()) 192 | cg.add(phase_var.set_input_wire(phase_config[CONF_INPUT])) 193 | cg.add(phase_var.set_calibration(phase_config[CONF_CALIBRATION])) 194 | 195 | if CONF_VOLTAGE in phase_config: 196 | voltage_sensor = await sensor.new_sensor(phase_config[CONF_VOLTAGE]) 197 | cg.add(phase_var.set_voltage_sensor(voltage_sensor)) 198 | 199 | if CONF_FREQUENCY in phase_config: 200 | frequency_sensor = await sensor.new_sensor(phase_config[CONF_FREQUENCY]) 201 | cg.add(phase_var.set_frequency_sensor(frequency_sensor)) 202 | 203 | if CONF_PHASE_ANGLE in phase_config: 204 | phase_angle_sensor = await sensor.new_sensor(phase_config[CONF_PHASE_ANGLE]) 205 | cg.add(phase_var.set_phase_angle_sensor(phase_angle_sensor)) 206 | 207 | phases.append(phase_var) 208 | cg.add(var.set_phases(phases)) 209 | 210 | ct_clamps = [] 211 | for ct_config in config[CONF_CT_CLAMPS]: 212 | ct_clamp_var = cg.new_Pvariable(ct_config[CONF_ID], CTClampConfig()) 213 | phase_var = await cg.get_variable(ct_config[CONF_PHASE_ID]) 214 | cg.add(ct_clamp_var.set_phase(phase_var)) 215 | cg.add(ct_clamp_var.set_input_port(ct_config[CONF_INPUT])) 216 | 217 | if CONF_POWER in ct_config: 218 | power_sensor = await sensor.new_sensor(ct_config[CONF_POWER]) 219 | cg.add(ct_clamp_var.set_power_sensor(power_sensor)) 220 | 221 | if CONF_CURRENT in ct_config: 222 | current_sensor = await sensor.new_sensor(ct_config[CONF_CURRENT]) 223 | cg.add(ct_clamp_var.set_current_sensor(current_sensor)) 224 | 225 | ct_clamps.append(ct_clamp_var) 226 | cg.add(var.set_ct_clamps(ct_clamps)) 227 | 228 | for trigger_conf in config.get(CONF_ON_UPDATE, []): 229 | trigger = cg.new_Pvariable(trigger_conf[CONF_TRIGGER_ID], var) 230 | await automation.build_automation(trigger, [], trigger_conf ) 231 | -------------------------------------------------------------------------------- /script/clang-tidy: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from helpers import ( 4 | print_error_for_file, 5 | get_output, 6 | filter_grep, 7 | build_all_include, 8 | temp_header_file, 9 | git_ls_files, 10 | filter_changed, 11 | load_idedata, 12 | root_path, 13 | basepath, 14 | ) 15 | import argparse 16 | import click 17 | import colorama 18 | import multiprocessing 19 | import os 20 | import queue 21 | import re 22 | import shutil 23 | import subprocess 24 | import sys 25 | import tempfile 26 | import threading 27 | 28 | 29 | def clang_options(idedata): 30 | cmd = [] 31 | 32 | # extract target architecture from triplet in g++ filename 33 | triplet = os.path.basename(idedata["cxx_path"])[:-4] 34 | if triplet.startswith("xtensa-"): 35 | # clang doesn't support Xtensa (yet?), so compile in 32-bit mode and pretend we're the Xtensa compiler 36 | cmd.append("-m32") 37 | cmd.append("-D__XTENSA__") 38 | else: 39 | cmd.append(f"--target={triplet}") 40 | 41 | # set flags 42 | cmd.extend( 43 | [ 44 | # disable built-in include directories from the host 45 | "-nostdinc", 46 | "-nostdinc++", 47 | # replace pgmspace.h, as it uses GNU extensions clang doesn't support 48 | # https://github.com/earlephilhower/newlib-xtensa/pull/18 49 | "-D_PGMSPACE_H_", 50 | "-Dpgm_read_byte(s)=(*(const uint8_t *)(s))", 51 | "-Dpgm_read_byte_near(s)=(*(const uint8_t *)(s))", 52 | "-Dpgm_read_word(s)=(*(const uint16_t *)(s))", 53 | "-Dpgm_read_dword(s)=(*(const uint32_t *)(s))", 54 | "-DPROGMEM=", 55 | "-DPGM_P=const char *", 56 | "-DPSTR(s)=(s)", 57 | # this next one is also needed with upstream pgmspace.h 58 | # suppress warning about identifier naming in expansion of this macro 59 | "-DPSTRN(s, n)=(s)", 60 | # suppress warning about attribute cannot be applied to type 61 | # https://github.com/esp8266/Arduino/pull/8258 62 | "-Ddeprecated(x)=", 63 | # allow to condition code on the presence of clang-tidy 64 | "-DCLANG_TIDY", 65 | # (esp-idf) Disable this header because they use asm with registers clang-tidy doesn't know 66 | "-D__XTENSA_API_H__", 67 | # (esp-idf) Fix __once_callable in some libstdc++ headers 68 | "-D_GLIBCXX_HAVE_TLS", 69 | ] 70 | ) 71 | 72 | # copy compiler flags, except those clang doesn't understand. 73 | cmd.extend( 74 | flag 75 | for flag in idedata["cxx_flags"].split(" ") 76 | if flag 77 | not in ( 78 | "-free", 79 | "-fipa-pta", 80 | "-fstrict-volatile-bitfields", 81 | "-mlongcalls", 82 | "-mtext-section-literals", 83 | "-mfix-esp32-psram-cache-issue", 84 | "-mfix-esp32-psram-cache-strategy=memw", 85 | "-fno-tree-switch-conversion", 86 | ) 87 | ) 88 | 89 | # defines 90 | cmd.extend(f"-D{define}" for define in idedata["defines"]) 91 | 92 | # add toolchain include directories using -isystem to suppress their errors 93 | # idedata contains include directories for all toolchains of this platform, only use those from the one in use 94 | toolchain_dir = os.path.normpath(f"{idedata['cxx_path']}/../../") 95 | for directory in idedata["includes"]["toolchain"]: 96 | if directory.startswith(toolchain_dir): 97 | cmd.extend(["-isystem", directory]) 98 | 99 | # add library include directories using -isystem to suppress their errors 100 | for directory in sorted(set(idedata["includes"]["build"])): 101 | # skip our own directories, we add those later 102 | if not directory.startswith(f"{root_path}/") or directory.startswith( 103 | f"{root_path}/.pio/" 104 | ): 105 | cmd.extend(["-isystem", directory]) 106 | 107 | # add the esphome include directory using -I 108 | cmd.extend(["-I", root_path]) 109 | 110 | return cmd 111 | 112 | 113 | def run_tidy(args, options, tmpdir, queue, lock, failed_files): 114 | while True: 115 | path = queue.get() 116 | invocation = ["clang-tidy-11"] 117 | 118 | if tmpdir is not None: 119 | invocation.append("--export-fixes") 120 | # Get a temporary file. We immediately close the handle so clang-tidy can 121 | # overwrite it. 122 | (handle, name) = tempfile.mkstemp(suffix=".yaml", dir=tmpdir) 123 | os.close(handle) 124 | invocation.append(name) 125 | 126 | if args.quiet: 127 | invocation.append("--quiet") 128 | 129 | if sys.stdout.isatty(): 130 | invocation.append("--use-color") 131 | 132 | invocation.append(f"--header-filter={os.path.abspath(basepath)}/.*") 133 | invocation.append(os.path.abspath(path)) 134 | invocation.append("--") 135 | invocation.extend(options) 136 | 137 | proc = subprocess.run(invocation, capture_output=True, encoding="utf-8") 138 | if proc.returncode != 0: 139 | with lock: 140 | print_error_for_file(path, proc.stdout) 141 | failed_files.append(path) 142 | queue.task_done() 143 | 144 | 145 | def progress_bar_show(value): 146 | if value is None: 147 | return "" 148 | 149 | 150 | def split_list(a, n): 151 | k, m = divmod(len(a), n) 152 | return [a[i * k + min(i, m) : (i + 1) * k + min(i + 1, m)] for i in range(n)] 153 | 154 | 155 | def main(): 156 | colorama.init() 157 | 158 | parser = argparse.ArgumentParser() 159 | parser.add_argument( 160 | "-j", 161 | "--jobs", 162 | type=int, 163 | default=multiprocessing.cpu_count(), 164 | help="number of tidy instances to be run in parallel.", 165 | ) 166 | parser.add_argument( 167 | "-e", 168 | "--environment", 169 | default="esp32-arduino-tidy", 170 | help="the PlatformIO environment to use (as defined in platformio.ini)", 171 | ) 172 | parser.add_argument( 173 | "files", nargs="*", default=[], help="files to be processed (regex on path)" 174 | ) 175 | parser.add_argument("--fix", action="store_true", help="apply fix-its") 176 | parser.add_argument( 177 | "-q", "--quiet", action="store_false", help="run clang-tidy in quiet mode" 178 | ) 179 | parser.add_argument( 180 | "-c", "--changed", action="store_true", help="only run on changed files" 181 | ) 182 | parser.add_argument("-g", "--grep", help="only run on files containing value") 183 | parser.add_argument( 184 | "--split-num", type=int, help="split the files into X jobs.", default=None 185 | ) 186 | parser.add_argument( 187 | "--split-at", type=int, help="which split is this? starts at 1", default=None 188 | ) 189 | parser.add_argument( 190 | "--all-headers", 191 | action="store_true", 192 | help="create a dummy file that checks all headers", 193 | ) 194 | args = parser.parse_args() 195 | 196 | try: 197 | get_output("clang-tidy-11", "-version") 198 | except: 199 | print( 200 | """ 201 | Oops. It looks like clang-tidy-11 is not installed. 202 | 203 | Please check you can run "clang-tidy-11 -version" in your terminal and install 204 | clang-tidy (v11) if necessary. 205 | 206 | Note you can also upload your code as a pull request on GitHub and see the CI check 207 | output to apply clang-tidy. 208 | """ 209 | ) 210 | return 1 211 | 212 | idedata = load_idedata(args.environment) 213 | options = clang_options(idedata) 214 | 215 | files = [] 216 | for path in git_ls_files(["*.cpp"]): 217 | files.append(os.path.relpath(path, os.getcwd())) 218 | 219 | if args.files: 220 | # Match against files specified on command-line 221 | file_name_re = re.compile("|".join(args.files)) 222 | files = [p for p in files if file_name_re.search(p)] 223 | 224 | if args.changed: 225 | files = filter_changed(files) 226 | 227 | if args.grep: 228 | files = filter_grep(files, args.grep) 229 | 230 | files.sort() 231 | 232 | if args.split_num: 233 | files = split_list(files, args.split_num)[args.split_at - 1] 234 | 235 | if args.all_headers and args.split_at in (None, 1): 236 | build_all_include() 237 | files.insert(0, temp_header_file) 238 | 239 | tmpdir = None 240 | if args.fix: 241 | tmpdir = tempfile.mkdtemp() 242 | 243 | failed_files = [] 244 | try: 245 | task_queue = queue.Queue(args.jobs) 246 | lock = threading.Lock() 247 | for _ in range(args.jobs): 248 | t = threading.Thread( 249 | target=run_tidy, 250 | args=(args, options, tmpdir, task_queue, lock, failed_files), 251 | ) 252 | t.daemon = True 253 | t.start() 254 | 255 | # Fill the queue with files. 256 | with click.progressbar( 257 | files, width=30, file=sys.stderr, item_show_func=progress_bar_show 258 | ) as bar: 259 | for name in bar: 260 | task_queue.put(name) 261 | 262 | # Wait for all threads to be done. 263 | task_queue.join() 264 | 265 | except KeyboardInterrupt: 266 | print() 267 | print("Ctrl-C detected, goodbye.") 268 | if tmpdir: 269 | shutil.rmtree(tmpdir) 270 | os.kill(0, 9) 271 | 272 | if args.fix and failed_files: 273 | print("Applying fixes ...") 274 | try: 275 | subprocess.call(["clang-apply-replacements-11", tmpdir]) 276 | except: 277 | print("Error applying fixes.\n", file=sys.stderr) 278 | raise 279 | 280 | sys.exit(len(failed_files)) 281 | 282 | 283 | if __name__ == "__main__": 284 | main() 285 | -------------------------------------------------------------------------------- /script/ci-custom.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from helpers import styled, print_error_for_file, git_ls_files, filter_changed 4 | import argparse 5 | import codecs 6 | import collections 7 | import colorama 8 | import fnmatch 9 | import functools 10 | import os.path 11 | import re 12 | import sys 13 | import time 14 | 15 | sys.path.append(os.path.dirname(__file__)) 16 | 17 | 18 | def find_all(a_str, sub): 19 | if not a_str.find(sub): 20 | # Optimization: If str is not in whole text, then do not try 21 | # on each line 22 | return 23 | for i, line in enumerate(a_str.split("\n")): 24 | column = 0 25 | while True: 26 | column = line.find(sub, column) 27 | if column == -1: 28 | break 29 | yield i, column 30 | column += len(sub) 31 | 32 | 33 | colorama.init() 34 | 35 | parser = argparse.ArgumentParser() 36 | parser.add_argument( 37 | "files", nargs="*", default=[], help="files to be processed (regex on path)" 38 | ) 39 | parser.add_argument( 40 | "-c", "--changed", action="store_true", help="Only run on changed files" 41 | ) 42 | parser.add_argument( 43 | "--print-slowest", action="store_true", help="Print the slowest checks" 44 | ) 45 | args = parser.parse_args() 46 | 47 | EXECUTABLE_BIT = git_ls_files() 48 | files = list(EXECUTABLE_BIT.keys()) 49 | # Match against re 50 | file_name_re = re.compile("|".join(args.files)) 51 | files = [p for p in files if file_name_re.search(p)] 52 | 53 | if args.changed: 54 | files = filter_changed(files) 55 | 56 | files.sort() 57 | 58 | file_types = ( 59 | ".h", 60 | ".c", 61 | ".cpp", 62 | ".tcc", 63 | ".yaml", 64 | ".yml", 65 | ".ini", 66 | ".txt", 67 | ".ico", 68 | ".svg", 69 | ".py", 70 | ".html", 71 | ".js", 72 | ".md", 73 | ".sh", 74 | ".css", 75 | ".proto", 76 | ".conf", 77 | ".cfg", 78 | ".woff", 79 | ".woff2", 80 | "", 81 | ) 82 | cpp_include = ("*.h", "*.c", "*.cpp", "*.tcc") 83 | ignore_types = (".ico", ".woff", ".woff2", "") 84 | 85 | LINT_FILE_CHECKS = [] 86 | LINT_CONTENT_CHECKS = [] 87 | LINT_POST_CHECKS = [] 88 | 89 | 90 | def run_check(lint_obj, fname, *args): 91 | include = lint_obj["include"] 92 | exclude = lint_obj["exclude"] 93 | func = lint_obj["func"] 94 | if include is not None: 95 | for incl in include: 96 | if fnmatch.fnmatch(fname, incl): 97 | break 98 | else: 99 | return None 100 | for excl in exclude: 101 | if fnmatch.fnmatch(fname, excl): 102 | return None 103 | return func(*args) 104 | 105 | 106 | def run_checks(lints, fname, *args): 107 | for lint in lints: 108 | start = time.process_time() 109 | try: 110 | add_errors(fname, run_check(lint, fname, *args)) 111 | except Exception: 112 | print(f"Check {lint['func'].__name__} on file {fname} failed:") 113 | raise 114 | duration = time.process_time() - start 115 | lint.setdefault("durations", []).append(duration) 116 | 117 | 118 | def _add_check(checks, func, include=None, exclude=None): 119 | checks.append( 120 | { 121 | "include": include, 122 | "exclude": exclude or [], 123 | "func": func, 124 | } 125 | ) 126 | 127 | 128 | def lint_file_check(**kwargs): 129 | def decorator(func): 130 | _add_check(LINT_FILE_CHECKS, func, **kwargs) 131 | return func 132 | 133 | return decorator 134 | 135 | 136 | def lint_content_check(**kwargs): 137 | def decorator(func): 138 | _add_check(LINT_CONTENT_CHECKS, func, **kwargs) 139 | return func 140 | 141 | return decorator 142 | 143 | 144 | def lint_post_check(func): 145 | _add_check(LINT_POST_CHECKS, func) 146 | return func 147 | 148 | 149 | def lint_re_check(regex, **kwargs): 150 | flags = kwargs.pop("flags", re.MULTILINE) 151 | prog = re.compile(regex, flags) 152 | decor = lint_content_check(**kwargs) 153 | 154 | def decorator(func): 155 | @functools.wraps(func) 156 | def new_func(fname, content): 157 | errors = [] 158 | for match in prog.finditer(content): 159 | if "NOLINT" in match.group(0): 160 | continue 161 | lineno = content.count("\n", 0, match.start()) + 1 162 | substr = content[: match.start()] 163 | col = len(substr) - substr.rfind("\n") 164 | err = func(fname, match) 165 | if err is None: 166 | continue 167 | errors.append((lineno, col + 1, err)) 168 | return errors 169 | 170 | return decor(new_func) 171 | 172 | return decorator 173 | 174 | 175 | def lint_content_find_check(find, only_first=False, **kwargs): 176 | decor = lint_content_check(**kwargs) 177 | 178 | def decorator(func): 179 | @functools.wraps(func) 180 | def new_func(fname, content): 181 | find_ = find 182 | if callable(find): 183 | find_ = find(fname, content) 184 | errors = [] 185 | for line, col in find_all(content, find_): 186 | err = func(fname) 187 | errors.append((line + 1, col + 1, err)) 188 | if only_first: 189 | break 190 | return errors 191 | 192 | return decor(new_func) 193 | 194 | return decorator 195 | 196 | 197 | @lint_file_check(include=["*.ino"]) 198 | def lint_ino(fname): 199 | return "This file extension (.ino) is not allowed. Please use either .cpp or .h" 200 | 201 | 202 | @lint_file_check( 203 | exclude=[f"*{f}" for f in file_types] 204 | + [ 205 | ".clang-*", 206 | ".dockerignore", 207 | ".editorconfig", 208 | "*.gitignore", 209 | "LICENSE", 210 | "pylintrc", 211 | "MANIFEST.in", 212 | "docker/Dockerfile*", 213 | "docker/rootfs/*", 214 | "script/*", 215 | ] 216 | ) 217 | def lint_ext_check(fname): 218 | return ( 219 | "This file extension is not a registered file type. If this is an error, please " 220 | "update the script/ci-custom.py script." 221 | ) 222 | 223 | 224 | @lint_file_check( 225 | exclude=[ 226 | "**.sh", 227 | "docker/ha-addon-rootfs/**", 228 | "docker/*.py", 229 | "script/*", 230 | "setup.py", 231 | ] 232 | ) 233 | def lint_executable_bit(fname): 234 | ex = EXECUTABLE_BIT[fname] 235 | if ex != 100644: 236 | return ( 237 | "File has invalid executable bit {}. If running from a windows machine please " 238 | "see disabling executable bit in git.".format(ex) 239 | ) 240 | return None 241 | 242 | 243 | @lint_content_find_check( 244 | "\t", 245 | only_first=True, 246 | exclude=[ 247 | "esphome/dashboard/static/ace.js", 248 | "esphome/dashboard/static/ext-searchbox.js", 249 | ], 250 | ) 251 | def lint_tabs(fname): 252 | return "File contains tab character. Please convert tabs to spaces." 253 | 254 | 255 | @lint_content_find_check("\r", only_first=True) 256 | def lint_newline(fname): 257 | return "File contains Windows newline. Please set your editor to Unix newline mode." 258 | 259 | 260 | @lint_content_check(exclude=["*.svg"]) 261 | def lint_end_newline(fname, content): 262 | if content and not content.endswith("\n"): 263 | return "File does not end with a newline, please add an empty line at the end of the file." 264 | return None 265 | 266 | 267 | CPP_RE_EOL = r"\s*?(?://.*?)?$" 268 | 269 | 270 | def highlight(s): 271 | return f"\033[36m{s}\033[0m" 272 | 273 | 274 | @lint_re_check( 275 | r"^#define\s+([a-zA-Z0-9_]+)\s+([0-9bx]+)" + CPP_RE_EOL, 276 | include=cpp_include, 277 | exclude=[ 278 | "esphome/core/log.h", 279 | "esphome/components/socket/headers.h", 280 | "esphome/core/defines.h", 281 | ], 282 | ) 283 | def lint_no_defines(fname, match): 284 | s = highlight(f"static const uint8_t {match.group(1)} = {match.group(2)};") 285 | return ( 286 | "#define macros for integer constants are not allowed, please use " 287 | "{} style instead (replace uint8_t with the appropriate " 288 | "datatype). See also Google style guide.".format(s) 289 | ) 290 | 291 | 292 | @lint_re_check(r"^\s*delay\((\d+)\);" + CPP_RE_EOL, include=cpp_include) 293 | def lint_no_long_delays(fname, match): 294 | duration_ms = int(match.group(1)) 295 | if duration_ms < 50: 296 | return None 297 | return ( 298 | "{} - long calls to delay() are not allowed in ESPHome because everything executes " 299 | "in one thread. Calling delay() will block the main thread and slow down ESPHome.\n" 300 | "If there's no way to work around the delay() and it doesn't execute often, please add " 301 | "a '// NOLINT' comment to the line." 302 | "".format(highlight(match.group(0).strip())) 303 | ) 304 | 305 | 306 | @lint_content_check(include=["esphome/const.py"]) 307 | def lint_const_ordered(fname, content): 308 | """Lint that value in const.py are ordered. 309 | 310 | Reason: Otherwise people add it to the end, and then that results in merge conflicts. 311 | """ 312 | lines = content.splitlines() 313 | errors = [] 314 | for start in ["CONF_", "ICON_", "UNIT_"]: 315 | matching = [ 316 | (i + 1, line) for i, line in enumerate(lines) if line.startswith(start) 317 | ] 318 | ordered = list(sorted(matching, key=lambda x: x[1].replace("_", " "))) 319 | ordered = [(mi, ol) for (mi, _), (_, ol) in zip(matching, ordered)] 320 | for (mi, ml), (oi, ol) in zip(matching, ordered): 321 | if ml == ol: 322 | continue 323 | target = next(i for i, l in ordered if l == ml) 324 | target_text = next(l for i, l in matching if target == i) 325 | errors.append( 326 | ( 327 | mi, 328 | 1, 329 | f"Constant {highlight(ml)} is not ordered, please make sure all " 330 | f"constants are ordered. See line {mi} (should go to line {target}, " 331 | f"{target_text})", 332 | ) 333 | ) 334 | return errors 335 | 336 | 337 | @lint_re_check(r'^\s*CONF_([A-Z_0-9a-z]+)\s+=\s+[\'"](.*?)[\'"]\s*?$', include=["*.py"]) 338 | def lint_conf_matches(fname, match): 339 | const = match.group(1) 340 | value = match.group(2) 341 | const_norm = const.lower() 342 | value_norm = value.replace(".", "_") 343 | if const_norm == value_norm: 344 | return None 345 | return ( 346 | "Constant {} does not match value {}! Please make sure the constant's name matches its " 347 | "value!" 348 | "".format(highlight("CONF_" + const), highlight(value)) 349 | ) 350 | 351 | 352 | CONF_RE = r'^(CONF_[a-zA-Z0-9_]+)\s*=\s*[\'"].*?[\'"]\s*?$' 353 | with codecs.open("esphome/const.py", "r", encoding="utf-8") as f_handle: 354 | constants_content = f_handle.read() 355 | CONSTANTS = [m.group(1) for m in re.finditer(CONF_RE, constants_content, re.MULTILINE)] 356 | 357 | CONSTANTS_USES = collections.defaultdict(list) 358 | 359 | 360 | @lint_re_check(CONF_RE, include=["*.py"], exclude=["esphome/const.py"]) 361 | def lint_conf_from_const_py(fname, match): 362 | name = match.group(1) 363 | if name not in CONSTANTS: 364 | CONSTANTS_USES[name].append(fname) 365 | return None 366 | return ( 367 | "Constant {} has already been defined in const.py - please import the constant from " 368 | "const.py directly.".format(highlight(name)) 369 | ) 370 | 371 | 372 | RAW_PIN_ACCESS_RE = ( 373 | r"^\s(pinMode|digitalWrite|digitalRead)\((.*)->get_pin\(\),\s*([^)]+).*\)" 374 | ) 375 | 376 | 377 | @lint_re_check(RAW_PIN_ACCESS_RE, include=cpp_include) 378 | def lint_no_raw_pin_access(fname, match): 379 | func = match.group(1) 380 | pin = match.group(2) 381 | mode = match.group(3) 382 | new_func = { 383 | "pinMode": "pin_mode", 384 | "digitalWrite": "digital_write", 385 | "digitalRead": "digital_read", 386 | }[func] 387 | new_code = highlight(f"{pin}->{new_func}({mode})") 388 | return f"Don't use raw {func} calls. Instead, use the `->{new_func}` function: {new_code}" 389 | 390 | 391 | # Functions from Arduino framework that are forbidden to use directly 392 | ARDUINO_FORBIDDEN = [ 393 | "digitalWrite", 394 | "digitalRead", 395 | "pinMode", 396 | "shiftOut", 397 | "shiftIn", 398 | "radians", 399 | "degrees", 400 | "interrupts", 401 | "noInterrupts", 402 | "lowByte", 403 | "highByte", 404 | "bitRead", 405 | "bitSet", 406 | "bitClear", 407 | "bitWrite", 408 | "bit", 409 | "analogRead", 410 | "analogWrite", 411 | "pulseIn", 412 | "pulseInLong", 413 | "tone", 414 | ] 415 | ARDUINO_FORBIDDEN_RE = r"[^\w\d](" + r"|".join(ARDUINO_FORBIDDEN) + r")\(.*" 416 | 417 | 418 | @lint_re_check( 419 | ARDUINO_FORBIDDEN_RE, 420 | include=cpp_include, 421 | exclude=[ 422 | "esphome/components/mqtt/custom_mqtt_device.h", 423 | "esphome/components/sun/sun.cpp", 424 | ], 425 | ) 426 | def lint_no_arduino_framework_functions(fname, match): 427 | nolint = highlight("// NOLINT") 428 | return ( 429 | f"The function {highlight(match.group(1))} from the Arduino framework is forbidden to be " 430 | f"used directly in the ESPHome codebase. Please use ESPHome's abstractions and equivalent " 431 | f"C++ instead.\n" 432 | f"\n" 433 | f"(If the function is strictly necessary, please add `{nolint}` to the end of the line)" 434 | ) 435 | 436 | 437 | IDF_CONVERSION_FORBIDDEN = { 438 | "ARDUINO_ARCH_ESP32": "USE_ESP32", 439 | "ARDUINO_ARCH_ESP8266": "USE_ESP8266", 440 | "pgm_read_byte": "progmem_read_byte", 441 | "ICACHE_RAM_ATTR": "IRAM_ATTR", 442 | "esphome/core/esphal.h": "esphome/core/hal.h", 443 | } 444 | IDF_CONVERSION_FORBIDDEN_RE = r"(" + r"|".join(IDF_CONVERSION_FORBIDDEN) + r").*" 445 | 446 | 447 | @lint_re_check( 448 | IDF_CONVERSION_FORBIDDEN_RE, 449 | include=cpp_include, 450 | ) 451 | def lint_no_removed_in_idf_conversions(fname, match): 452 | replacement = IDF_CONVERSION_FORBIDDEN[match.group(1)] 453 | return ( 454 | f"The macro {highlight(match.group(1))} can no longer be used in ESPHome directly. " 455 | f"Please use {highlight(replacement)} instead." 456 | ) 457 | 458 | 459 | @lint_re_check( 460 | r"[^\w\d]byte\s+[\w\d]+\s*=", 461 | include=cpp_include, 462 | exclude={ 463 | "esphome/components/tuya/tuya.h", 464 | }, 465 | ) 466 | def lint_no_byte_datatype(fname, match): 467 | return ( 468 | f"The datatype {highlight('byte')} is not allowed to be used in ESPHome. " 469 | f"Please use {highlight('uint8_t')} instead." 470 | ) 471 | 472 | 473 | @lint_post_check 474 | def lint_constants_usage(): 475 | errors = [] 476 | for constant, uses in CONSTANTS_USES.items(): 477 | if len(uses) < 4: 478 | continue 479 | errors.append( 480 | "Constant {} is defined in {} files. Please move all definitions of the " 481 | "constant to const.py (Uses: {})" 482 | "".format(highlight(constant), len(uses), ", ".join(uses)) 483 | ) 484 | return errors 485 | 486 | 487 | def relative_cpp_search_text(fname, content): 488 | parts = fname.split("/") 489 | integration = parts[2] 490 | return f'#include "esphome/components/{integration}' 491 | 492 | 493 | @lint_content_find_check(relative_cpp_search_text, include=["esphome/components/*.cpp"]) 494 | def lint_relative_cpp_import(fname): 495 | return ( 496 | "Component contains absolute import - Components must always use " 497 | "relative imports.\n" 498 | "Change:\n" 499 | ' #include "esphome/components/abc/abc.h"\n' 500 | "to:\n" 501 | ' #include "abc.h"\n\n' 502 | ) 503 | 504 | 505 | def relative_py_search_text(fname, content): 506 | parts = fname.split("/") 507 | integration = parts[2] 508 | return f"esphome.components.{integration}" 509 | 510 | 511 | @lint_content_find_check( 512 | relative_py_search_text, 513 | include=["esphome/components/*.py"], 514 | exclude=["esphome/components/web_server/__init__.py"], 515 | ) 516 | def lint_relative_py_import(fname): 517 | return ( 518 | "Component contains absolute import - Components must always use " 519 | "relative imports within the integration.\n" 520 | "Change:\n" 521 | ' from esphome.components.abc import abc_ns"\n' 522 | "to:\n" 523 | " from . import abc_ns\n\n" 524 | ) 525 | 526 | 527 | @lint_content_check( 528 | include=[ 529 | "esphome/components/*.h", 530 | "esphome/components/*.cpp", 531 | "esphome/components/*.tcc", 532 | ], 533 | exclude=[ 534 | "esphome/components/socket/headers.h", 535 | "esphome/components/esp32/core.cpp", 536 | "esphome/components/esp8266/core.cpp", 537 | "esphome/components/rp2040/core.cpp", 538 | ], 539 | ) 540 | def lint_namespace(fname, content): 541 | expected_name = re.match( 542 | r"^esphome/components/([^/]+)/.*", fname.replace(os.path.sep, "/") 543 | ).group(1) 544 | search = f"namespace {expected_name}" 545 | if search in content: 546 | return None 547 | return ( 548 | "Invalid namespace found in C++ file. All integration C++ files should put all " 549 | "functions in a separate namespace that matches the integration's name. " 550 | "Please make sure the file contains {}".format(highlight(search)) 551 | ) 552 | 553 | 554 | @lint_content_find_check('"esphome.h"', include=cpp_include, exclude=["tests/custom.h"]) 555 | def lint_esphome_h(fname): 556 | return ( 557 | "File contains reference to 'esphome.h' - This file is " 558 | "auto-generated and should only be used for *custom* " 559 | "components. Please replace with references to the direct files." 560 | ) 561 | 562 | 563 | @lint_content_check(include=["*.h"]) 564 | def lint_pragma_once(fname, content): 565 | if "#pragma once" not in content: 566 | return ( 567 | "Header file contains no 'pragma once' header guard. Please add a " 568 | "'#pragma once' line at the top of the file." 569 | ) 570 | return None 571 | 572 | 573 | @lint_re_check( 574 | r"(whitelist|blacklist|slave)", 575 | exclude=["script/ci-custom.py"], 576 | flags=re.IGNORECASE | re.MULTILINE, 577 | ) 578 | def lint_inclusive_language(fname, match): 579 | # From https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=49decddd39e5f6132ccd7d9fdc3d7c470b0061bb 580 | return ( 581 | "Avoid the use of whitelist/blacklist/slave.\n" 582 | "Recommended replacements for 'master / slave' are:\n" 583 | " '{primary,main} / {secondary,replica,subordinate}\n" 584 | " '{initiator,requester} / {target,responder}'\n" 585 | " '{controller,host} / {device,worker,proxy}'\n" 586 | " 'leader / follower'\n" 587 | " 'director / performer'\n" 588 | "\n" 589 | "Recommended replacements for 'blacklist/whitelist' are:\n" 590 | " 'denylist / allowlist'\n" 591 | " 'blocklist / passlist'" 592 | ) 593 | 594 | 595 | @lint_re_check(r"[\t\r\f\v ]+$") 596 | def lint_trailing_whitespace(fname, match): 597 | return "Trailing whitespace detected" 598 | 599 | 600 | @lint_content_find_check( 601 | "ESP_LOG", 602 | include=["*.h", "*.tcc"], 603 | exclude=[ 604 | "esphome/components/binary_sensor/binary_sensor.h", 605 | "esphome/components/button/button.h", 606 | "esphome/components/climate/climate.h", 607 | "esphome/components/cover/cover.h", 608 | "esphome/components/display/display_buffer.h", 609 | "esphome/components/fan/fan.h", 610 | "esphome/components/i2c/i2c.h", 611 | "esphome/components/lock/lock.h", 612 | "esphome/components/mqtt/mqtt_component.h", 613 | "esphome/components/number/number.h", 614 | "esphome/components/output/binary_output.h", 615 | "esphome/components/output/float_output.h", 616 | "esphome/components/nextion/nextion_base.h", 617 | "esphome/components/select/select.h", 618 | "esphome/components/sensor/sensor.h", 619 | "esphome/components/stepper/stepper.h", 620 | "esphome/components/switch/switch.h", 621 | "esphome/components/text_sensor/text_sensor.h", 622 | "esphome/core/component.h", 623 | "esphome/core/gpio.h", 624 | "esphome/core/log.h", 625 | "tests/custom.h", 626 | ], 627 | ) 628 | def lint_log_in_header(fname): 629 | return ( 630 | "Found reference to ESP_LOG in header file. Using ESP_LOG* in header files " 631 | "is currently not possible - please move the definition to a source file (.cpp)" 632 | ) 633 | 634 | 635 | errors = collections.defaultdict(list) 636 | 637 | 638 | def add_errors(fname, errs): 639 | if not isinstance(errs, list): 640 | errs = [errs] 641 | for err in errs: 642 | if err is None: 643 | continue 644 | try: 645 | lineno, col, msg = err 646 | except ValueError: 647 | lineno = 1 648 | col = 1 649 | msg = err 650 | if not isinstance(msg, str): 651 | raise ValueError("Error is not instance of string!") 652 | if not isinstance(lineno, int): 653 | raise ValueError("Line number is not an int!") 654 | if not isinstance(col, int): 655 | raise ValueError("Column number is not an int!") 656 | errors[fname].append((lineno, col, msg)) 657 | 658 | 659 | for fname in files: 660 | _, ext = os.path.splitext(fname) 661 | run_checks(LINT_FILE_CHECKS, fname, fname) 662 | if ext in ignore_types: 663 | continue 664 | try: 665 | with codecs.open(fname, "r", encoding="utf-8") as f_handle: 666 | content = f_handle.read() 667 | except UnicodeDecodeError: 668 | add_errors( 669 | fname, 670 | "File is not readable as UTF-8. Please set your editor to UTF-8 mode.", 671 | ) 672 | continue 673 | run_checks(LINT_CONTENT_CHECKS, fname, fname, content) 674 | 675 | run_checks(LINT_POST_CHECKS, "POST") 676 | 677 | for f, errs in sorted(errors.items()): 678 | bold = functools.partial(styled, colorama.Style.BRIGHT) 679 | bold_red = functools.partial(styled, (colorama.Style.BRIGHT, colorama.Fore.RED)) 680 | err_str = ( 681 | f"{bold(f'{f}:{lineno}:{col}:')} {bold_red('lint:')} {msg}\n" 682 | for lineno, col, msg in errs 683 | ) 684 | print_error_for_file(f, "\n".join(err_str)) 685 | 686 | if args.print_slowest: 687 | lint_times = [] 688 | for lint in LINT_FILE_CHECKS + LINT_CONTENT_CHECKS + LINT_POST_CHECKS: 689 | durations = lint.get("durations", []) 690 | lint_times.append((sum(durations), len(durations), lint["func"].__name__)) 691 | lint_times.sort(key=lambda x: -x[0]) 692 | for i in range(min(len(lint_times), 10)): 693 | dur, invocations, name = lint_times[i] 694 | print(f" - '{name}' took {dur:.2f}s total (ran on {invocations} files)") 695 | print(f"Total time measured: {sum(x[0] for x in lint_times):.2f}s") 696 | 697 | sys.exit(len(errors)) 698 | -------------------------------------------------------------------------------- /README.old.md: -------------------------------------------------------------------------------- 1 | For issues, please go to [the discussion board](https://github.com/emporia-vue-local/esphome/discussions). 2 | 3 | **ESPHome Documentation:** https://esphome.io/ 4 | 5 |
6 | Instructions changelog 7 | 8 | - 2023-11-01: suggest setting `restore: false` 9 | - 2023-10-31: remove warning about flash, see https://github.com/emporia-vue-local/esphome/discussions/227#discussioncomment-7412125 10 | - 2023-09-11: reduce logging verbosity 11 | - 2023-09-03: revamp configuration for improved accuracy, thanks to [adam](https://www.technowizardry.net/2023/02/local-energy-monitoring-using-the-emporia-vue-2/) and [@kahrendt](https://github.com/kahrendt) 12 | - 2023-06-11: fix buzzer with GND, move LED to HA config section, add template classes 13 | - 2023-03-08: configuration example for net metering 14 | - 2023-02-20: update style to modern home assistant, add buzzer support, add led support 15 | - 2023-01-28: add frequency support 16 | - 2023-01-18: increase flash write interval 17 | - 2022-12-07: switch suggested branch back to dev 18 | - 2022-07-30: add home assistant instructions & MQTT FAQ. 19 | - 2022-07-16: mention using UART adaptor's RTS pin, thanks to @PanicRide 20 | - 2022-07-02: mention mqtt is now supported 21 | - 2022-04-30: bump software version number to 2022.4.0 22 | - 2022-05-04: mention 64-bit ARM issues in FAQ 23 | 24 |
25 | 26 | # Setting up Emporia Vue 2/3 with ESPHome 27 | 28 | **Got a Vue 3? [You can install ESPHome local control on it as well!](https://digiblur.com/2024/03/14/emporia-vue-gen3-esp32-esphome-home-assistant/)** Set `variant: vue3` in the `emporia_vue` sensor block when compiling for Gen 3 hardware. 29 | 30 | ![example of hass setup](https://i.imgur.com/hC26j2M.png) 31 | 32 | ## What you need 33 | 34 | - USB to serial converter module 35 | - I tested this with a cheap & generic CH340G adapter 36 | - 4 male-to-female jumper wires 37 | - 4 male pcb-mount headers 38 | - Soldering iron & accessories 39 | - [some recommendations here](https://www.reddit.com/r/AskElectronics/wiki/soldering) 40 | - [esptool.py](https://github.com/espressif/esptool) ([windows instructions](https://cyberblogspot.com/how-to-install-esptool-on-windows-10/), [generic instructions](https://docs.espressif.com/projects/esptool/en/latest/esp32/installation.html)) 41 | - Working ESPHome installation [(see "Getting started")](https://esphome.io/) 42 | 43 | ## Panel installation, part 1 44 | 45 | You'll want to install the clamps & wiring harness into your panel following the instructions at https://www.emporiaenergy.com/installation-guides. At this time, place a label on each wire using masking tape & a pen rather than connecting them to the energy monitor. 46 | 47 | Next, we need to figure out which circuits are on which phases, and in the case of multi-pole breakers, the multiplier. There should be a label like the following on your panel: 48 | ![panel phase diagram](https://i.imgur.com/GkoaLzp.jpeg) 49 | For each clamp, you want to make a note of the following information: 50 | 51 | - clamp number 52 | - circuit number 53 | - phase 54 | - multiplier, if it is a multi-pole breaker 55 | 56 | For the wiring harness, you'll want to make a note of which color cable matches which service main clamp (A, B, C). 57 | 58 | ## Writing configuration 59 | 60 | Here's a starting point for a configuration, save it to `.yaml` into project folder: 61 | 62 | ```yaml 63 | esphome: 64 | name: emporiavue2 65 | friendly_name: vue2 66 | 67 | external_components: 68 | - source: github://emporia-vue-local/esphome@dev 69 | components: 70 | - emporia_vue 71 | 72 | esp32: 73 | board: esp32dev 74 | framework: 75 | type: esp-idf 76 | version: recommended 77 | 78 | # Enable Home Assistant API 79 | api: 80 | encryption: 81 | # Encryption key is generated by the new device wizard. 82 | key: "" 83 | 84 | services: 85 | - service: play_rtttl 86 | variables: 87 | song_str: string 88 | then: 89 | - rtttl.play: 90 | rtttl: !lambda 'return song_str;' 91 | 92 | ota: 93 | # Create a secure password for pushing OTA updates. 94 | password: "" 95 | 96 | # Enable logging 97 | logger: 98 | logs: 99 | # by default, every reading will be printed to the UART, which is very slow 100 | # This will disable printing the readings but keep other helpful messages 101 | sensor: INFO 102 | 103 | wifi: 104 | # Wifi credentials are stored securely by new device wizard. 105 | ssid: !secret wifi_ssid 106 | password: !secret wifi_password 107 | 108 | preferences: 109 | # please also make sure `restore: false` is set on all `platform: total_daily_energy` 110 | # sensors below. 111 | flash_write_interval: "48h" 112 | 113 | output: 114 | - platform: ledc 115 | pin: GPIO12 116 | id: buzzer 117 | - platform: gpio 118 | pin: GPIO27 119 | id: buzzer_gnd 120 | 121 | rtttl: 122 | output: buzzer 123 | on_finished_playback: 124 | - logger.log: 'Song ended!' 125 | 126 | button: 127 | - platform: template 128 | name: "Two Beeps" 129 | on_press: 130 | - rtttl.play: "two short:d=4,o=5,b=100:16e6,16e6" 131 | 132 | light: 133 | - platform: status_led 134 | name: "D3_LED" 135 | pin: 23 136 | restore_mode: ALWAYS_ON 137 | entity_category: config 138 | 139 | i2c: 140 | sda: 21 141 | scl: 22 142 | scan: false 143 | frequency: 400kHz 144 | timeout: 1ms 145 | id: i2c_a 146 | 147 | time: 148 | # needs some time source to reset daily counters and not accumulate 149 | # floating-point issues. If Home Assistant isn't available, use sntp and 150 | # set servers and/or DNS as appropriate: https://esphome.io/components/time/sntp.html 151 | - platform: homeassistant 152 | id: my_time 153 | 154 | # these are called references in YAML. They allow you to reuse 155 | # this configuration in each sensor, while only defining it once 156 | .defaultfilters: 157 | - &throttle_avg 158 | # average all raw readings together over a 5 second span before publishing 159 | throttle_average: 5s 160 | - &throttle_time 161 | # only send the most recent measurement every 60 seconds 162 | throttle: 60s 163 | - &invert 164 | # invert and filter out any values below 0. 165 | lambda: 'return max(-x, 0.0f);' 166 | - &pos 167 | # filter out any values below 0. 168 | lambda: 'return max(x, 0.0f);' 169 | - &abs 170 | # take the absolute value of the value 171 | lambda: 'return abs(x);' 172 | 173 | sensor: 174 | - platform: emporia_vue 175 | # Set the hardware revision. Default is Vue 2; use "vue3" for the Gen 3 hardware 176 | variant: vue2 177 | i2c_id: i2c_a 178 | phases: 179 | - id: phase_a # Verify that this specific phase/leg is connected to correct input wire color on device listed below 180 | input: BLACK # Vue device wire color 181 | calibration: 0.022 # 0.022 is used as the default as starting point but may need adjusted to ensure accuracy 182 | # To calculate new calibration value use the formula * / 183 | voltage: 184 | name: "Phase A Voltage" 185 | filters: [*throttle_avg, *pos] 186 | frequency: 187 | name: "Phase A Frequency" 188 | filters: [*throttle_avg, *pos] 189 | - id: phase_b # Verify that this specific phase/leg is connected to correct input wire color on device listed below 190 | input: RED # Vue device wire color 191 | calibration: 0.022 # 0.022 is used as the default as starting point but may need adjusted to ensure accuracy 192 | # To calculate new calibration value use the formula * / 193 | voltage: 194 | name: "Phase B Voltage" 195 | filters: [*throttle_avg, *pos] 196 | phase_angle: 197 | name: "Phase B Phase Angle" 198 | filters: [*throttle_avg, *pos] 199 | ct_clamps: 200 | # Do not specify a name for any of the power sensors here, only an id. This leaves the power sensors internal to ESPHome. 201 | # Copy sensors will filter and then send power measurements to HA 202 | # These non-throttled power sensors are used for accurately calculating energy 203 | - phase_id: phase_a 204 | input: "A" # Verify the CT going to this device input also matches the phase/leg 205 | power: 206 | id: phase_a_power 207 | filters: [*pos] 208 | - phase_id: phase_b 209 | input: "B" # Verify the CT going to this device input also matches the phase/leg 210 | power: 211 | id: phase_b_power 212 | filters: [*pos] 213 | # Pay close attention to set the phase_id for each breaker by matching it to the phase/leg it connects to in the panel 214 | - { phase_id: phase_a, input: "1", power: { id: cir1, filters: [ *pos ] } } 215 | - { phase_id: phase_b, input: "2", power: { id: cir2, filters: [ *pos ] } } 216 | - { phase_id: phase_a, input: "3", power: { id: cir3, filters: [ *pos ] } } 217 | - { phase_id: phase_a, input: "4", power: { id: cir4, filters: [ *pos ] } } 218 | - { phase_id: phase_a, input: "5", power: { id: cir5, filters: [ *pos, multiply: 2 ] } } 219 | - { phase_id: phase_a, input: "6", power: { id: cir6, filters: [ *pos, multiply: 2 ] } } 220 | - { phase_id: phase_a, input: "7", power: { id: cir7, filters: [ *pos, multiply: 2 ] } } 221 | - { phase_id: phase_b, input: "8", power: { id: cir8, filters: [ *pos ] } } 222 | - { phase_id: phase_b, input: "9", power: { id: cir9, filters: [ *pos ] } } 223 | - { phase_id: phase_b, input: "10", power: { id: cir10, filters: [ *pos ] } } 224 | - { phase_id: phase_a, input: "11", power: { id: cir11, filters: [ *pos, multiply: 2 ] } } 225 | - { phase_id: phase_a, input: "12", power: { id: cir12, filters: [ *pos, multiply: 2 ] } } 226 | - { phase_id: phase_a, input: "13", power: { id: cir13, filters: [ *pos ] } } 227 | - { phase_id: phase_a, input: "14", power: { id: cir14, filters: [ *pos ] } } 228 | - { phase_id: phase_b, input: "15", power: { id: cir15, filters: [ *pos ] } } 229 | - { phase_id: phase_a, input: "16", power: { id: cir16, filters: [ *pos ] } } 230 | on_update: 231 | then: 232 | - component.update: total_power 233 | - component.update: balance_power 234 | # The copy sensors filter and send the power state to HA 235 | - { platform: copy, name: "Phase A Power", source_id: phase_a_power, filters: *throttle_avg } 236 | - { platform: copy, name: "Phase B Power", source_id: phase_b_power, filters: *throttle_avg } 237 | - { platform: copy, name: "Total Power", source_id: total_power, filters: *throttle_avg } 238 | - { platform: copy, name: "Balance Power", source_id: balance_power, filters: *throttle_avg } 239 | - { platform: copy, name: "Circuit 1 Power", source_id: cir1, filters: *throttle_avg } 240 | - { platform: copy, name: "Circuit 2 Power", source_id: cir2, filters: *throttle_avg } 241 | - { platform: copy, name: "Circuit 3 Power", source_id: cir3, filters: *throttle_avg } 242 | - { platform: copy, name: "Circuit 4 Power", source_id: cir4, filters: *throttle_avg } 243 | - { platform: copy, name: "Circuit 5 Power", source_id: cir5, filters: *throttle_avg } 244 | - { platform: copy, name: "Circuit 6 Power", source_id: cir6, filters: *throttle_avg } 245 | - { platform: copy, name: "Circuit 7 Power", source_id: cir7, filters: *throttle_avg } 246 | - { platform: copy, name: "Circuit 8 Power", source_id: cir8, filters: *throttle_avg } 247 | - { platform: copy, name: "Circuit 9 Power", source_id: cir9, filters: *throttle_avg } 248 | - { platform: copy, name: "Circuit 10 Power", source_id: cir10, filters: *throttle_avg } 249 | - { platform: copy, name: "Circuit 11 Power", source_id: cir11, filters: *throttle_avg } 250 | - { platform: copy, name: "Circuit 12 Power", source_id: cir12, filters: *throttle_avg } 251 | - { platform: copy, name: "Circuit 13 Power", source_id: cir13, filters: *throttle_avg } 252 | - { platform: copy, name: "Circuit 14 Power", source_id: cir14, filters: *throttle_avg } 253 | - { platform: copy, name: "Circuit 15 Power", source_id: cir15, filters: *throttle_avg } 254 | - { platform: copy, name: "Circuit 16 Power", source_id: cir16, filters: *throttle_avg } 255 | - platform: template 256 | lambda: return id(phase_a_power).state + id(phase_b_power).state; 257 | update_interval: never # will be updated after all power sensors update via on_update trigger 258 | id: total_power 259 | device_class: power 260 | state_class: measurement 261 | unit_of_measurement: "W" 262 | - platform: total_daily_energy 263 | name: "Total Daily Energy" 264 | power_id: total_power 265 | accuracy_decimals: 0 266 | restore: false 267 | filters: *throttle_time 268 | - platform: template 269 | lambda: !lambda |- 270 | return max(0.0f, id(total_power).state - 271 | id( cir1).state - 272 | id( cir2).state - 273 | id( cir3).state - 274 | id( cir4).state - 275 | id( cir5).state - 276 | id( cir6).state - 277 | id( cir7).state - 278 | id( cir8).state - 279 | id( cir9).state - 280 | id(cir10).state - 281 | id(cir11).state - 282 | id(cir12).state - 283 | id(cir13).state - 284 | id(cir14).state - 285 | id(cir15).state - 286 | id(cir16).state); 287 | update_interval: never # will be updated after all power sensors update via on_update trigger 288 | id: balance_power 289 | device_class: power 290 | state_class: measurement 291 | unit_of_measurement: "W" 292 | - platform: total_daily_energy 293 | name: "Balance Daily Energy" 294 | power_id: balance_power 295 | accuracy_decimals: 0 296 | restore: false 297 | filters: *throttle_time 298 | - { power_id: cir1, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 1 Daily Energy", filters: *throttle_time } 299 | - { power_id: cir2, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 2 Daily Energy", filters: *throttle_time } 300 | - { power_id: cir3, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 3 Daily Energy", filters: *throttle_time } 301 | - { power_id: cir4, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 4 Daily Energy", filters: *throttle_time } 302 | - { power_id: cir5, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 5 Daily Energy", filters: *throttle_time } 303 | - { power_id: cir6, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 6 Daily Energy", filters: *throttle_time } 304 | - { power_id: cir7, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 7 Daily Energy", filters: *throttle_time } 305 | - { power_id: cir8, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 8 Daily Energy", filters: *throttle_time } 306 | - { power_id: cir9, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 9 Daily Energy", filters: *throttle_time } 307 | - { power_id: cir10, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 10 Daily Energy", filters: *throttle_time } 308 | - { power_id: cir11, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 11 Daily Energy", filters: *throttle_time } 309 | - { power_id: cir12, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 12 Daily Energy", filters: *throttle_time } 310 | - { power_id: cir13, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 13 Daily Energy", filters: *throttle_time } 311 | - { power_id: cir14, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 14 Daily Energy", filters: *throttle_time } 312 | - { power_id: cir15, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 15 Daily Energy", filters: *throttle_time } 313 | - { power_id: cir16, platform: total_daily_energy, accuracy_decimals: 0, restore: false, name: "Circuit 16 Daily Energy", filters: *throttle_time } 314 | ``` 315 | 316 | **Vue 3 hardware:** Change `variant: vue2` above to `variant: vue3`. Vue 2 units can leave the line as-is or delete it entirely to use the default. 317 | 318 | You'll want to replace ``, ``, and `` with a unique password, and your wifi credentials, respectively. 319 | 320 | You'll also want to update the `sensor` section of the configuration using the information you've collected in _Panel installation, part 1_. 321 | 322 | Note the `throttle_avg`. This is optional, but since we get a reading every 240ms, it is helpful to average these readings together so that we don't need to store such dense, noisy, data in Home Assistant. 323 | 324 | Note the "Total Power", "Total Daily Energy", and "Circuit x Daily Energy". This is needed for the Home Assistant energy system, which requires daily kWh numbers. 325 | 326 | To configure energy returned to the grid for NET metering ([more info here](https://www.nrel.gov/state-local-tribal/basics-net-metering.html)), you need to add the following configuration: 327 | 328 | ```yaml 329 | sensor: 330 | - platform: emporia_vue 331 | ct_clamps: 332 | - phase_id: phase_a 333 | input: "A" # Verify the CT going to this device input also matches the phase/leg 334 | power: 335 | name: "Phase A Power Return" 336 | id: phase_a_power_return 337 | filters: [*throttle_avg, *invert] # This measures energy uploaded to grid on phase A 338 | - phase_id: phase_b 339 | input: "B" # Verify the CT going to this device input also matches the phase/leg 340 | power: 341 | name: "Phase B Power Return" 342 | id: phase_b_power_return 343 | filters: [*throttle_avg, *invert] # This measures energy uploaded to grid on phase B 344 | - platform: template 345 | name: "Total Power Return" 346 | lambda: return id(phase_a_power_return).state + id(phase_b_power_return).state; 347 | update_interval: 1s 348 | id: total_power_return 349 | device_class: power 350 | state_class: measurement 351 | unit_of_measurement: "W" 352 | - platform: total_daily_energy 353 | name: "Total Daily Energy Return" 354 | power_id: total_power_return 355 | accuracy_decimals: 0 356 | 357 | ``` 358 | 359 | Your solar sensors' configuration depends on your setup (single phase, split phase, 3-phase). The following example shows a split-phase installation using ct clamps 15 and 16: 360 | 361 | ```yaml 362 | sensor: 363 | - platform: template 364 | name: "Solar Power" 365 | lambda: return id(cir15).state + id(cir16).state; 366 | id: solar_power 367 | device_class: power 368 | state_class: measurement 369 | unit_of_measurement: "W" 370 | - platform: total_daily_energy 371 | name: "Solar Daily Energy" 372 | power_id: solar_power 373 | accuracy_decimals: 0 374 | ``` 375 | 376 | Do not use the `web_server` since it is not compatible with the `esp-idf` framework, and you will get odd error messages. 377 | 378 | It's not too critical to get this right on the first try, because you can update the board over WiFi using [the ESPHome Dashboard](https://esphome.io/guides/getting_started_command_line.html#bonus-esphome-dashboard). 379 | 380 | ## Backing up & flashing the Vue 2 381 | 382 | **⚠️⚡ Do not power your Vue by mains when doing this flashing! It will not work & is deadly. Only connect your Vue to the mains with the enclosure closed. ⚡⚠️** 383 | 384 | Pry the lever on one of the jumper cables up using a pencil or a needle or some other sharp thing. If your cables don't have a lever, cut one end of the cable & strip it using scissors or a knife. 385 | ![prying the lever on the jumper cable](https://i.imgur.com/BZJGdKq.jpg)![separated cable](https://i.imgur.com/eOc29M7.jpg) 386 | You will then need to solder a serial header onto the programming port, so that it looks like this: 387 | 388 | ![closeup of the debug header pinout](https://i.imgur.com/NetVsQo.jpeg) 389 | Plug the USB adapter in. Connect RX to RX, TX to TX, and GND to GND. Do not connect 5V or 3.3V at this time. 390 | 391 | Plug in the unmodified end of the cable we modified above into the IO0 pin of the Emporia Vue 2. 392 | 393 | Open a console window and test that `esptool.py version` works. 394 | 395 | ![photo of connected jumpers](https://i.imgur.com/TmB5PPV.jpeg) 396 | Hold the modified end of the cable in IO0 to the metal shield on the ESP32. If you'd like, you can tape it down so that you have both hands free. 397 | 398 | While holding it in place, connect 5V on your UART adapter to the `VCC_5V0` pin on the board. 399 | 400 | If your TTL adapter has both the DTR and RTS pins exposed, you can let it automatically reboot the board and put the chip into flash mode when necessary. IO0 connects to DTR, and EN connects to RTS. In this case, you don't need to hold anything down. 401 | 402 | ### Doing a backup 403 | 404 | With your other hand, run the following in the console: `esptool.py -b 921600 read_flash 0 0x800000 flash_contents.bin`. Successful completion of this step is _critical_ in case something goes wrong later. This file is necessary to restore the device to factory function. 405 | 406 | If the above command fails, try again using `esptool.py -b 115200 read_flash 0 0x800000 flash_contents.bin`. If you're using an Apple Silicon (M1, M2, etc) CPU and it stops working after a certain percentage every time, try using a different machine 407 | 408 | ### Flashing new software 409 | 410 | With your other hand, kick off the upload process. If you're using the command-line, `esphome run .yaml`, otherwise click the button in the GUI. This will take a few minutes and install the new software on the Vue 2! 411 | 412 | You'll see a bunch of errors like `Failed to read from sensor due to I2C error 3`, but that's fine, since they'll go away when it is installed into into the wall. 413 | 414 | ## Panel installation, part 2 415 | 416 | Reassemble to Vue 2, and follow the instructions to plug everything in & started up! 417 | 418 | ## Getting a GUI 419 | 420 | This project works best with Home Assistant. Follow these instructions to [connect the Vue 2 to Home Assistant](https://esphome.io/guides/getting_started_hassio.html#connecting-your-device-to-home-assistant). 421 | 422 | Once you connect the Vue to Home Assistant, you can [configure the Home Assistant energy monitor functionallity](https://my.home-assistant.io/redirect/config_energy), as well as a variety of automations. 423 | 424 | ## FAQ 425 | 426 | ### What is MQTT? 427 | 428 | MQTT is an alternative way of communicating the readings. If you need it, you already know, and it is not required for use with Home Assistant. 429 | 430 | ### How do I use this with MQTT? 431 | 432 | There's now support for MQTT with this integration thanks to the hard work of the ESPHome folks! Please reference [MQTT Client Component](https://esphome.io/components/mqtt.html) for how to get this set up. 433 | 434 | ### I'm getting negative values 435 | 436 | - You may have put that clamp on the wire backwards 437 | - You may have selected the wrong phase in the configuration 438 | 439 | ### I've recorded negative energy values and I want to reset them 440 | 441 | Sensor values are saved to the esp32 flash. You can reset all sensors by implementing a [factory reset button](https://esphome.io/components/button/factory_reset.html). 442 | 443 | ### The readings on one or two of my sensors are crazy 444 | 445 | Sometimes the CTs aren't fully plugged into the 3.5mm jacks on the Vue. It's often not an issue with the initial install, but with stuff getting jostled around as you put things back together. 446 | 447 | This issue will often manifest as jumps between 0W and some other wattage for no reason. 448 | 449 | Open up the panel, and make sure every connector is fully inserted into the Vue. Check if the problem is solved before putting the panel cover back on. 450 | 451 | ### My data readings go up and down 452 | 453 | If your readings are within ±1W, then they're within the expected margin of error. The filters are designed to smooth out noise like this, and it's expected as no physical system can be perfect. 454 | 455 | If the readings are significant outside of that, there may be a problem. 456 | 457 | ### I'm seeing zeros on certain current clamps 458 | 459 | First off, you will want to remove all filters for that sensor. Replace `filters: [ *throttle_avg, *pos ]`, etc, with `filters: []`. 460 | 461 | If your data is hovering around 0, then you either don't have any load on that circuit or there's some other issue that hasn't come up before. 462 | 463 | If you're seeing negative data, it could be a few things: 464 | 465 | - First off, make sure you've properly installed the clamps according to the instructions. The L side of the clamp should point towards the load. For solar systems or similar, keep in mind that current flows from the solar panel to your electrical panel, not the other way. 466 | - Make sure you've selected the correct phase in the configuration. You will get negative _and_ nonsense power readings if you select the wrong phase. You can't negate the data through a filter and expect it to be correct. 467 | 468 | When you're done troubleshooting, remember to place the filters back. 469 | 470 | ### I'm using a 64-bit Pi & can't compile! 471 | 472 | Some users have successfully managed to build this on a 64-bit Pi: https://github.com/emporia-vue-local/esphome/discussions/147 473 | 474 | ~If you're using a 64-bit ARM OS, unfortunately you are unable to build this. It's not a limitation with this project, but a limitation with the upstream PlatformIO toolchains.~ 475 | 476 | You'll see an error like 477 | 478 | ``` 479 | Could not find the package with 'platformio/toolchain-esp32ulp @ ~1.22851.0' requirements for your system 'linux_aarch64' 480 | ``` 481 | 482 | You can try using a different computer. 32-bit and 64-bit x86 computers are both compatible (most laptops & desktops). 483 | -------------------------------------------------------------------------------- /script/api_protobuf/api_protobuf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Python 3 script to automatically generate C++ classes for ESPHome's native API. 3 | 4 | It's pretty crappy spaghetti code, but it works. 5 | 6 | you need to install protobuf-compiler: 7 | running protc --version should return 8 | libprotoc 3.6.1 9 | 10 | then run this script with python3 and the files 11 | 12 | esphome/components/api/api_pb2_service.h 13 | esphome/components/api/api_pb2_service.cpp 14 | esphome/components/api/api_pb2.h 15 | esphome/components/api/api_pb2.cpp 16 | 17 | will be generated, they still need to be formatted 18 | """ 19 | 20 | import re 21 | from pathlib import Path 22 | from textwrap import dedent 23 | from subprocess import call 24 | 25 | # Generate with 26 | # protoc --python_out=script/api_protobuf -I esphome/components/api/ api_options.proto 27 | 28 | import aioesphomeapi.api_options_pb2 as pb 29 | import google.protobuf.descriptor_pb2 as descriptor 30 | 31 | file_header = "// This file was automatically generated with a tool.\n" 32 | file_header += "// See scripts/api_protobuf/api_protobuf.py\n" 33 | 34 | cwd = Path(__file__).resolve().parent 35 | root = cwd.parent.parent / "esphome" / "components" / "api" 36 | prot = root / "api.protoc" 37 | call(["protoc", "-o", str(prot), "-I", str(root), "api.proto"]) 38 | content = prot.read_bytes() 39 | 40 | d = descriptor.FileDescriptorSet.FromString(content) 41 | 42 | 43 | def indent_list(text, padding=" "): 44 | lines = [] 45 | for line in text.splitlines(): 46 | if line == "": 47 | p = "" 48 | elif line.startswith("#ifdef") or line.startswith("#endif"): 49 | p = "" 50 | else: 51 | p = padding 52 | lines.append(p + line) 53 | return lines 54 | 55 | 56 | def indent(text, padding=" "): 57 | return "\n".join(indent_list(text, padding)) 58 | 59 | 60 | def camel_to_snake(name): 61 | # https://stackoverflow.com/a/1176023 62 | s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) 63 | return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() 64 | 65 | 66 | class TypeInfo: 67 | def __init__(self, field): 68 | self._field = field 69 | 70 | @property 71 | def default_value(self): 72 | return "" 73 | 74 | @property 75 | def name(self): 76 | return self._field.name 77 | 78 | @property 79 | def arg_name(self): 80 | return self.name 81 | 82 | @property 83 | def field_name(self): 84 | return self.name 85 | 86 | @property 87 | def number(self): 88 | return self._field.number 89 | 90 | @property 91 | def repeated(self): 92 | return self._field.label == 3 93 | 94 | @property 95 | def cpp_type(self): 96 | raise NotImplementedError 97 | 98 | @property 99 | def reference_type(self): 100 | return f"{self.cpp_type} " 101 | 102 | @property 103 | def const_reference_type(self): 104 | return f"{self.cpp_type} " 105 | 106 | @property 107 | def public_content(self) -> str: 108 | return [self.class_member] 109 | 110 | @property 111 | def protected_content(self) -> str: 112 | return [] 113 | 114 | @property 115 | def class_member(self) -> str: 116 | return f"{self.cpp_type} {self.field_name}{{{self.default_value}}};" 117 | 118 | @property 119 | def decode_varint_content(self) -> str: 120 | content = self.decode_varint 121 | if content is None: 122 | return None 123 | return dedent( 124 | f"""\ 125 | case {self.number}: {{ 126 | this->{self.field_name} = {content}; 127 | return true; 128 | }}""" 129 | ) 130 | 131 | decode_varint = None 132 | 133 | @property 134 | def decode_length_content(self) -> str: 135 | content = self.decode_length 136 | if content is None: 137 | return None 138 | return dedent( 139 | f"""\ 140 | case {self.number}: {{ 141 | this->{self.field_name} = {content}; 142 | return true; 143 | }}""" 144 | ) 145 | 146 | decode_length = None 147 | 148 | @property 149 | def decode_32bit_content(self) -> str: 150 | content = self.decode_32bit 151 | if content is None: 152 | return None 153 | return dedent( 154 | f"""\ 155 | case {self.number}: {{ 156 | this->{self.field_name} = {content}; 157 | return true; 158 | }}""" 159 | ) 160 | 161 | decode_32bit = None 162 | 163 | @property 164 | def decode_64bit_content(self) -> str: 165 | content = self.decode_64bit 166 | if content is None: 167 | return None 168 | return dedent( 169 | f"""\ 170 | case {self.number}: {{ 171 | this->{self.field_name} = {content}; 172 | return true; 173 | }}""" 174 | ) 175 | 176 | decode_64bit = None 177 | 178 | @property 179 | def encode_content(self): 180 | return f"buffer.{self.encode_func}({self.number}, this->{self.field_name});" 181 | 182 | encode_func = None 183 | 184 | @property 185 | def dump_content(self): 186 | o = f'out.append(" {self.name}: ");\n' 187 | o += self.dump(f"this->{self.field_name}") + "\n" 188 | o += f'out.append("\\n");\n' 189 | return o 190 | 191 | dump = None 192 | 193 | 194 | TYPE_INFO = {} 195 | 196 | 197 | def register_type(name): 198 | def func(value): 199 | TYPE_INFO[name] = value 200 | return value 201 | 202 | return func 203 | 204 | 205 | @register_type(1) 206 | class DoubleType(TypeInfo): 207 | cpp_type = "double" 208 | default_value = "0.0" 209 | decode_64bit = "value.as_double()" 210 | encode_func = "encode_double" 211 | 212 | def dump(self, name): 213 | o = f'sprintf(buffer, "%g", {name});\n' 214 | o += f"out.append(buffer);" 215 | return o 216 | 217 | 218 | @register_type(2) 219 | class FloatType(TypeInfo): 220 | cpp_type = "float" 221 | default_value = "0.0f" 222 | decode_32bit = "value.as_float()" 223 | encode_func = "encode_float" 224 | 225 | def dump(self, name): 226 | o = f'sprintf(buffer, "%g", {name});\n' 227 | o += f"out.append(buffer);" 228 | return o 229 | 230 | 231 | @register_type(3) 232 | class Int64Type(TypeInfo): 233 | cpp_type = "int64_t" 234 | default_value = "0" 235 | decode_varint = "value.as_int64()" 236 | encode_func = "encode_int64" 237 | 238 | def dump(self, name): 239 | o = f'sprintf(buffer, "%lld", {name});\n' 240 | o += f"out.append(buffer);" 241 | return o 242 | 243 | 244 | @register_type(4) 245 | class UInt64Type(TypeInfo): 246 | cpp_type = "uint64_t" 247 | default_value = "0" 248 | decode_varint = "value.as_uint64()" 249 | encode_func = "encode_uint64" 250 | 251 | def dump(self, name): 252 | o = f'sprintf(buffer, "%llu", {name});\n' 253 | o += f"out.append(buffer);" 254 | return o 255 | 256 | 257 | @register_type(5) 258 | class Int32Type(TypeInfo): 259 | cpp_type = "int32_t" 260 | default_value = "0" 261 | decode_varint = "value.as_int32()" 262 | encode_func = "encode_int32" 263 | 264 | def dump(self, name): 265 | o = f'sprintf(buffer, "%d", {name});\n' 266 | o += f"out.append(buffer);" 267 | return o 268 | 269 | 270 | @register_type(6) 271 | class Fixed64Type(TypeInfo): 272 | cpp_type = "uint64_t" 273 | default_value = "0" 274 | decode_64bit = "value.as_fixed64()" 275 | encode_func = "encode_fixed64" 276 | 277 | def dump(self, name): 278 | o = f'sprintf(buffer, "%llu", {name});\n' 279 | o += f"out.append(buffer);" 280 | return o 281 | 282 | 283 | @register_type(7) 284 | class Fixed32Type(TypeInfo): 285 | cpp_type = "uint32_t" 286 | default_value = "0" 287 | decode_32bit = "value.as_fixed32()" 288 | encode_func = "encode_fixed32" 289 | 290 | def dump(self, name): 291 | o = f'sprintf(buffer, "%u", {name});\n' 292 | o += f"out.append(buffer);" 293 | return o 294 | 295 | 296 | @register_type(8) 297 | class BoolType(TypeInfo): 298 | cpp_type = "bool" 299 | default_value = "false" 300 | decode_varint = "value.as_bool()" 301 | encode_func = "encode_bool" 302 | 303 | def dump(self, name): 304 | o = f"out.append(YESNO({name}));" 305 | return o 306 | 307 | 308 | @register_type(9) 309 | class StringType(TypeInfo): 310 | cpp_type = "std::string" 311 | default_value = "" 312 | reference_type = "std::string &" 313 | const_reference_type = "const std::string &" 314 | decode_length = "value.as_string()" 315 | encode_func = "encode_string" 316 | 317 | def dump(self, name): 318 | o = f'out.append("\'").append({name}).append("\'");' 319 | return o 320 | 321 | 322 | @register_type(11) 323 | class MessageType(TypeInfo): 324 | @property 325 | def cpp_type(self): 326 | return self._field.type_name[1:] 327 | 328 | default_value = "" 329 | 330 | @property 331 | def reference_type(self): 332 | return f"{self.cpp_type} &" 333 | 334 | @property 335 | def const_reference_type(self): 336 | return f"const {self.cpp_type} &" 337 | 338 | @property 339 | def encode_func(self): 340 | return f"encode_message<{self.cpp_type}>" 341 | 342 | @property 343 | def decode_length(self): 344 | return f"value.as_message<{self.cpp_type}>()" 345 | 346 | def dump(self, name): 347 | o = f"{name}.dump_to(out);" 348 | return o 349 | 350 | 351 | @register_type(12) 352 | class BytesType(TypeInfo): 353 | cpp_type = "std::string" 354 | default_value = "" 355 | reference_type = "std::string &" 356 | const_reference_type = "const std::string &" 357 | decode_length = "value.as_string()" 358 | encode_func = "encode_string" 359 | 360 | def dump(self, name): 361 | o = f'out.append("\'").append({name}).append("\'");' 362 | return o 363 | 364 | 365 | @register_type(13) 366 | class UInt32Type(TypeInfo): 367 | cpp_type = "uint32_t" 368 | default_value = "0" 369 | decode_varint = "value.as_uint32()" 370 | encode_func = "encode_uint32" 371 | 372 | def dump(self, name): 373 | o = f'sprintf(buffer, "%u", {name});\n' 374 | o += f"out.append(buffer);" 375 | return o 376 | 377 | 378 | @register_type(14) 379 | class EnumType(TypeInfo): 380 | @property 381 | def cpp_type(self): 382 | return f"enums::{self._field.type_name[1:]}" 383 | 384 | @property 385 | def decode_varint(self): 386 | return f"value.as_enum<{self.cpp_type}>()" 387 | 388 | default_value = "" 389 | 390 | @property 391 | def encode_func(self): 392 | return f"encode_enum<{self.cpp_type}>" 393 | 394 | def dump(self, name): 395 | o = f"out.append(proto_enum_to_string<{self.cpp_type}>({name}));" 396 | return o 397 | 398 | 399 | @register_type(15) 400 | class SFixed32Type(TypeInfo): 401 | cpp_type = "int32_t" 402 | default_value = "0" 403 | decode_32bit = "value.as_sfixed32()" 404 | encode_func = "encode_sfixed32" 405 | 406 | def dump(self, name): 407 | o = f'sprintf(buffer, "%d", {name});\n' 408 | o += f"out.append(buffer);" 409 | return o 410 | 411 | 412 | @register_type(16) 413 | class SFixed64Type(TypeInfo): 414 | cpp_type = "int64_t" 415 | default_value = "0" 416 | decode_64bit = "value.as_sfixed64()" 417 | encode_func = "encode_sfixed64" 418 | 419 | def dump(self, name): 420 | o = f'sprintf(buffer, "%lld", {name});\n' 421 | o += f"out.append(buffer);" 422 | return o 423 | 424 | 425 | @register_type(17) 426 | class SInt32Type(TypeInfo): 427 | cpp_type = "int32_t" 428 | default_value = "0" 429 | decode_varint = "value.as_sint32()" 430 | encode_func = "encode_sint32" 431 | 432 | def dump(self, name): 433 | o = f'sprintf(buffer, "%d", {name});\n' 434 | o += f"out.append(buffer);" 435 | return o 436 | 437 | 438 | @register_type(18) 439 | class SInt64Type(TypeInfo): 440 | cpp_type = "int64_t" 441 | default_value = "0" 442 | decode_varint = "value.as_sint64()" 443 | encode_func = "encode_sint64" 444 | 445 | def dump(self, name): 446 | o = f'sprintf(buffer, "%lld", {name});\n' 447 | o += f"out.append(buffer);" 448 | return o 449 | 450 | 451 | class RepeatedTypeInfo(TypeInfo): 452 | def __init__(self, field): 453 | super().__init__(field) 454 | self._ti = TYPE_INFO[field.type](field) 455 | 456 | @property 457 | def cpp_type(self): 458 | return f"std::vector<{self._ti.cpp_type}>" 459 | 460 | @property 461 | def reference_type(self): 462 | return f"{self.cpp_type} &" 463 | 464 | @property 465 | def const_reference_type(self): 466 | return f"const {self.cpp_type} &" 467 | 468 | @property 469 | def decode_varint_content(self) -> str: 470 | content = self._ti.decode_varint 471 | if content is None: 472 | return None 473 | return dedent( 474 | f"""\ 475 | case {self.number}: {{ 476 | this->{self.field_name}.push_back({content}); 477 | return true; 478 | }}""" 479 | ) 480 | 481 | @property 482 | def decode_length_content(self) -> str: 483 | content = self._ti.decode_length 484 | if content is None: 485 | return None 486 | return dedent( 487 | f"""\ 488 | case {self.number}: {{ 489 | this->{self.field_name}.push_back({content}); 490 | return true; 491 | }}""" 492 | ) 493 | 494 | @property 495 | def decode_32bit_content(self) -> str: 496 | content = self._ti.decode_32bit 497 | if content is None: 498 | return None 499 | return dedent( 500 | f"""\ 501 | case {self.number}: {{ 502 | this->{self.field_name}.push_back({content}); 503 | return true; 504 | }}""" 505 | ) 506 | 507 | @property 508 | def decode_64bit_content(self) -> str: 509 | content = self._ti.decode_64bit 510 | if content is None: 511 | return None 512 | return dedent( 513 | f"""\ 514 | case {self.number}: {{ 515 | this->{self.field_name}.push_back({content}); 516 | return true; 517 | }}""" 518 | ) 519 | 520 | @property 521 | def _ti_is_bool(self): 522 | # std::vector is specialized for bool, reference does not work 523 | return isinstance(self._ti, BoolType) 524 | 525 | @property 526 | def encode_content(self): 527 | o = f"for (auto {'' if self._ti_is_bool else '&'}it : this->{self.field_name}) {{\n" 528 | o += f" buffer.{self._ti.encode_func}({self.number}, it, true);\n" 529 | o += f"}}" 530 | return o 531 | 532 | @property 533 | def dump_content(self): 534 | o = f'for (const auto {"" if self._ti_is_bool else "&"}it : this->{self.field_name}) {{\n' 535 | o += f' out.append(" {self.name}: ");\n' 536 | o += indent(self._ti.dump("it")) + "\n" 537 | o += f' out.append("\\n");\n' 538 | o += f"}}\n" 539 | return o 540 | 541 | 542 | def build_enum_type(desc): 543 | name = desc.name 544 | out = f"enum {name} : uint32_t {{\n" 545 | for v in desc.value: 546 | out += f" {v.name} = {v.number},\n" 547 | out += "};\n" 548 | 549 | cpp = f"#ifdef HAS_PROTO_MESSAGE_DUMP\n" 550 | cpp += f"template<> const char *proto_enum_to_string(enums::{name} value) {{\n" 551 | cpp += f" switch (value) {{\n" 552 | for v in desc.value: 553 | cpp += f" case enums::{v.name}:\n" 554 | cpp += f' return "{v.name}";\n' 555 | cpp += f" default:\n" 556 | cpp += f' return "UNKNOWN";\n' 557 | cpp += f" }}\n" 558 | cpp += f"}}\n" 559 | cpp += f"#endif\n" 560 | 561 | return out, cpp 562 | 563 | 564 | def build_message_type(desc): 565 | public_content = [] 566 | protected_content = [] 567 | decode_varint = [] 568 | decode_length = [] 569 | decode_32bit = [] 570 | decode_64bit = [] 571 | encode = [] 572 | dump = [] 573 | 574 | for field in desc.field: 575 | if field.label == 3: 576 | ti = RepeatedTypeInfo(field) 577 | else: 578 | ti = TYPE_INFO[field.type](field) 579 | protected_content.extend(ti.protected_content) 580 | public_content.extend(ti.public_content) 581 | encode.append(ti.encode_content) 582 | 583 | if ti.decode_varint_content: 584 | decode_varint.append(ti.decode_varint_content) 585 | if ti.decode_length_content: 586 | decode_length.append(ti.decode_length_content) 587 | if ti.decode_32bit_content: 588 | decode_32bit.append(ti.decode_32bit_content) 589 | if ti.decode_64bit_content: 590 | decode_64bit.append(ti.decode_64bit_content) 591 | if ti.dump_content: 592 | dump.append(ti.dump_content) 593 | 594 | cpp = "" 595 | if decode_varint: 596 | decode_varint.append("default:\n return false;") 597 | o = f"bool {desc.name}::decode_varint(uint32_t field_id, ProtoVarInt value) {{\n" 598 | o += " switch (field_id) {\n" 599 | o += indent("\n".join(decode_varint), " ") + "\n" 600 | o += " }\n" 601 | o += "}\n" 602 | cpp += o 603 | prot = "bool decode_varint(uint32_t field_id, ProtoVarInt value) override;" 604 | protected_content.insert(0, prot) 605 | if decode_length: 606 | decode_length.append("default:\n return false;") 607 | o = f"bool {desc.name}::decode_length(uint32_t field_id, ProtoLengthDelimited value) {{\n" 608 | o += " switch (field_id) {\n" 609 | o += indent("\n".join(decode_length), " ") + "\n" 610 | o += " }\n" 611 | o += "}\n" 612 | cpp += o 613 | prot = "bool decode_length(uint32_t field_id, ProtoLengthDelimited value) override;" 614 | protected_content.insert(0, prot) 615 | if decode_32bit: 616 | decode_32bit.append("default:\n return false;") 617 | o = f"bool {desc.name}::decode_32bit(uint32_t field_id, Proto32Bit value) {{\n" 618 | o += " switch (field_id) {\n" 619 | o += indent("\n".join(decode_32bit), " ") + "\n" 620 | o += " }\n" 621 | o += "}\n" 622 | cpp += o 623 | prot = "bool decode_32bit(uint32_t field_id, Proto32Bit value) override;" 624 | protected_content.insert(0, prot) 625 | if decode_64bit: 626 | decode_64bit.append("default:\n return false;") 627 | o = f"bool {desc.name}::decode_64bit(uint32_t field_id, Proto64Bit value) {{\n" 628 | o += " switch (field_id) {\n" 629 | o += indent("\n".join(decode_64bit), " ") + "\n" 630 | o += " }\n" 631 | o += "}\n" 632 | cpp += o 633 | prot = "bool decode_64bit(uint32_t field_id, Proto64Bit value) override;" 634 | protected_content.insert(0, prot) 635 | 636 | o = f"void {desc.name}::encode(ProtoWriteBuffer buffer) const {{" 637 | if encode: 638 | if len(encode) == 1 and len(encode[0]) + len(o) + 3 < 120: 639 | o += f" {encode[0]} " 640 | else: 641 | o += "\n" 642 | o += indent("\n".join(encode)) + "\n" 643 | o += "}\n" 644 | cpp += o 645 | prot = "void encode(ProtoWriteBuffer buffer) const override;" 646 | public_content.append(prot) 647 | 648 | o = f"void {desc.name}::dump_to(std::string &out) const {{" 649 | if dump: 650 | if len(dump) == 1 and len(dump[0]) + len(o) + 3 < 120: 651 | o += f" {dump[0]} " 652 | else: 653 | o += "\n" 654 | o += f" __attribute__((unused)) char buffer[64];\n" 655 | o += f' out.append("{desc.name} {{\\n");\n' 656 | o += indent("\n".join(dump)) + "\n" 657 | o += f' out.append("}}");\n' 658 | else: 659 | o2 = f'out.append("{desc.name} {{}}");' 660 | if len(o) + len(o2) + 3 < 120: 661 | o += f" {o2} " 662 | else: 663 | o += "\n" 664 | o += f" {o2}\n" 665 | o += "}\n" 666 | cpp += f"#ifdef HAS_PROTO_MESSAGE_DUMP\n" 667 | cpp += o 668 | cpp += f"#endif\n" 669 | prot = "#ifdef HAS_PROTO_MESSAGE_DUMP\n" 670 | prot += "void dump_to(std::string &out) const override;\n" 671 | prot += "#endif\n" 672 | public_content.append(prot) 673 | 674 | out = f"class {desc.name} : public ProtoMessage {{\n" 675 | out += " public:\n" 676 | out += indent("\n".join(public_content)) + "\n" 677 | out += "\n" 678 | out += " protected:\n" 679 | out += indent("\n".join(protected_content)) 680 | if len(protected_content) > 0: 681 | out += "\n" 682 | out += "};\n" 683 | return out, cpp 684 | 685 | 686 | file = d.file[0] 687 | content = file_header 688 | content += """\ 689 | #pragma once 690 | 691 | #include "proto.h" 692 | 693 | namespace esphome { 694 | namespace api { 695 | 696 | """ 697 | 698 | cpp = file_header 699 | cpp += """\ 700 | #include "api_pb2.h" 701 | #include "esphome/core/log.h" 702 | 703 | namespace esphome { 704 | namespace api { 705 | 706 | """ 707 | 708 | content += "namespace enums {\n\n" 709 | 710 | for enum in file.enum_type: 711 | s, c = build_enum_type(enum) 712 | content += s 713 | cpp += c 714 | 715 | content += "\n} // namespace enums\n\n" 716 | 717 | mt = file.message_type 718 | 719 | for m in mt: 720 | s, c = build_message_type(m) 721 | content += s 722 | cpp += c 723 | 724 | content += """\ 725 | 726 | } // namespace api 727 | } // namespace esphome 728 | """ 729 | cpp += """\ 730 | 731 | } // namespace api 732 | } // namespace esphome 733 | """ 734 | 735 | with open(root / "api_pb2.h", "w") as f: 736 | f.write(content) 737 | 738 | with open(root / "api_pb2.cpp", "w") as f: 739 | f.write(cpp) 740 | 741 | SOURCE_BOTH = 0 742 | SOURCE_SERVER = 1 743 | SOURCE_CLIENT = 2 744 | 745 | RECEIVE_CASES = {} 746 | 747 | class_name = "APIServerConnectionBase" 748 | 749 | ifdefs = {} 750 | 751 | 752 | def get_opt(desc, opt, default=None): 753 | if not desc.options.HasExtension(opt): 754 | return default 755 | return desc.options.Extensions[opt] 756 | 757 | 758 | def build_service_message_type(mt): 759 | snake = camel_to_snake(mt.name) 760 | id_ = get_opt(mt, pb.id) 761 | if id_ is None: 762 | return None 763 | 764 | source = get_opt(mt, pb.source, 0) 765 | 766 | ifdef = get_opt(mt, pb.ifdef) 767 | log = get_opt(mt, pb.log, True) 768 | nodelay = get_opt(mt, pb.no_delay, False) 769 | hout = "" 770 | cout = "" 771 | 772 | if ifdef is not None: 773 | ifdefs[str(mt.name)] = ifdef 774 | hout += f"#ifdef {ifdef}\n" 775 | cout += f"#ifdef {ifdef}\n" 776 | 777 | if source in (SOURCE_BOTH, SOURCE_SERVER): 778 | # Generate send 779 | func = f"send_{snake}" 780 | hout += f"bool {func}(const {mt.name} &msg);\n" 781 | cout += f"bool {class_name}::{func}(const {mt.name} &msg) {{\n" 782 | if log: 783 | cout += f"#ifdef HAS_PROTO_MESSAGE_DUMP\n" 784 | cout += f' ESP_LOGVV(TAG, "{func}: %s", msg.dump().c_str());\n' 785 | cout += f"#endif\n" 786 | # cout += f' this->set_nodelay({str(nodelay).lower()});\n' 787 | cout += f" return this->send_message_<{mt.name}>(msg, {id_});\n" 788 | cout += f"}}\n" 789 | if source in (SOURCE_BOTH, SOURCE_CLIENT): 790 | # Generate receive 791 | func = f"on_{snake}" 792 | hout += f"virtual void {func}(const {mt.name} &value){{}};\n" 793 | case = "" 794 | if ifdef is not None: 795 | case += f"#ifdef {ifdef}\n" 796 | case += f"{mt.name} msg;\n" 797 | case += f"msg.decode(msg_data, msg_size);\n" 798 | if log: 799 | case += f"#ifdef HAS_PROTO_MESSAGE_DUMP\n" 800 | case += f'ESP_LOGVV(TAG, "{func}: %s", msg.dump().c_str());\n' 801 | case += f"#endif\n" 802 | case += f"this->{func}(msg);\n" 803 | if ifdef is not None: 804 | case += f"#endif\n" 805 | case += "break;" 806 | RECEIVE_CASES[id_] = case 807 | 808 | if ifdef is not None: 809 | hout += f"#endif\n" 810 | cout += f"#endif\n" 811 | 812 | return hout, cout 813 | 814 | 815 | hpp = file_header 816 | hpp += """\ 817 | #pragma once 818 | 819 | #include "api_pb2.h" 820 | #include "esphome/core/defines.h" 821 | 822 | namespace esphome { 823 | namespace api { 824 | 825 | """ 826 | 827 | cpp = file_header 828 | cpp += """\ 829 | #include "api_pb2_service.h" 830 | #include "esphome/core/log.h" 831 | 832 | namespace esphome { 833 | namespace api { 834 | 835 | static const char *const TAG = "api.service"; 836 | 837 | """ 838 | 839 | hpp += f"class {class_name} : public ProtoService {{\n" 840 | hpp += " public:\n" 841 | 842 | for mt in file.message_type: 843 | obj = build_service_message_type(mt) 844 | if obj is None: 845 | continue 846 | hout, cout = obj 847 | hpp += indent(hout) + "\n" 848 | cpp += cout 849 | 850 | cases = list(RECEIVE_CASES.items()) 851 | cases.sort() 852 | hpp += " protected:\n" 853 | hpp += f" bool read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) override;\n" 854 | out = f"bool {class_name}::read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) {{\n" 855 | out += f" switch (msg_type) {{\n" 856 | for i, case in cases: 857 | c = f"case {i}: {{\n" 858 | c += indent(case) + "\n" 859 | c += f"}}" 860 | out += indent(c, " ") + "\n" 861 | out += " default:\n" 862 | out += " return false;\n" 863 | out += " }\n" 864 | out += " return true;\n" 865 | out += "}\n" 866 | cpp += out 867 | hpp += "};\n" 868 | 869 | serv = file.service[0] 870 | class_name = "APIServerConnection" 871 | hpp += "\n" 872 | hpp += f"class {class_name} : public {class_name}Base {{\n" 873 | hpp += " public:\n" 874 | hpp_protected = "" 875 | cpp += "\n" 876 | 877 | m = serv.method[0] 878 | for m in serv.method: 879 | func = m.name 880 | inp = m.input_type[1:] 881 | ret = m.output_type[1:] 882 | is_void = ret == "void" 883 | snake = camel_to_snake(inp) 884 | on_func = f"on_{snake}" 885 | needs_conn = get_opt(m, pb.needs_setup_connection, True) 886 | needs_auth = get_opt(m, pb.needs_authentication, True) 887 | 888 | ifdef = ifdefs.get(inp, None) 889 | 890 | if ifdef is not None: 891 | hpp += f"#ifdef {ifdef}\n" 892 | hpp_protected += f"#ifdef {ifdef}\n" 893 | cpp += f"#ifdef {ifdef}\n" 894 | 895 | hpp_protected += f" void {on_func}(const {inp} &msg) override;\n" 896 | hpp += f" virtual {ret} {func}(const {inp} &msg) = 0;\n" 897 | cpp += f"void {class_name}::{on_func}(const {inp} &msg) {{\n" 898 | body = "" 899 | if needs_conn: 900 | body += "if (!this->is_connection_setup()) {\n" 901 | body += " this->on_no_setup_connection();\n" 902 | body += " return;\n" 903 | body += "}\n" 904 | if needs_auth: 905 | body += "if (!this->is_authenticated()) {\n" 906 | body += " this->on_unauthenticated_access();\n" 907 | body += " return;\n" 908 | body += "}\n" 909 | 910 | if is_void: 911 | body += f"this->{func}(msg);\n" 912 | else: 913 | body += f"{ret} ret = this->{func}(msg);\n" 914 | ret_snake = camel_to_snake(ret) 915 | body += f"if (!this->send_{ret_snake}(ret)) {{\n" 916 | body += f" this->on_fatal_error();\n" 917 | body += "}\n" 918 | cpp += indent(body) + "\n" + "}\n" 919 | 920 | if ifdef is not None: 921 | hpp += f"#endif\n" 922 | hpp_protected += f"#endif\n" 923 | cpp += f"#endif\n" 924 | 925 | hpp += " protected:\n" 926 | hpp += hpp_protected 927 | hpp += "};\n" 928 | 929 | hpp += """\ 930 | 931 | } // namespace api 932 | } // namespace esphome 933 | """ 934 | cpp += """\ 935 | 936 | } // namespace api 937 | } // namespace esphome 938 | """ 939 | 940 | with open(root / "api_pb2_service.h", "w") as f: 941 | f.write(hpp) 942 | 943 | with open(root / "api_pb2_service.cpp", "w") as f: 944 | f.write(cpp) 945 | 946 | prot.unlink() 947 | -------------------------------------------------------------------------------- /script/build_language_schema.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import json 3 | import argparse 4 | import os 5 | import glob 6 | import re 7 | import voluptuous as vol 8 | 9 | # NOTE: Cannot import other esphome components globally as a modification in vol_schema 10 | # is needed before modules are loaded 11 | import esphome.schema_extractors as ejs 12 | 13 | ejs.EnableSchemaExtraction = True 14 | 15 | # schema format: 16 | # Schemas are split in several files in json format, one for core stuff, one for each platform (sensor, binary_sensor, etc) and 17 | # one for each component (dallas, sim800l, etc.) component can have schema for root component/hub and also for platform component, 18 | # e.g. dallas has hub component which has pin and then has the sensor platform which has sensor name, index, etc. 19 | # When files are loaded they are merged in a single object. 20 | # The root format is 21 | 22 | S_CONFIG_VAR = "config_var" 23 | S_CONFIG_VARS = "config_vars" 24 | S_CONFIG_SCHEMA = "CONFIG_SCHEMA" 25 | S_COMPONENT = "component" 26 | S_COMPONENTS = "components" 27 | S_PLATFORMS = "platforms" 28 | S_SCHEMA = "schema" 29 | S_SCHEMAS = "schemas" 30 | S_EXTENDS = "extends" 31 | S_TYPE = "type" 32 | S_NAME = "name" 33 | 34 | parser = argparse.ArgumentParser() 35 | parser.add_argument( 36 | "--output-path", default=".", help="Output path", type=os.path.abspath 37 | ) 38 | 39 | args = parser.parse_args() 40 | 41 | DUMP_RAW = False 42 | DUMP_UNKNOWN = False 43 | DUMP_PATH = False 44 | JSON_DUMP_PRETTY = True 45 | 46 | # store here dynamic load of esphome components 47 | components = {} 48 | 49 | schema_core = {} 50 | 51 | # output is where all is built 52 | output = {"core": schema_core} 53 | # The full generated output is here here 54 | schema_full = {"components": output} 55 | 56 | # A string, string map, key is the str(schema) and value is 57 | # a tuple, first element is the schema reference and second is the schema path given, the schema reference is needed to test as different schemas have same key 58 | known_schemas = {} 59 | 60 | solve_registry = [] 61 | 62 | 63 | def get_component_names(): 64 | from esphome.loader import CORE_COMPONENTS_PATH 65 | 66 | component_names = ["esphome", "sensor"] 67 | 68 | for d in os.listdir(CORE_COMPONENTS_PATH): 69 | if not d.startswith("__") and os.path.isdir( 70 | os.path.join(CORE_COMPONENTS_PATH, d) 71 | ): 72 | if d not in component_names: 73 | component_names.append(d) 74 | 75 | return component_names 76 | 77 | 78 | def load_components(): 79 | from esphome.config import get_component 80 | 81 | for domain in get_component_names(): 82 | components[domain] = get_component(domain) 83 | 84 | 85 | load_components() 86 | 87 | # Import esphome after loading components (so schema is tracked) 88 | # pylint: disable=wrong-import-position 89 | import esphome.core as esphome_core 90 | import esphome.config_validation as cv 91 | from esphome import automation 92 | from esphome import pins 93 | from esphome.components import remote_base 94 | from esphome.const import CONF_TYPE 95 | from esphome.loader import get_platform, CORE_COMPONENTS_PATH 96 | from esphome.helpers import write_file_if_changed 97 | from esphome.util import Registry 98 | 99 | # pylint: enable=wrong-import-position 100 | 101 | 102 | def write_file(name, obj): 103 | full_path = os.path.join(args.output_path, name + ".json") 104 | if JSON_DUMP_PRETTY: 105 | json_str = json.dumps(obj, indent=2) 106 | else: 107 | json_str = json.dumps(obj, separators=(",", ":")) 108 | write_file_if_changed(full_path, json_str) 109 | print(f"Wrote {full_path}") 110 | 111 | 112 | def register_module_schemas(key, module, manifest=None): 113 | for name, schema in module_schemas(module): 114 | register_known_schema(key, name, schema) 115 | 116 | if manifest: 117 | # Multi conf should allow list of components 118 | # not sure about 2nd part of the if, might be useless config (e.g. as3935) 119 | if manifest.multi_conf and S_CONFIG_SCHEMA in output[key][S_SCHEMAS]: 120 | output[key][S_SCHEMAS][S_CONFIG_SCHEMA]["is_list"] = True 121 | 122 | 123 | def register_known_schema(module, name, schema): 124 | if module not in output: 125 | output[module] = {S_SCHEMAS: {}} 126 | config = convert_config(schema, f"{module}/{name}") 127 | if S_TYPE not in config: 128 | print(f"Config var without type: {module}.{name}") 129 | 130 | output[module][S_SCHEMAS][name] = config 131 | repr_schema = repr(schema) 132 | if repr_schema in known_schemas: 133 | schema_info = known_schemas[repr_schema] 134 | schema_info.append((schema, f"{module}.{name}")) 135 | else: 136 | known_schemas[repr_schema] = [(schema, f"{module}.{name}")] 137 | 138 | 139 | def module_schemas(module): 140 | # This should yield elements in order so extended schemas are resolved properly 141 | # To do this we check on the source code where the symbol is seen first. Seems to work. 142 | try: 143 | module_str = inspect.getsource(module) 144 | except TypeError: 145 | # improv 146 | module_str = "" 147 | except OSError: 148 | # some empty __init__ files 149 | module_str = "" 150 | schemas = {} 151 | for m_attr_name in dir(module): 152 | m_attr_obj = getattr(module, m_attr_name) 153 | if isConvertibleSchema(m_attr_obj): 154 | schemas[module_str.find(m_attr_name)] = [m_attr_name, m_attr_obj] 155 | 156 | for pos in sorted(schemas.keys()): 157 | yield schemas[pos] 158 | 159 | 160 | found_registries = {} 161 | 162 | # Pin validators keys are the functions in pin which validate the pins 163 | pin_validators = {} 164 | 165 | 166 | def add_pin_validators(): 167 | for m_attr_name in dir(pins): 168 | if "gpio" in m_attr_name: 169 | s = pin_validators[repr(getattr(pins, m_attr_name))] = {} 170 | if "schema" in m_attr_name: 171 | s["schema"] = True # else is just number 172 | if "internal" in m_attr_name: 173 | s["internal"] = True 174 | if "input" in m_attr_name: 175 | s["modes"] = ["input"] 176 | elif "output" in m_attr_name: 177 | s["modes"] = ["output"] 178 | else: 179 | s["modes"] = [] 180 | if "pullup" in m_attr_name: 181 | s["modes"].append("pullup") 182 | from esphome.components.adc import sensor as adc_sensor 183 | 184 | pin_validators[repr(adc_sensor.validate_adc_pin)] = { 185 | "internal": True, 186 | "modes": ["input"], 187 | } 188 | 189 | 190 | def add_module_registries(domain, module): 191 | for attr_name in dir(module): 192 | attr_obj = getattr(module, attr_name) 193 | if isinstance(attr_obj, Registry): 194 | if attr_obj == automation.ACTION_REGISTRY: 195 | reg_type = "action" 196 | reg_domain = "core" 197 | found_registries[repr(attr_obj)] = reg_type 198 | elif attr_obj == automation.CONDITION_REGISTRY: 199 | reg_type = "condition" 200 | reg_domain = "core" 201 | found_registries[repr(attr_obj)] = reg_type 202 | else: # attr_name == "FILTER_REGISTRY": 203 | reg_domain = domain 204 | reg_type = attr_name.partition("_")[0].lower() 205 | found_registries[repr(attr_obj)] = f"{domain}.{reg_type}" 206 | 207 | for name in attr_obj.keys(): 208 | if "." not in name: 209 | reg_entry_name = name 210 | else: 211 | parts = name.split(".") 212 | if len(parts) == 2: 213 | reg_domain = parts[0] 214 | reg_entry_name = parts[1] 215 | else: 216 | reg_domain = ".".join([parts[1], parts[0]]) 217 | reg_entry_name = parts[2] 218 | 219 | if reg_domain not in output: 220 | output[reg_domain] = {} 221 | if reg_type not in output[reg_domain]: 222 | output[reg_domain][reg_type] = {} 223 | output[reg_domain][reg_type][reg_entry_name] = convert_config( 224 | attr_obj[name].schema, f"{reg_domain}/{reg_type}/{reg_entry_name}" 225 | ) 226 | 227 | # print(f"{domain} - {attr_name} - {name}") 228 | 229 | 230 | def do_pins(): 231 | # do pin registries 232 | pins_providers = schema_core["pins"] = [] 233 | for pin_registry in pins.PIN_SCHEMA_REGISTRY: 234 | s = convert_config( 235 | pins.PIN_SCHEMA_REGISTRY[pin_registry][1], f"pins/{pin_registry}" 236 | ) 237 | if pin_registry not in output: 238 | output[pin_registry] = {} # mcp23xxx does not create a component yet 239 | output[pin_registry]["pin"] = s 240 | pins_providers.append(pin_registry) 241 | 242 | 243 | def do_esp32(): 244 | import esphome.components.esp32.boards as esp32_boards 245 | 246 | setEnum( 247 | output["esp32"]["schemas"]["CONFIG_SCHEMA"]["schema"]["config_vars"]["board"], 248 | list(esp32_boards.BOARDS.keys()), 249 | ) 250 | 251 | 252 | def do_esp8266(): 253 | import esphome.components.esp8266.boards as esp8266_boards 254 | 255 | setEnum( 256 | output["esp8266"]["schemas"]["CONFIG_SCHEMA"]["schema"]["config_vars"]["board"], 257 | list(esp8266_boards.ESP8266_BOARD_PINS.keys()), 258 | ) 259 | 260 | 261 | def fix_remote_receiver(): 262 | remote_receiver_schema = output["remote_receiver.binary_sensor"]["schemas"] 263 | remote_receiver_schema["CONFIG_SCHEMA"] = { 264 | "type": "schema", 265 | "schema": { 266 | "extends": ["binary_sensor.BINARY_SENSOR_SCHEMA", "core.COMPONENT_SCHEMA"], 267 | "config_vars": output["remote_base"].pop("binary"), 268 | }, 269 | } 270 | remote_receiver_schema["CONFIG_SCHEMA"]["schema"]["config_vars"]["receiver_id"] = { 271 | "key": "GeneratedID", 272 | "use_id_type": "remote_base::RemoteReceiverBase", 273 | "type": "use_id", 274 | } 275 | 276 | 277 | def fix_script(): 278 | output["script"][S_SCHEMAS][S_CONFIG_SCHEMA][S_TYPE] = S_SCHEMA 279 | config_schema = output["script"][S_SCHEMAS][S_CONFIG_SCHEMA] 280 | config_schema[S_SCHEMA][S_CONFIG_VARS]["id"]["id_type"] = { 281 | "class": "script::Script" 282 | } 283 | config_schema["is_list"] = True 284 | 285 | 286 | def fix_menu(): 287 | # # Menu has a recursive schema which is not kept properly 288 | schemas = output["display_menu_base"][S_SCHEMAS] 289 | # 1. Move items to a new schema 290 | schemas["MENU_TYPES"] = { 291 | S_TYPE: S_SCHEMA, 292 | S_SCHEMA: { 293 | S_CONFIG_VARS: { 294 | "items": schemas["DISPLAY_MENU_BASE_SCHEMA"][S_SCHEMA][S_CONFIG_VARS][ 295 | "items" 296 | ] 297 | } 298 | }, 299 | } 300 | # 2. Remove items from the base schema 301 | schemas["DISPLAY_MENU_BASE_SCHEMA"][S_SCHEMA][S_CONFIG_VARS].pop("items") 302 | # 3. Add extends to this 303 | schemas["DISPLAY_MENU_BASE_SCHEMA"][S_SCHEMA][S_EXTENDS].append( 304 | "display_menu_base.MENU_TYPES" 305 | ) 306 | # 4. Configure menu items inside as recursive 307 | menu = schemas["MENU_TYPES"][S_SCHEMA][S_CONFIG_VARS]["items"]["types"]["menu"] 308 | menu[S_CONFIG_VARS].pop("items") 309 | menu[S_EXTENDS] = ["display_menu_base.MENU_TYPES"] 310 | 311 | 312 | def get_logger_tags(): 313 | pattern = re.compile(r'^static const char \*const TAG = "(\w.*)";', re.MULTILINE) 314 | # tags not in components dir 315 | tags = [ 316 | "app", 317 | "component", 318 | "entity_base", 319 | "scheduler", 320 | "api.service", 321 | ] 322 | for x in os.walk(CORE_COMPONENTS_PATH): 323 | for y in glob.glob(os.path.join(x[0], "*.cpp")): 324 | with open(y, encoding="utf-8") as file: 325 | data = file.read() 326 | match = pattern.search(data) 327 | if match: 328 | tags.append(match.group(1)) 329 | return tags 330 | 331 | 332 | def add_logger_tags(): 333 | tags = get_logger_tags() 334 | logs = output["logger"]["schemas"]["CONFIG_SCHEMA"]["schema"]["config_vars"][ 335 | "logs" 336 | ]["schema"]["config_vars"] 337 | for t in tags: 338 | logs[t] = logs["string"].copy() 339 | logs.pop("string") 340 | 341 | 342 | def add_referenced_recursive(referenced_schemas, config_var, path, eat_schema=False): 343 | assert ( 344 | S_CONFIG_VARS not in config_var and S_EXTENDS not in config_var 345 | ) # S_TYPE in cv or "key" in cv or len(cv) == 0 346 | if ( 347 | config_var.get(S_TYPE) in ["schema", "trigger", "maybe"] 348 | and S_SCHEMA in config_var 349 | ): 350 | schema = config_var[S_SCHEMA] 351 | for k, v in schema.get(S_CONFIG_VARS, {}).items(): 352 | if eat_schema: 353 | new_path = path + [S_CONFIG_VARS, k] 354 | else: 355 | new_path = path + ["schema", S_CONFIG_VARS, k] 356 | add_referenced_recursive(referenced_schemas, v, new_path) 357 | for k in schema.get(S_EXTENDS, []): 358 | if k not in referenced_schemas: 359 | referenced_schemas[k] = [path] 360 | else: 361 | if path not in referenced_schemas[k]: 362 | referenced_schemas[k].append(path) 363 | 364 | s1 = get_str_path_schema(k) 365 | p = k.split(".") 366 | if len(p) == 3 and path[0] == f"{p[0]}.{p[1]}": 367 | # special case for schema inside platforms 368 | add_referenced_recursive( 369 | referenced_schemas, s1, [path[0], "schemas", p[2]] 370 | ) 371 | else: 372 | add_referenced_recursive( 373 | referenced_schemas, s1, [p[0], "schemas", p[1]] 374 | ) 375 | elif config_var.get(S_TYPE) == "typed": 376 | for tk, tv in config_var.get("types").items(): 377 | add_referenced_recursive( 378 | referenced_schemas, 379 | { 380 | S_TYPE: S_SCHEMA, 381 | S_SCHEMA: tv, 382 | }, 383 | path + ["types", tk], 384 | eat_schema=True, 385 | ) 386 | 387 | 388 | def get_str_path_schema(strPath): 389 | parts = strPath.split(".") 390 | if len(parts) > 2: 391 | parts[0] += "." + parts[1] 392 | parts[1] = parts[2] 393 | s1 = output.get(parts[0], {}).get(S_SCHEMAS, {}).get(parts[1], {}) 394 | return s1 395 | 396 | 397 | def pop_str_path_schema(strPath): 398 | parts = strPath.split(".") 399 | if len(parts) > 2: 400 | parts[0] += "." + parts[1] 401 | parts[1] = parts[2] 402 | output.get(parts[0], {}).get(S_SCHEMAS, {}).pop(parts[1]) 403 | 404 | 405 | def get_arr_path_schema(path): 406 | s = output 407 | for x in path: 408 | s = s[x] 409 | return s 410 | 411 | 412 | def merge(source, destination): 413 | """ 414 | run me with nosetests --with-doctest file.py 415 | 416 | >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } } 417 | >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } } 418 | >>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } } 419 | True 420 | """ 421 | for key, value in source.items(): 422 | if isinstance(value, dict): 423 | # get node or create one 424 | node = destination.setdefault(key, {}) 425 | merge(value, node) 426 | else: 427 | destination[key] = value 428 | 429 | return destination 430 | 431 | 432 | def shrink(): 433 | """Shrink the extending schemas which has just an end type, e.g. at this point 434 | ota / port is type schema with extended pointing to core.port, this should instead be 435 | type number. core.port is number 436 | 437 | This also fixes enums, as they are another schema and they are instead put in the same cv 438 | """ 439 | 440 | # referenced_schemas contains a dict, keys are all that are shown in extends: [] arrays, values are lists of paths that are pointing to that extend 441 | # e.g. key: core.COMPONENT_SCHEMA has a lot of paths of config vars which extends this schema 442 | 443 | pass_again = True 444 | 445 | while pass_again: 446 | pass_again = False 447 | 448 | referenced_schemas = {} 449 | 450 | for k, v in output.items(): 451 | for kv, vv in v.items(): 452 | if kv != "pin" and isinstance(vv, dict): 453 | for kvv, vvv in vv.items(): 454 | add_referenced_recursive(referenced_schemas, vvv, [k, kv, kvv]) 455 | 456 | for x, paths in referenced_schemas.items(): 457 | if len(paths) == 1: 458 | key_s = get_str_path_schema(x) 459 | arr_s = get_arr_path_schema(paths[0]) 460 | # key_s |= arr_s 461 | # key_s.pop(S_EXTENDS) 462 | pass_again = True 463 | if S_SCHEMA in arr_s: 464 | if S_EXTENDS in arr_s[S_SCHEMA]: 465 | arr_s[S_SCHEMA].pop(S_EXTENDS) 466 | else: 467 | print("expected extends here!" + x) 468 | arr_s = merge(key_s, arr_s) 469 | if arr_s[S_TYPE] in ["enum", "typed"]: 470 | arr_s.pop(S_SCHEMA) 471 | else: 472 | arr_s.pop(S_EXTENDS) 473 | arr_s |= key_s[S_SCHEMA] 474 | print(x) 475 | 476 | # simple types should be spread on each component, 477 | # for enums so far these are logger.is_log_level, cover.validate_cover_state and pulse_counter.sensor.COUNT_MODE_SCHEMA 478 | # then for some reasons sensor filter registry falls here 479 | # then are all simple types, integer and strings 480 | for x, paths in referenced_schemas.items(): 481 | key_s = get_str_path_schema(x) 482 | if key_s and key_s[S_TYPE] in ["enum", "registry", "integer", "string"]: 483 | if key_s[S_TYPE] == "registry": 484 | print("Spreading registry: " + x) 485 | for target in paths: 486 | target_s = get_arr_path_schema(target) 487 | assert target_s[S_SCHEMA][S_EXTENDS] == [x] 488 | target_s.pop(S_SCHEMA) 489 | target_s |= key_s 490 | if key_s[S_TYPE] in ["integer", "string"]: 491 | target_s["data_type"] = x.split(".")[1] 492 | # remove this dangling again 493 | pop_str_path_schema(x) 494 | elif not key_s: 495 | for target in paths: 496 | target_s = get_arr_path_schema(target) 497 | assert target_s[S_SCHEMA][S_EXTENDS] == [x] 498 | target_s.pop(S_SCHEMA) 499 | target_s.pop(S_TYPE) # undefined 500 | target_s["data_type"] = x.split(".")[1] 501 | # remove this dangling again 502 | pop_str_path_schema(x) 503 | 504 | # remove dangling items (unreachable schemas) 505 | for domain, domain_schemas in output.items(): 506 | for schema_name in list(domain_schemas.get(S_SCHEMAS, {}).keys()): 507 | s = f"{domain}.{schema_name}" 508 | if ( 509 | not s.endswith("." + S_CONFIG_SCHEMA) 510 | and s not in referenced_schemas.keys() 511 | ): 512 | print(f"Removing {s}") 513 | output[domain][S_SCHEMAS].pop(schema_name) 514 | 515 | 516 | def build_schema(): 517 | print("Building schema") 518 | 519 | # check esphome was not loaded globally (IDE auto imports) 520 | if len(ejs.extended_schemas) == 0: 521 | raise Exception( 522 | "no data collected. Did you globally import an ESPHome component?" 523 | ) 524 | 525 | # Core schema 526 | schema_core[S_SCHEMAS] = {} 527 | register_module_schemas("core", cv) 528 | 529 | platforms = {} 530 | schema_core[S_PLATFORMS] = platforms 531 | core_components = {} 532 | schema_core[S_COMPONENTS] = core_components 533 | 534 | add_pin_validators() 535 | 536 | # Load a preview of each component 537 | for domain, manifest in components.items(): 538 | if manifest.is_platform_component: 539 | # e.g. sensor, binary sensor, add S_COMPONENTS 540 | # note: S_COMPONENTS is not filled until loaded, e.g. 541 | # if lock: is not used, then we don't need to know about their 542 | # platforms yet. 543 | output[domain] = {S_COMPONENTS: {}, S_SCHEMAS: {}} 544 | platforms[domain] = {} 545 | elif manifest.config_schema is not None: 546 | # e.g. dallas 547 | output[domain] = {S_SCHEMAS: {S_CONFIG_SCHEMA: {}}} 548 | 549 | # Generate platforms (e.g. sensor, binary_sensor, climate ) 550 | for domain in platforms: 551 | c = components[domain] 552 | register_module_schemas(domain, c.module) 553 | 554 | # Generate components 555 | for domain, manifest in components.items(): 556 | if domain not in platforms: 557 | if manifest.config_schema is not None: 558 | core_components[domain] = {} 559 | if len(manifest.dependencies) > 0: 560 | core_components[domain]["dependencies"] = manifest.dependencies 561 | register_module_schemas(domain, manifest.module, manifest) 562 | 563 | for platform in platforms: 564 | platform_manifest = get_platform(domain=platform, platform=domain) 565 | if platform_manifest is not None: 566 | output[platform][S_COMPONENTS][domain] = {} 567 | if len(platform_manifest.dependencies) > 0: 568 | output[platform][S_COMPONENTS][domain][ 569 | "dependencies" 570 | ] = platform_manifest.dependencies 571 | register_module_schemas( 572 | f"{domain}.{platform}", platform_manifest.module, platform_manifest 573 | ) 574 | 575 | # Do registries 576 | add_module_registries("core", automation) 577 | for domain, manifest in components.items(): 578 | add_module_registries(domain, manifest.module) 579 | add_module_registries("remote_base", remote_base) 580 | 581 | # update props pointing to registries 582 | for reg_config_var in solve_registry: 583 | (registry, config_var) = reg_config_var 584 | config_var[S_TYPE] = "registry" 585 | config_var["registry"] = found_registries[repr(registry)] 586 | 587 | do_pins() 588 | do_esp8266() 589 | do_esp32() 590 | fix_remote_receiver() 591 | fix_script() 592 | add_logger_tags() 593 | shrink() 594 | fix_menu() 595 | 596 | # aggregate components, so all component info is in same file, otherwise we have dallas.json, dallas.sensor.json, etc. 597 | data = {} 598 | for component, component_schemas in output.items(): 599 | if "." in component: 600 | key = component.partition(".")[0] 601 | if key not in data: 602 | data[key] = {} 603 | data[key][component] = component_schemas 604 | else: 605 | if component not in data: 606 | data[component] = {} 607 | data[component] |= {component: component_schemas} 608 | 609 | # bundle core inside esphome 610 | data["esphome"]["core"] = data.pop("core")["core"] 611 | 612 | for c, s in data.items(): 613 | write_file(c, s) 614 | 615 | 616 | def setEnum(obj, items): 617 | obj[S_TYPE] = "enum" 618 | obj["values"] = items 619 | 620 | 621 | def isConvertibleSchema(schema): 622 | if schema is None: 623 | return False 624 | if isinstance(schema, (cv.Schema, cv.All)): 625 | return True 626 | if repr(schema) in ejs.hidden_schemas: 627 | return True 628 | if repr(schema) in ejs.typed_schemas: 629 | return True 630 | if repr(schema) in ejs.list_schemas: 631 | return True 632 | if repr(schema) in ejs.registry_schemas: 633 | return True 634 | if isinstance(schema, dict): 635 | for k in schema.keys(): 636 | if isinstance(k, (cv.Required, cv.Optional)): 637 | return True 638 | return False 639 | 640 | 641 | def convert_config(schema, path): 642 | converted = {} 643 | convert_1(schema, converted, path) 644 | return converted 645 | 646 | 647 | def convert_1(schema, config_var, path): 648 | """config_var can be a config_var or a schema: both are dicts 649 | config_var has a S_TYPE property, if this is S_SCHEMA, then it has a S_SCHEMA property 650 | schema does not have a type property, schema can have optionally both S_CONFIG_VARS and S_EXTENDS 651 | """ 652 | repr_schema = repr(schema) 653 | 654 | if repr_schema in known_schemas: 655 | schema_info = known_schemas[(repr_schema)] 656 | for (schema_instance, name) in schema_info: 657 | if schema_instance is schema: 658 | assert S_CONFIG_VARS not in config_var 659 | assert S_EXTENDS not in config_var 660 | if not S_TYPE in config_var: 661 | config_var[S_TYPE] = S_SCHEMA 662 | # assert config_var[S_TYPE] == S_SCHEMA 663 | 664 | if S_SCHEMA not in config_var: 665 | config_var[S_SCHEMA] = {} 666 | if S_EXTENDS not in config_var[S_SCHEMA]: 667 | config_var[S_SCHEMA][S_EXTENDS] = [name] 668 | else: 669 | config_var[S_SCHEMA][S_EXTENDS].append(name) 670 | return 671 | 672 | # Extended schemas are tracked when the .extend() is used in a schema 673 | if repr_schema in ejs.extended_schemas: 674 | extended = ejs.extended_schemas.get(repr_schema) 675 | # The midea actions are extending an empty schema (resulted in the templatize not templatizing anything) 676 | # this causes a recursion in that this extended looks the same in extended schema as the extended[1] 677 | if repr_schema == repr(extended[1]): 678 | assert path.startswith("midea_ac/") 679 | return 680 | 681 | assert len(extended) == 2 682 | convert_1(extended[0], config_var, path + "/extL") 683 | convert_1(extended[1], config_var, path + "/extR") 684 | return 685 | 686 | if isinstance(schema, cv.All): 687 | i = 0 688 | for inner in schema.validators: 689 | i = i + 1 690 | convert_1(inner, config_var, path + f"/val {i}") 691 | return 692 | 693 | if hasattr(schema, "validators"): 694 | i = 0 695 | for inner in schema.validators: 696 | i = i + 1 697 | convert_1(inner, config_var, path + f"/val {i}") 698 | 699 | if isinstance(schema, cv.Schema): 700 | convert_1(schema.schema, config_var, path + "/all") 701 | return 702 | 703 | if isinstance(schema, dict): 704 | convert_keys(config_var, schema, path) 705 | return 706 | 707 | if repr_schema in ejs.list_schemas: 708 | config_var["is_list"] = True 709 | items_schema = ejs.list_schemas[repr_schema][0] 710 | convert_1(items_schema, config_var, path + "/list") 711 | return 712 | 713 | if DUMP_RAW: 714 | config_var["raw"] = repr_schema 715 | 716 | # pylint: disable=comparison-with-callable 717 | if schema == cv.boolean: 718 | config_var[S_TYPE] = "boolean" 719 | elif schema == automation.validate_potentially_and_condition: 720 | config_var[S_TYPE] = "registry" 721 | config_var["registry"] = "condition" 722 | elif schema == cv.int_ or schema == cv.int_range: 723 | config_var[S_TYPE] = "integer" 724 | elif schema == cv.string or schema == cv.string_strict or schema == cv.valid_name: 725 | config_var[S_TYPE] = "string" 726 | 727 | elif isinstance(schema, vol.Schema): 728 | # test: esphome/project 729 | config_var[S_TYPE] = "schema" 730 | config_var["schema"] = convert_config(schema.schema, path + "/s")["schema"] 731 | 732 | elif repr_schema in pin_validators: 733 | config_var |= pin_validators[repr_schema] 734 | config_var[S_TYPE] = "pin" 735 | 736 | elif repr_schema in ejs.hidden_schemas: 737 | schema_type = ejs.hidden_schemas[repr_schema] 738 | 739 | data = schema(ejs.SCHEMA_EXTRACT) 740 | 741 | # enums, e.g. esp32/variant 742 | if schema_type == "one_of": 743 | config_var[S_TYPE] = "enum" 744 | config_var["values"] = list(data) 745 | elif schema_type == "enum": 746 | config_var[S_TYPE] = "enum" 747 | config_var["values"] = list(data.keys()) 748 | elif schema_type == "maybe": 749 | config_var[S_TYPE] = S_SCHEMA 750 | config_var["maybe"] = data[1] 751 | config_var["schema"] = convert_config(data[0], path + "/maybe")["schema"] 752 | # esphome/on_boot 753 | elif schema_type == "automation": 754 | extra_schema = None 755 | config_var[S_TYPE] = "trigger" 756 | if automation.AUTOMATION_SCHEMA == ejs.extended_schemas[repr(data)][0]: 757 | extra_schema = ejs.extended_schemas[repr(data)][1] 758 | if ( 759 | extra_schema is not None and len(extra_schema) > 1 760 | ): # usually only trigger_id here 761 | config = convert_config(extra_schema, path + "/extra") 762 | if "schema" in config: 763 | automation_schema = config["schema"] 764 | if not ( 765 | len(automation_schema["config_vars"]) == 1 766 | and "trigger_id" in automation_schema["config_vars"] 767 | ): 768 | automation_schema["config_vars"]["then"] = {S_TYPE: "trigger"} 769 | if "trigger_id" in automation_schema["config_vars"]: 770 | automation_schema["config_vars"].pop("trigger_id") 771 | 772 | config_var[S_TYPE] = "trigger" 773 | config_var["schema"] = automation_schema 774 | # some triggers can have a list of actions directly, while others needs to have some other configuration, 775 | # e.g. sensor.on_value_rang, and the list of actions is only accepted under "then" property. 776 | try: 777 | schema({"delay": "1s"}) 778 | except cv.Invalid: 779 | config_var["has_required_var"] = True 780 | else: 781 | print("figure out " + path) 782 | elif schema_type == "effects": 783 | config_var[S_TYPE] = "registry" 784 | config_var["registry"] = "light.effects" 785 | config_var["filter"] = data[0] 786 | elif schema_type == "templatable": 787 | config_var["templatable"] = True 788 | convert_1(data, config_var, path + "/templat") 789 | elif schema_type == "triggers": 790 | # remote base 791 | convert_1(data, config_var, path + "/trigger") 792 | elif schema_type == "sensor": 793 | schema = data 794 | convert_1(data, config_var, path + "/trigger") 795 | elif schema_type == "declare_id": 796 | # pylint: disable=protected-access 797 | parents = data._parents 798 | 799 | config_var["id_type"] = { 800 | "class": str(data.base), 801 | "parents": [str(x.base) for x in parents] 802 | if isinstance(parents, list) 803 | else None, 804 | } 805 | elif schema_type == "use_id": 806 | if inspect.ismodule(data): 807 | m_attr_obj = getattr(data, "CONFIG_SCHEMA") 808 | use_schema = known_schemas.get(repr(m_attr_obj)) 809 | if use_schema: 810 | [output_module, output_name] = use_schema[0][1].split(".") 811 | use_id_config = output[output_module][S_SCHEMAS][output_name] 812 | config_var["use_id_type"] = use_id_config["schema"]["config_vars"][ 813 | "id" 814 | ]["id_type"]["class"] 815 | config_var[S_TYPE] = "use_id" 816 | else: 817 | print("TODO deferred?") 818 | else: 819 | if isinstance(data, str): 820 | # TODO: Figure out why pipsolar does this 821 | config_var["use_id_type"] = data 822 | else: 823 | config_var["use_id_type"] = str(data.base) 824 | config_var[S_TYPE] = "use_id" 825 | else: 826 | raise Exception("Unknown extracted schema type") 827 | elif config_var.get("key") == "GeneratedID": 828 | if path == "i2c/CONFIG_SCHEMA/extL/all/id": 829 | config_var["id_type"] = {"class": "i2c::I2CBus", "parents": ["Component"]} 830 | elif path == "uart/CONFIG_SCHEMA/val 1/extL/all/id": 831 | config_var["id_type"] = { 832 | "class": "uart::UARTComponent", 833 | "parents": ["Component"], 834 | } 835 | elif path == "pins/esp32/val 1/id": 836 | config_var["id_type"] = "pin" 837 | else: 838 | raise Exception("Cannot determine id_type for " + path) 839 | 840 | elif repr_schema in ejs.registry_schemas: 841 | solve_registry.append((ejs.registry_schemas[repr_schema], config_var)) 842 | 843 | elif repr_schema in ejs.typed_schemas: 844 | config_var[S_TYPE] = "typed" 845 | types = config_var["types"] = {} 846 | typed_schema = ejs.typed_schemas[repr_schema] 847 | if len(typed_schema) > 1: 848 | config_var["typed_key"] = typed_schema[1].get("key", CONF_TYPE) 849 | for schema_key, schema_type in typed_schema[0][0].items(): 850 | config = convert_config(schema_type, path + "/type_" + schema_key) 851 | types[schema_key] = config["schema"] 852 | 853 | elif DUMP_UNKNOWN: 854 | if S_TYPE not in config_var: 855 | config_var["unknown"] = repr_schema 856 | 857 | if DUMP_PATH: 858 | config_var["path"] = path 859 | 860 | 861 | def get_overridden_config(key, converted): 862 | # check if the key is in any extended schema in this converted schema, i.e. 863 | # if we see a on_value_range in a dallas sensor, then this is overridden because 864 | # it is already defined in sensor 865 | assert S_CONFIG_VARS not in converted and S_EXTENDS not in converted 866 | config = converted.get(S_SCHEMA, {}) 867 | 868 | return get_overridden_key_inner(key, config, {}) 869 | 870 | 871 | def get_overridden_key_inner(key, config, ret): 872 | if S_EXTENDS not in config: 873 | return ret 874 | for s in config[S_EXTENDS]: 875 | p = s.partition(".") 876 | s1 = output.get(p[0], {}).get(S_SCHEMAS, {}).get(p[2], {}).get(S_SCHEMA) 877 | if s1: 878 | if key in s1.get(S_CONFIG_VARS, {}): 879 | for k, v in s1.get(S_CONFIG_VARS)[key].items(): 880 | if k not in ret: # keep most overridden 881 | ret[k] = v 882 | get_overridden_key_inner(key, s1, ret) 883 | 884 | return ret 885 | 886 | 887 | def convert_keys(converted, schema, path): 888 | for k, v in schema.items(): 889 | # deprecated stuff 890 | if repr(v).startswith("", str(k), re.IGNORECASE 909 | ) 910 | if key_string_match: 911 | converted["key_type"] = key_string_match.group(1) 912 | else: 913 | converted["key_type"] = str(k) 914 | 915 | esphome_core.CORE.data = { 916 | esphome_core.KEY_CORE: {esphome_core.KEY_TARGET_PLATFORM: "esp8266"} 917 | } 918 | if hasattr(k, "default") and str(k.default) != "...": 919 | default_value = k.default() 920 | if default_value is not None: 921 | result["default"] = str(default_value) 922 | 923 | # Do value 924 | convert_1(v, result, path + f"/{str(k)}") 925 | if "schema" not in converted: 926 | converted[S_TYPE] = "schema" 927 | converted["schema"] = {S_CONFIG_VARS: {}} 928 | if S_CONFIG_VARS not in converted["schema"]: 929 | converted["schema"][S_CONFIG_VARS] = {} 930 | for base_k, base_v in get_overridden_config(k, converted).items(): 931 | if base_k in result and base_v == result[base_k]: 932 | result.pop(base_k) 933 | converted["schema"][S_CONFIG_VARS][str(k)] = result 934 | if "key" in converted and converted["key"] == "String": 935 | config_vars = converted["schema"]["config_vars"] 936 | assert len(config_vars) == 1 937 | key = list(config_vars.keys())[0] 938 | assert key.startswith("<") 939 | config_vars["string"] = config_vars.pop(key) 940 | 941 | 942 | build_schema() 943 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | # ESPHome License 2 | 3 | Copyright (c) 2019 ESPHome 4 | 5 | The ESPHome License is made up of two base licenses: MIT and the GNU GENERAL PUBLIC LICENSE. 6 | The C++/runtime codebase of the ESPHome project (file extensions .c, .cpp, .h, .hpp, .tcc, .ino) are 7 | published under the GPLv3 license. The python codebase and all other parts of this codebase are 8 | published under the MIT license. 9 | 10 | Both MIT and GPLv3 licenses are attached to this document. 11 | 12 | ## MIT License 13 | 14 | Copyright (c) 2019 ESPHome 15 | 16 | Permission is hereby granted, free of charge, to any person obtaining a copy 17 | of this software and associated documentation files (the "Software"), to deal 18 | in the Software without restriction, including without limitation the rights 19 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 20 | copies of the Software, and to permit persons to whom the Software is 21 | furnished to do so, subject to the following conditions: 22 | 23 | The above copyright notice and this permission notice shall be included in all 24 | copies or substantial portions of the Software. 25 | 26 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 27 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 28 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 29 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 30 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 31 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 32 | SOFTWARE. 33 | 34 | ## GPLv3 License 35 | 36 | GNU GENERAL PUBLIC LICENSE 37 | Version 3, 29 June 2007 38 | 39 | Copyright (C) 2007 Free Software Foundation, Inc. 40 | Everyone is permitted to copy and distribute verbatim copies 41 | of this license document, but changing it is not allowed. 42 | 43 | Preamble 44 | 45 | The GNU General Public License is a free, copyleft license for 46 | software and other kinds of works. 47 | 48 | The licenses for most software and other practical works are designed 49 | to take away your freedom to share and change the works. By contrast, 50 | the GNU General Public License is intended to guarantee your freedom to 51 | share and change all versions of a program--to make sure it remains free 52 | software for all its users. We, the Free Software Foundation, use the 53 | GNU General Public License for most of our software; it applies also to 54 | any other work released this way by its authors. You can apply it to 55 | your programs, too. 56 | 57 | When we speak of free software, we are referring to freedom, not 58 | price. Our General Public Licenses are designed to make sure that you 59 | have the freedom to distribute copies of free software (and charge for 60 | them if you wish), that you receive source code or can get it if you 61 | want it, that you can change the software or use pieces of it in new 62 | free programs, and that you know you can do these things. 63 | 64 | To protect your rights, we need to prevent others from denying you 65 | these rights or asking you to surrender the rights. Therefore, you have 66 | certain responsibilities if you distribute copies of the software, or if 67 | you modify it: responsibilities to respect the freedom of others. 68 | 69 | For example, if you distribute copies of such a program, whether 70 | gratis or for a fee, you must pass on to the recipients the same 71 | freedoms that you received. You must make sure that they, too, receive 72 | or can get the source code. And you must show them these terms so they 73 | know their rights. 74 | 75 | Developers that use the GNU GPL protect your rights with two steps: 76 | (1) assert copyright on the software, and (2) offer you this License 77 | giving you legal permission to copy, distribute and/or modify it. 78 | 79 | For the developers' and authors' protection, the GPL clearly explains 80 | that there is no warranty for this free software. For both users' and 81 | authors' sake, the GPL requires that modified versions be marked as 82 | changed, so that their problems will not be attributed erroneously to 83 | authors of previous versions. 84 | 85 | Some devices are designed to deny users access to install or run 86 | modified versions of the software inside them, although the manufacturer 87 | can do so. This is fundamentally incompatible with the aim of 88 | protecting users' freedom to change the software. The systematic 89 | pattern of such abuse occurs in the area of products for individuals to 90 | use, which is precisely where it is most unacceptable. Therefore, we 91 | have designed this version of the GPL to prohibit the practice for those 92 | products. If such problems arise substantially in other domains, we 93 | stand ready to extend this provision to those domains in future versions 94 | of the GPL, as needed to protect the freedom of users. 95 | 96 | Finally, every program is threatened constantly by software patents. 97 | States should not allow patents to restrict development and use of 98 | software on general-purpose computers, but in those that do, we wish to 99 | avoid the special danger that patents applied to a free program could 100 | make it effectively proprietary. To prevent this, the GPL assures that 101 | patents cannot be used to render the program non-free. 102 | 103 | The precise terms and conditions for copying, distribution and 104 | modification follow. 105 | 106 | TERMS AND CONDITIONS 107 | 108 | 0. Definitions. 109 | 110 | "This License" refers to version 3 of the GNU General Public License. 111 | 112 | "Copyright" also means copyright-like laws that apply to other kinds of 113 | works, such as semiconductor masks. 114 | 115 | "The Program" refers to any copyrightable work licensed under this 116 | License. Each licensee is addressed as "you". "Licensees" and 117 | "recipients" may be individuals or organizations. 118 | 119 | To "modify" a work means to copy from or adapt all or part of the work 120 | in a fashion requiring copyright permission, other than the making of an 121 | exact copy. The resulting work is called a "modified version" of the 122 | earlier work or a work "based on" the earlier work. 123 | 124 | A "covered work" means either the unmodified Program or a work based 125 | on the Program. 126 | 127 | To "propagate" a work means to do anything with it that, without 128 | permission, would make you directly or secondarily liable for 129 | infringement under applicable copyright law, except executing it on a 130 | computer or modifying a private copy. Propagation includes copying, 131 | distribution (with or without modification), making available to the 132 | public, and in some countries other activities as well. 133 | 134 | To "convey" a work means any kind of propagation that enables other 135 | parties to make or receive copies. Mere interaction with a user through 136 | a computer network, with no transfer of a copy, is not conveying. 137 | 138 | An interactive user interface displays "Appropriate Legal Notices" 139 | to the extent that it includes a convenient and prominently visible 140 | feature that (1) displays an appropriate copyright notice, and (2) 141 | tells the user that there is no warranty for the work (except to the 142 | extent that warranties are provided), that licensees may convey the 143 | work under this License, and how to view a copy of this License. If 144 | the interface presents a list of user commands or options, such as a 145 | menu, a prominent item in the list meets this criterion. 146 | 147 | 1. Source Code. 148 | 149 | The "source code" for a work means the preferred form of the work 150 | for making modifications to it. "Object code" means any non-source 151 | form of a work. 152 | 153 | A "Standard Interface" means an interface that either is an official 154 | standard defined by a recognized standards body, or, in the case of 155 | interfaces specified for a particular programming language, one that 156 | is widely used among developers working in that language. 157 | 158 | The "System Libraries" of an executable work include anything, other 159 | than the work as a whole, that (a) is included in the normal form of 160 | packaging a Major Component, but which is not part of that Major 161 | Component, and (b) serves only to enable use of the work with that 162 | Major Component, or to implement a Standard Interface for which an 163 | implementation is available to the public in source code form. A 164 | "Major Component", in this context, means a major essential component 165 | (kernel, window system, and so on) of the specific operating system 166 | (if any) on which the executable work runs, or a compiler used to 167 | produce the work, or an object code interpreter used to run it. 168 | 169 | The "Corresponding Source" for a work in object code form means all 170 | the source code needed to generate, install, and (for an executable 171 | work) run the object code and to modify the work, including scripts to 172 | control those activities. However, it does not include the work's 173 | System Libraries, or general-purpose tools or generally available free 174 | programs which are used unmodified in performing those activities but 175 | which are not part of the work. For example, Corresponding Source 176 | includes interface definition files associated with source files for 177 | the work, and the source code for shared libraries and dynamically 178 | linked subprograms that the work is specifically designed to require, 179 | such as by intimate data communication or control flow between those 180 | subprograms and other parts of the work. 181 | 182 | The Corresponding Source need not include anything that users 183 | can regenerate automatically from other parts of the Corresponding 184 | Source. 185 | 186 | The Corresponding Source for a work in source code form is that 187 | same work. 188 | 189 | 2. Basic Permissions. 190 | 191 | All rights granted under this License are granted for the term of 192 | copyright on the Program, and are irrevocable provided the stated 193 | conditions are met. This License explicitly affirms your unlimited 194 | permission to run the unmodified Program. The output from running a 195 | covered work is covered by this License only if the output, given its 196 | content, constitutes a covered work. This License acknowledges your 197 | rights of fair use or other equivalent, as provided by copyright law. 198 | 199 | You may make, run and propagate covered works that you do not 200 | convey, without conditions so long as your license otherwise remains 201 | in force. You may convey covered works to others for the sole purpose 202 | of having them make modifications exclusively for you, or provide you 203 | with facilities for running those works, provided that you comply with 204 | the terms of this License in conveying all material for which you do 205 | not control copyright. Those thus making or running the covered works 206 | for you must do so exclusively on your behalf, under your direction 207 | and control, on terms that prohibit them from making any copies of 208 | your copyrighted material outside their relationship with you. 209 | 210 | Conveying under any other circumstances is permitted solely under 211 | the conditions stated below. Sublicensing is not allowed; section 10 212 | makes it unnecessary. 213 | 214 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 215 | 216 | No covered work shall be deemed part of an effective technological 217 | measure under any applicable law fulfilling obligations under article 218 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 219 | similar laws prohibiting or restricting circumvention of such 220 | measures. 221 | 222 | When you convey a covered work, you waive any legal power to forbid 223 | circumvention of technological measures to the extent such circumvention 224 | is effected by exercising rights under this License with respect to 225 | the covered work, and you disclaim any intention to limit operation or 226 | modification of the work as a means of enforcing, against the work's 227 | users, your or third parties' legal rights to forbid circumvention of 228 | technological measures. 229 | 230 | 4. Conveying Verbatim Copies. 231 | 232 | You may convey verbatim copies of the Program's source code as you 233 | receive it, in any medium, provided that you conspicuously and 234 | appropriately publish on each copy an appropriate copyright notice; 235 | keep intact all notices stating that this License and any 236 | non-permissive terms added in accord with section 7 apply to the code; 237 | keep intact all notices of the absence of any warranty; and give all 238 | recipients a copy of this License along with the Program. 239 | 240 | You may charge any price or no price for each copy that you convey, 241 | and you may offer support or warranty protection for a fee. 242 | 243 | 5. Conveying Modified Source Versions. 244 | 245 | You may convey a work based on the Program, or the modifications to 246 | produce it from the Program, in the form of source code under the 247 | terms of section 4, provided that you also meet all of these conditions: 248 | 249 | a) The work must carry prominent notices stating that you modified 250 | it, and giving a relevant date. 251 | 252 | b) The work must carry prominent notices stating that it is 253 | released under this License and any conditions added under section 254 | 7. This requirement modifies the requirement in section 4 to 255 | "keep intact all notices". 256 | 257 | c) You must license the entire work, as a whole, under this 258 | License to anyone who comes into possession of a copy. This 259 | License will therefore apply, along with any applicable section 7 260 | additional terms, to the whole of the work, and all its parts, 261 | regardless of how they are packaged. This License gives no 262 | permission to license the work in any other way, but it does not 263 | invalidate such permission if you have separately received it. 264 | 265 | d) If the work has interactive user interfaces, each must display 266 | Appropriate Legal Notices; however, if the Program has interactive 267 | interfaces that do not display Appropriate Legal Notices, your 268 | work need not make them do so. 269 | 270 | A compilation of a covered work with other separate and independent 271 | works, which are not by their nature extensions of the covered work, 272 | and which are not combined with it such as to form a larger program, 273 | in or on a volume of a storage or distribution medium, is called an 274 | "aggregate" if the compilation and its resulting copyright are not 275 | used to limit the access or legal rights of the compilation's users 276 | beyond what the individual works permit. Inclusion of a covered work 277 | in an aggregate does not cause this License to apply to the other 278 | parts of the aggregate. 279 | 280 | 6. Conveying Non-Source Forms. 281 | 282 | You may convey a covered work in object code form under the terms 283 | of sections 4 and 5, provided that you also convey the 284 | machine-readable Corresponding Source under the terms of this License, 285 | in one of these ways: 286 | 287 | a) Convey the object code in, or embodied in, a physical product 288 | (including a physical distribution medium), accompanied by the 289 | Corresponding Source fixed on a durable physical medium 290 | customarily used for software interchange. 291 | 292 | b) Convey the object code in, or embodied in, a physical product 293 | (including a physical distribution medium), accompanied by a 294 | written offer, valid for at least three years and valid for as 295 | long as you offer spare parts or customer support for that product 296 | model, to give anyone who possesses the object code either (1) a 297 | copy of the Corresponding Source for all the software in the 298 | product that is covered by this License, on a durable physical 299 | medium customarily used for software interchange, for a price no 300 | more than your reasonable cost of physically performing this 301 | conveying of source, or (2) access to copy the 302 | Corresponding Source from a network server at no charge. 303 | 304 | c) Convey individual copies of the object code with a copy of the 305 | written offer to provide the Corresponding Source. This 306 | alternative is allowed only occasionally and noncommercially, and 307 | only if you received the object code with such an offer, in accord 308 | with subsection 6b. 309 | 310 | d) Convey the object code by offering access from a designated 311 | place (gratis or for a charge), and offer equivalent access to the 312 | Corresponding Source in the same way through the same place at no 313 | further charge. You need not require recipients to copy the 314 | Corresponding Source along with the object code. If the place to 315 | copy the object code is a network server, the Corresponding Source 316 | may be on a different server (operated by you or a third party) 317 | that supports equivalent copying facilities, provided you maintain 318 | clear directions next to the object code saying where to find the 319 | Corresponding Source. Regardless of what server hosts the 320 | Corresponding Source, you remain obligated to ensure that it is 321 | available for as long as needed to satisfy these requirements. 322 | 323 | e) Convey the object code using peer-to-peer transmission, provided 324 | you inform other peers where the object code and Corresponding 325 | Source of the work are being offered to the general public at no 326 | charge under subsection 6d. 327 | 328 | A separable portion of the object code, whose source code is excluded 329 | from the Corresponding Source as a System Library, need not be 330 | included in conveying the object code work. 331 | 332 | A "User Product" is either (1) a "consumer product", which means any 333 | tangible personal property which is normally used for personal, family, 334 | or household purposes, or (2) anything designed or sold for incorporation 335 | into a dwelling. In determining whether a product is a consumer product, 336 | doubtful cases shall be resolved in favor of coverage. For a particular 337 | product received by a particular user, "normally used" refers to a 338 | typical or common use of that class of product, regardless of the status 339 | of the particular user or of the way in which the particular user 340 | actually uses, or expects or is expected to use, the product. A product 341 | is a consumer product regardless of whether the product has substantial 342 | commercial, industrial or non-consumer uses, unless such uses represent 343 | the only significant mode of use of the product. 344 | 345 | "Installation Information" for a User Product means any methods, 346 | procedures, authorization keys, or other information required to install 347 | and execute modified versions of a covered work in that User Product from 348 | a modified version of its Corresponding Source. The information must 349 | suffice to ensure that the continued functioning of the modified object 350 | code is in no case prevented or interfered with solely because 351 | modification has been made. 352 | 353 | If you convey an object code work under this section in, or with, or 354 | specifically for use in, a User Product, and the conveying occurs as 355 | part of a transaction in which the right of possession and use of the 356 | User Product is transferred to the recipient in perpetuity or for a 357 | fixed term (regardless of how the transaction is characterized), the 358 | Corresponding Source conveyed under this section must be accompanied 359 | by the Installation Information. But this requirement does not apply 360 | if neither you nor any third party retains the ability to install 361 | modified object code on the User Product (for example, the work has 362 | been installed in ROM). 363 | 364 | The requirement to provide Installation Information does not include a 365 | requirement to continue to provide support service, warranty, or updates 366 | for a work that has been modified or installed by the recipient, or for 367 | the User Product in which it has been modified or installed. Access to a 368 | network may be denied when the modification itself materially and 369 | adversely affects the operation of the network or violates the rules and 370 | protocols for communication across the network. 371 | 372 | Corresponding Source conveyed, and Installation Information provided, 373 | in accord with this section must be in a format that is publicly 374 | documented (and with an implementation available to the public in 375 | source code form), and must require no special password or key for 376 | unpacking, reading or copying. 377 | 378 | 7. Additional Terms. 379 | 380 | "Additional permissions" are terms that supplement the terms of this 381 | License by making exceptions from one or more of its conditions. 382 | Additional permissions that are applicable to the entire Program shall 383 | be treated as though they were included in this License, to the extent 384 | that they are valid under applicable law. If additional permissions 385 | apply only to part of the Program, that part may be used separately 386 | under those permissions, but the entire Program remains governed by 387 | this License without regard to the additional permissions. 388 | 389 | When you convey a copy of a covered work, you may at your option 390 | remove any additional permissions from that copy, or from any part of 391 | it. (Additional permissions may be written to require their own 392 | removal in certain cases when you modify the work.) You may place 393 | additional permissions on material, added by you to a covered work, 394 | for which you have or can give appropriate copyright permission. 395 | 396 | Notwithstanding any other provision of this License, for material you 397 | add to a covered work, you may (if authorized by the copyright holders of 398 | that material) supplement the terms of this License with terms: 399 | 400 | a) Disclaiming warranty or limiting liability differently from the 401 | terms of sections 15 and 16 of this License; or 402 | 403 | b) Requiring preservation of specified reasonable legal notices or 404 | author attributions in that material or in the Appropriate Legal 405 | Notices displayed by works containing it; or 406 | 407 | c) Prohibiting misrepresentation of the origin of that material, or 408 | requiring that modified versions of such material be marked in 409 | reasonable ways as different from the original version; or 410 | 411 | d) Limiting the use for publicity purposes of names of licensors or 412 | authors of the material; or 413 | 414 | e) Declining to grant rights under trademark law for use of some 415 | trade names, trademarks, or service marks; or 416 | 417 | f) Requiring indemnification of licensors and authors of that 418 | material by anyone who conveys the material (or modified versions of 419 | it) with contractual assumptions of liability to the recipient, for 420 | any liability that these contractual assumptions directly impose on 421 | those licensors and authors. 422 | 423 | All other non-permissive additional terms are considered "further 424 | restrictions" within the meaning of section 10. If the Program as you 425 | received it, or any part of it, contains a notice stating that it is 426 | governed by this License along with a term that is a further 427 | restriction, you may remove that term. If a license document contains 428 | a further restriction but permits relicensing or conveying under this 429 | License, you may add to a covered work material governed by the terms 430 | of that license document, provided that the further restriction does 431 | not survive such relicensing or conveying. 432 | 433 | If you add terms to a covered work in accord with this section, you 434 | must place, in the relevant source files, a statement of the 435 | additional terms that apply to those files, or a notice indicating 436 | where to find the applicable terms. 437 | 438 | Additional terms, permissive or non-permissive, may be stated in the 439 | form of a separately written license, or stated as exceptions; 440 | the above requirements apply either way. 441 | 442 | 8. Termination. 443 | 444 | You may not propagate or modify a covered work except as expressly 445 | provided under this License. Any attempt otherwise to propagate or 446 | modify it is void, and will automatically terminate your rights under 447 | this License (including any patent licenses granted under the third 448 | paragraph of section 11). 449 | 450 | However, if you cease all violation of this License, then your 451 | license from a particular copyright holder is reinstated (a) 452 | provisionally, unless and until the copyright holder explicitly and 453 | finally terminates your license, and (b) permanently, if the copyright 454 | holder fails to notify you of the violation by some reasonable means 455 | prior to 60 days after the cessation. 456 | 457 | Moreover, your license from a particular copyright holder is 458 | reinstated permanently if the copyright holder notifies you of the 459 | violation by some reasonable means, this is the first time you have 460 | received notice of violation of this License (for any work) from that 461 | copyright holder, and you cure the violation prior to 30 days after 462 | your receipt of the notice. 463 | 464 | Termination of your rights under this section does not terminate the 465 | licenses of parties who have received copies or rights from you under 466 | this License. If your rights have been terminated and not permanently 467 | reinstated, you do not qualify to receive new licenses for the same 468 | material under section 10. 469 | 470 | 9. Acceptance Not Required for Having Copies. 471 | 472 | You are not required to accept this License in order to receive or 473 | run a copy of the Program. Ancillary propagation of a covered work 474 | occurring solely as a consequence of using peer-to-peer transmission 475 | to receive a copy likewise does not require acceptance. However, 476 | nothing other than this License grants you permission to propagate or 477 | modify any covered work. These actions infringe copyright if you do 478 | not accept this License. Therefore, by modifying or propagating a 479 | covered work, you indicate your acceptance of this License to do so. 480 | 481 | 10. Automatic Licensing of Downstream Recipients. 482 | 483 | Each time you convey a covered work, the recipient automatically 484 | receives a license from the original licensors, to run, modify and 485 | propagate that work, subject to this License. You are not responsible 486 | for enforcing compliance by third parties with this License. 487 | 488 | An "entity transaction" is a transaction transferring control of an 489 | organization, or substantially all assets of one, or subdividing an 490 | organization, or merging organizations. If propagation of a covered 491 | work results from an entity transaction, each party to that 492 | transaction who receives a copy of the work also receives whatever 493 | licenses to the work the party's predecessor in interest had or could 494 | give under the previous paragraph, plus a right to possession of the 495 | Corresponding Source of the work from the predecessor in interest, if 496 | the predecessor has it or can get it with reasonable efforts. 497 | 498 | You may not impose any further restrictions on the exercise of the 499 | rights granted or affirmed under this License. For example, you may 500 | not impose a license fee, royalty, or other charge for exercise of 501 | rights granted under this License, and you may not initiate litigation 502 | (including a cross-claim or counterclaim in a lawsuit) alleging that 503 | any patent claim is infringed by making, using, selling, offering for 504 | sale, or importing the Program or any portion of it. 505 | 506 | 11. Patents. 507 | 508 | A "contributor" is a copyright holder who authorizes use under this 509 | License of the Program or a work on which the Program is based. The 510 | work thus licensed is called the contributor's "contributor version". 511 | 512 | A contributor's "essential patent claims" are all patent claims 513 | owned or controlled by the contributor, whether already acquired or 514 | hereafter acquired, that would be infringed by some manner, permitted 515 | by this License, of making, using, or selling its contributor version, 516 | but do not include claims that would be infringed only as a 517 | consequence of further modification of the contributor version. For 518 | purposes of this definition, "control" includes the right to grant 519 | patent sublicenses in a manner consistent with the requirements of 520 | this License. 521 | 522 | Each contributor grants you a non-exclusive, worldwide, royalty-free 523 | patent license under the contributor's essential patent claims, to 524 | make, use, sell, offer for sale, import and otherwise run, modify and 525 | propagate the contents of its contributor version. 526 | 527 | In the following three paragraphs, a "patent license" is any express 528 | agreement or commitment, however denominated, not to enforce a patent 529 | (such as an express permission to practice a patent or covenant not to 530 | sue for patent infringement). To "grant" such a patent license to a 531 | party means to make such an agreement or commitment not to enforce a 532 | patent against the party. 533 | 534 | If you convey a covered work, knowingly relying on a patent license, 535 | and the Corresponding Source of the work is not available for anyone 536 | to copy, free of charge and under the terms of this License, through a 537 | publicly available network server or other readily accessible means, 538 | then you must either (1) cause the Corresponding Source to be so 539 | available, or (2) arrange to deprive yourself of the benefit of the 540 | patent license for this particular work, or (3) arrange, in a manner 541 | consistent with the requirements of this License, to extend the patent 542 | license to downstream recipients. "Knowingly relying" means you have 543 | actual knowledge that, but for the patent license, your conveying the 544 | covered work in a country, or your recipient's use of the covered work 545 | in a country, would infringe one or more identifiable patents in that 546 | country that you have reason to believe are valid. 547 | 548 | If, pursuant to or in connection with a single transaction or 549 | arrangement, you convey, or propagate by procuring conveyance of, a 550 | covered work, and grant a patent license to some of the parties 551 | receiving the covered work authorizing them to use, propagate, modify 552 | or convey a specific copy of the covered work, then the patent license 553 | you grant is automatically extended to all recipients of the covered 554 | work and works based on it. 555 | 556 | A patent license is "discriminatory" if it does not include within 557 | the scope of its coverage, prohibits the exercise of, or is 558 | conditioned on the non-exercise of one or more of the rights that are 559 | specifically granted under this License. You may not convey a covered 560 | work if you are a party to an arrangement with a third party that is 561 | in the business of distributing software, under which you make payment 562 | to the third party based on the extent of your activity of conveying 563 | the work, and under which the third party grants, to any of the 564 | parties who would receive the covered work from you, a discriminatory 565 | patent license (a) in connection with copies of the covered work 566 | conveyed by you (or copies made from those copies), or (b) primarily 567 | for and in connection with specific products or compilations that 568 | contain the covered work, unless you entered into that arrangement, 569 | or that patent license was granted, prior to 28 March 2007. 570 | 571 | Nothing in this License shall be construed as excluding or limiting 572 | any implied license or other defenses to infringement that may 573 | otherwise be available to you under applicable patent law. 574 | 575 | 12. No Surrender of Others' Freedom. 576 | 577 | If conditions are imposed on you (whether by court order, agreement or 578 | otherwise) that contradict the conditions of this License, they do not 579 | excuse you from the conditions of this License. If you cannot convey a 580 | covered work so as to satisfy simultaneously your obligations under this 581 | License and any other pertinent obligations, then as a consequence you may 582 | not convey it at all. For example, if you agree to terms that obligate you 583 | to collect a royalty for further conveying from those to whom you convey 584 | the Program, the only way you could satisfy both those terms and this 585 | License would be to refrain entirely from conveying the Program. 586 | 587 | 13. Use with the GNU Affero General Public License. 588 | 589 | Notwithstanding any other provision of this License, you have 590 | permission to link or combine any covered work with a work licensed 591 | under version 3 of the GNU Affero General Public License into a single 592 | combined work, and to convey the resulting work. The terms of this 593 | License will continue to apply to the part which is the covered work, 594 | but the special requirements of the GNU Affero General Public License, 595 | section 13, concerning interaction through a network will apply to the 596 | combination as such. 597 | 598 | 14. Revised Versions of this License. 599 | 600 | The Free Software Foundation may publish revised and/or new versions of 601 | the GNU General Public License from time to time. Such new versions will 602 | be similar in spirit to the present version, but may differ in detail to 603 | address new problems or concerns. 604 | 605 | Each version is given a distinguishing version number. If the 606 | Program specifies that a certain numbered version of the GNU General 607 | Public License "or any later version" applies to it, you have the 608 | option of following the terms and conditions either of that numbered 609 | version or of any later version published by the Free Software 610 | Foundation. If the Program does not specify a version number of the 611 | GNU General Public License, you may choose any version ever published 612 | by the Free Software Foundation. 613 | 614 | If the Program specifies that a proxy can decide which future 615 | versions of the GNU General Public License can be used, that proxy's 616 | public statement of acceptance of a version permanently authorizes you 617 | to choose that version for the Program. 618 | 619 | Later license versions may give you additional or different 620 | permissions. However, no additional obligations are imposed on any 621 | author or copyright holder as a result of your choosing to follow a 622 | later version. 623 | 624 | 15. Disclaimer of Warranty. 625 | 626 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 627 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 628 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 629 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 630 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 631 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 632 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 633 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 634 | 635 | 16. Limitation of Liability. 636 | 637 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 638 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 639 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 640 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 641 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 642 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 643 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 644 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 645 | SUCH DAMAGES. 646 | 647 | 17. Interpretation of Sections 15 and 16. 648 | 649 | If the disclaimer of warranty and limitation of liability provided 650 | above cannot be given local legal effect according to their terms, 651 | reviewing courts shall apply local law that most closely approximates 652 | an absolute waiver of all civil liability in connection with the 653 | Program, unless a warranty or assumption of liability accompanies a 654 | copy of the Program in return for a fee. 655 | 656 | END OF TERMS AND CONDITIONS 657 | 658 | How to Apply These Terms to Your New Programs 659 | 660 | If you develop a new program, and you want it to be of the greatest 661 | possible use to the public, the best way to achieve this is to make it 662 | free software which everyone can redistribute and change under these terms. 663 | 664 | To do so, attach the following notices to the program. It is safest 665 | to attach them to the start of each source file to most effectively 666 | state the exclusion of warranty; and each file should have at least 667 | the "copyright" line and a pointer to where the full notice is found. 668 | 669 | 670 | Copyright (C) 671 | 672 | This program is free software: you can redistribute it and/or modify 673 | it under the terms of the GNU General Public License as published by 674 | the Free Software Foundation, either version 3 of the License, or 675 | (at your option) any later version. 676 | 677 | This program is distributed in the hope that it will be useful, 678 | but WITHOUT ANY WARRANTY; without even the implied warranty of 679 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 680 | GNU General Public License for more details. 681 | 682 | You should have received a copy of the GNU General Public License 683 | along with this program. If not, see . 684 | 685 | Also add information on how to contact you by electronic and paper mail. 686 | 687 | If the program does terminal interaction, make it output a short 688 | notice like this when it starts in an interactive mode: 689 | 690 | Copyright (C) 691 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 692 | This is free software, and you are welcome to redistribute it 693 | under certain conditions; type `show c' for details. 694 | 695 | The hypothetical commands `show w' and `show c' should show the appropriate 696 | parts of the General Public License. Of course, your program's commands 697 | might be different; for a GUI interface, you would use an "about box". 698 | 699 | You should also get your employer (if you work as a programmer) or school, 700 | if any, to sign a "copyright disclaimer" for the program, if necessary. 701 | For more information on this, and how to apply and follow the GNU GPL, see 702 | . 703 | 704 | The GNU General Public License does not permit incorporating your program 705 | into proprietary programs. If your program is a subroutine library, you 706 | may consider it more useful to permit linking proprietary applications with 707 | the library. If this is what you want to do, use the GNU Lesser General 708 | Public License instead of this License. But first, please read 709 | . 710 | --------------------------------------------------------------------------------