init home-assistant
This commit is contained in:
1
home-assistant/script/scaffold/__init__.py
Normal file
1
home-assistant/script/scaffold/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Scaffold new integration."""
|
||||
121
home-assistant/script/scaffold/__main__.py
Normal file
121
home-assistant/script/scaffold/__main__.py
Normal file
@@ -0,0 +1,121 @@
|
||||
"""Validate manifests."""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from script.util import valid_integration
|
||||
|
||||
from . import docs, error, gather_info, generate
|
||||
|
||||
TEMPLATES = [
|
||||
p.name for p in (Path(__file__).parent / "templates").glob("*") if p.is_dir()
|
||||
]
|
||||
|
||||
|
||||
def get_arguments() -> argparse.Namespace:
|
||||
"""Get parsed passed in arguments."""
|
||||
parser = argparse.ArgumentParser(description="Home Assistant Scaffolder")
|
||||
parser.add_argument("template", type=str, choices=TEMPLATES)
|
||||
parser.add_argument(
|
||||
"--develop", action="store_true", help="Automatically fill in info"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--integration", type=valid_integration, help="Integration to target."
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Scaffold an integration."""
|
||||
if not Path("requirements_all.txt").is_file():
|
||||
print("Run from project root")
|
||||
return 1
|
||||
|
||||
args = get_arguments()
|
||||
|
||||
info = gather_info.gather_info(args)
|
||||
print()
|
||||
|
||||
# If we are calling scaffold on a non-existing integration,
|
||||
# We're going to first make it. If we're making an integration,
|
||||
# we will also make a config flow to go with it.
|
||||
|
||||
if info.is_new:
|
||||
generate.generate("integration", info)
|
||||
|
||||
# If it's a new integration and it's not a config flow,
|
||||
# create a config flow too.
|
||||
if not args.template.startswith("config_flow"):
|
||||
if info.helper:
|
||||
template = "config_flow_helper"
|
||||
elif info.oauth2:
|
||||
template = "config_flow_oauth2"
|
||||
elif info.authentication or not info.discoverable:
|
||||
template = "config_flow"
|
||||
else:
|
||||
template = "config_flow_discovery"
|
||||
|
||||
generate.generate(template, info)
|
||||
|
||||
# If we wanted a new integration, we've already done our work.
|
||||
if args.template != "integration":
|
||||
generate.generate(args.template, info)
|
||||
|
||||
pipe_null = {} if args.develop else {"stdout": subprocess.DEVNULL}
|
||||
|
||||
print("Running hassfest to pick up new information.")
|
||||
subprocess.run(["python", "-m", "script.hassfest"], **pipe_null, check=True)
|
||||
print()
|
||||
|
||||
print("Running gen_requirements_all to pick up new information.")
|
||||
subprocess.run(
|
||||
["python", "-m", "script.gen_requirements_all"], **pipe_null, check=True
|
||||
)
|
||||
print()
|
||||
|
||||
print("Running script/translations_develop to pick up new translation strings.")
|
||||
subprocess.run(
|
||||
[
|
||||
"python",
|
||||
"-m",
|
||||
"script.translations",
|
||||
"develop",
|
||||
"--integration",
|
||||
info.domain,
|
||||
],
|
||||
**pipe_null,
|
||||
check=True,
|
||||
)
|
||||
print()
|
||||
|
||||
if args.develop:
|
||||
print("Running tests")
|
||||
print(f"$ python3 -b -m pytest -vvv tests/components/{info.domain}")
|
||||
subprocess.run(
|
||||
[
|
||||
"python3",
|
||||
"-b",
|
||||
"-m",
|
||||
"pytest",
|
||||
"-vvv",
|
||||
f"tests/components/{info.domain}",
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
print()
|
||||
|
||||
docs.print_relevant_docs(args.template, info)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except error.ExitApp as err:
|
||||
print()
|
||||
print(f"Fatal Error: {err.reason}")
|
||||
sys.exit(err.exit_code)
|
||||
6
home-assistant/script/scaffold/const.py
Normal file
6
home-assistant/script/scaffold/const.py
Normal file
@@ -0,0 +1,6 @@
|
||||
"""Constants for scaffolding."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
COMPONENT_DIR = Path("homeassistant/components")
|
||||
TESTS_DIR = Path("tests/components")
|
||||
91
home-assistant/script/scaffold/docs.py
Normal file
91
home-assistant/script/scaffold/docs.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""Print links to relevant docs."""
|
||||
|
||||
from .model import Info
|
||||
|
||||
DATA = {
|
||||
"backup": {
|
||||
"title": "Backup",
|
||||
"docs": "https://developers.home-assistant.io/docs/core/platform/backup",
|
||||
},
|
||||
"config_flow": {
|
||||
"title": "Config Flow",
|
||||
"docs": "https://developers.home-assistant.io/docs/en/config_entries_config_flow_handler.html",
|
||||
},
|
||||
"config_flow_helper": {
|
||||
"title": "Helper Config Flow",
|
||||
"docs": "https://developers.home-assistant.io/docs/en/config_entries_config_flow_handler.html#helper",
|
||||
},
|
||||
"config_flow_discovery": {
|
||||
"title": "Discoverable Config Flow",
|
||||
"docs": "https://developers.home-assistant.io/docs/en/config_entries_config_flow_handler.html#discoverable-integrations-that-require-no-authentication",
|
||||
},
|
||||
"config_flow_oauth2": {
|
||||
"title": "OAuth2 Config Flow",
|
||||
"docs": "https://developers.home-assistant.io/docs/en/next/config_entries_config_flow_handler.html#configuration-via-oauth2",
|
||||
},
|
||||
"device_action": {
|
||||
"title": "Device Action",
|
||||
"docs": "https://developers.home-assistant.io/docs/en/device_automation_action.html",
|
||||
},
|
||||
"device_condition": {
|
||||
"title": "Device Condition",
|
||||
"docs": "https://developers.home-assistant.io/docs/en/device_automation_condition.html",
|
||||
},
|
||||
"device_trigger": {
|
||||
"title": "Device Trigger",
|
||||
"docs": "https://developers.home-assistant.io/docs/en/device_automation_trigger.html",
|
||||
},
|
||||
"integration": {
|
||||
"title": "Integration",
|
||||
"docs": "https://developers.home-assistant.io/docs/en/creating_integration_file_structure.html",
|
||||
},
|
||||
"reproduce_state": {
|
||||
"title": "Reproduce State",
|
||||
"docs": "https://developers.home-assistant.io/docs/core/platform/reproduce_state",
|
||||
"extra": "You will now need to update the code to make sure that every attribute that can occur in the state will cause the right service to be called.",
|
||||
},
|
||||
"significant_change": {
|
||||
"title": "Significant Change",
|
||||
"docs": "https://developers.home-assistant.io/docs/core/platform/significant_change",
|
||||
"extra": "You will now need to update the code to make sure that entities with different device classes are correctly considered.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def print_relevant_docs(template: str, info: Info) -> None:
|
||||
"""Print relevant docs."""
|
||||
data = DATA[template]
|
||||
|
||||
print()
|
||||
print("**************************")
|
||||
print()
|
||||
print()
|
||||
print(f"{data['title']} code has been generated")
|
||||
print()
|
||||
if info.files_added:
|
||||
print("Added the following files:")
|
||||
for file in info.files_added:
|
||||
print(f"- {file}")
|
||||
print()
|
||||
|
||||
if info.tests_added:
|
||||
print("Added the following tests:")
|
||||
for file in info.tests_added:
|
||||
print(f"- {file}")
|
||||
print()
|
||||
|
||||
if info.examples_added:
|
||||
print(
|
||||
"Because some files already existed, we added the following example files. Please copy the relevant code to the existing files."
|
||||
)
|
||||
for file in info.examples_added:
|
||||
print(f"- {file}")
|
||||
print()
|
||||
|
||||
print(
|
||||
"The next step is to look at the files and deal with all areas marked as TODO."
|
||||
)
|
||||
|
||||
if "extra" in data:
|
||||
print()
|
||||
print(data["extra"])
|
||||
10
home-assistant/script/scaffold/error.py
Normal file
10
home-assistant/script/scaffold/error.py
Normal file
@@ -0,0 +1,10 @@
|
||||
"""Errors for scaffolding."""
|
||||
|
||||
|
||||
class ExitApp(Exception):
|
||||
"""Exception to indicate app should exit."""
|
||||
|
||||
def __init__(self, reason, exit_code=1):
|
||||
"""Initialize the exit app exception."""
|
||||
self.reason = reason
|
||||
self.exit_code = exit_code
|
||||
186
home-assistant/script/scaffold/gather_info.py
Normal file
186
home-assistant/script/scaffold/gather_info.py
Normal file
@@ -0,0 +1,186 @@
|
||||
"""Gather info for scaffolding."""
|
||||
|
||||
import json
|
||||
|
||||
from homeassistant.util import slugify
|
||||
from script.hassfest.manifest import SUPPORTED_IOT_CLASSES
|
||||
|
||||
from .const import COMPONENT_DIR
|
||||
from .error import ExitApp
|
||||
from .model import Info
|
||||
|
||||
CHECK_EMPTY = ["Cannot be empty", lambda value: value]
|
||||
|
||||
|
||||
def gather_info(arguments) -> Info:
|
||||
"""Gather info."""
|
||||
if arguments.integration:
|
||||
info = {"domain": arguments.integration}
|
||||
elif arguments.develop:
|
||||
print("Running in developer mode. Automatically filling in info.")
|
||||
print()
|
||||
info = {"domain": "develop"}
|
||||
else:
|
||||
info = _gather_info(
|
||||
{
|
||||
"domain": {
|
||||
"prompt": "What is the domain?",
|
||||
"validators": [
|
||||
CHECK_EMPTY,
|
||||
[
|
||||
"Domains cannot contain spaces or special characters.",
|
||||
lambda value: value == slugify(value),
|
||||
],
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
info["is_new"] = not (COMPONENT_DIR / info["domain"] / "manifest.json").exists()
|
||||
|
||||
if not info["is_new"]:
|
||||
return _load_existing_integration(info["domain"])
|
||||
|
||||
if arguments.develop:
|
||||
info.update(
|
||||
{
|
||||
"name": "Develop Hub",
|
||||
"codeowner": "@developer",
|
||||
"requirement": "aiodevelop==1.2.3",
|
||||
"oauth2": True,
|
||||
"iot_class": "local_polling",
|
||||
}
|
||||
)
|
||||
else:
|
||||
info.update(gather_new_integration(arguments.template == "integration"))
|
||||
|
||||
return Info(**info)
|
||||
|
||||
|
||||
YES_NO = {
|
||||
"validators": [["Type either 'yes' or 'no'", lambda value: value in ("yes", "no")]],
|
||||
"converter": lambda value: value == "yes",
|
||||
}
|
||||
|
||||
|
||||
def gather_new_integration(determine_auth: bool) -> Info:
|
||||
"""Gather info about new integration from user."""
|
||||
fields = {
|
||||
"name": {
|
||||
"prompt": "What is the name of your integration?",
|
||||
"validators": [CHECK_EMPTY],
|
||||
},
|
||||
"codeowner": {
|
||||
"prompt": "What is your GitHub handle?",
|
||||
"validators": [
|
||||
CHECK_EMPTY,
|
||||
[
|
||||
'GitHub handles need to start with an "@"',
|
||||
lambda value: value.startswith("@"),
|
||||
],
|
||||
],
|
||||
},
|
||||
"requirement": {
|
||||
"prompt": "What PyPI package and version do you depend on? Leave blank for none.",
|
||||
"validators": [
|
||||
[
|
||||
"Versions should be pinned using '=='.",
|
||||
lambda value: not value or "==" in value,
|
||||
]
|
||||
],
|
||||
},
|
||||
"iot_class": {
|
||||
"prompt": (
|
||||
f"""How will your integration gather data?
|
||||
|
||||
Valid values are {', '.join(SUPPORTED_IOT_CLASSES)}
|
||||
|
||||
More info @ https://developers.home-assistant.io/docs/creating_integration_manifest#iot-class
|
||||
"""
|
||||
),
|
||||
"validators": [
|
||||
[
|
||||
f"You need to pick one of {', '.join(SUPPORTED_IOT_CLASSES)}",
|
||||
lambda value: value in SUPPORTED_IOT_CLASSES,
|
||||
]
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
if determine_auth:
|
||||
fields.update(
|
||||
{
|
||||
"authentication": {
|
||||
"prompt": "Does Home Assistant need the user to authenticate to control the device/service? (yes/no)",
|
||||
"default": "yes",
|
||||
**YES_NO,
|
||||
},
|
||||
"discoverable": {
|
||||
"prompt": "Is the device/service discoverable on the local network? (yes/no)",
|
||||
"default": "no",
|
||||
**YES_NO,
|
||||
},
|
||||
"helper": {
|
||||
"prompt": "Is this a helper integration? (yes/no)",
|
||||
"default": "no",
|
||||
**YES_NO,
|
||||
},
|
||||
"oauth2": {
|
||||
"prompt": "Can the user authenticate the device using OAuth2? (yes/no)",
|
||||
"default": "no",
|
||||
**YES_NO,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
return _gather_info(fields)
|
||||
|
||||
|
||||
def _load_existing_integration(domain) -> Info:
|
||||
"""Load an existing integration."""
|
||||
if not (COMPONENT_DIR / domain).exists():
|
||||
raise ExitApp("Integration does not exist", 1)
|
||||
|
||||
manifest = json.loads((COMPONENT_DIR / domain / "manifest.json").read_text())
|
||||
|
||||
return Info(domain=domain, name=manifest["name"], is_new=False)
|
||||
|
||||
|
||||
def _gather_info(fields) -> dict:
|
||||
"""Gather info from user."""
|
||||
answers = {}
|
||||
|
||||
for key, info in fields.items():
|
||||
hint = None
|
||||
while key not in answers:
|
||||
if hint is not None:
|
||||
print()
|
||||
print(f"Error: {hint}")
|
||||
|
||||
try:
|
||||
print()
|
||||
msg = info["prompt"]
|
||||
if "default" in info:
|
||||
msg += f" [{info['default']}]"
|
||||
value = input(f"{msg}\n> ")
|
||||
except (KeyboardInterrupt, EOFError) as err:
|
||||
raise ExitApp("Interrupted!", 1) from err
|
||||
|
||||
value = value.strip()
|
||||
|
||||
if value == "" and "default" in info:
|
||||
value = info["default"]
|
||||
|
||||
hint = None
|
||||
|
||||
for validator_hint, validator in info["validators"]:
|
||||
if not validator(value):
|
||||
hint = validator_hint
|
||||
break
|
||||
|
||||
if hint is None:
|
||||
if "converter" in info:
|
||||
value = info["converter"](value)
|
||||
answers[key] = value
|
||||
|
||||
return answers
|
||||
201
home-assistant/script/scaffold/generate.py
Normal file
201
home-assistant/script/scaffold/generate.py
Normal file
@@ -0,0 +1,201 @@
|
||||
"""Generate an integration."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .model import Info
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).parent / "templates"
|
||||
TEMPLATE_INTEGRATION = TEMPLATE_DIR / "integration"
|
||||
TEMPLATE_TESTS = TEMPLATE_DIR / "tests"
|
||||
|
||||
|
||||
def generate(template: str, info: Info) -> None:
|
||||
"""Generate a template."""
|
||||
print(f"Scaffolding {template} for the {info.domain} integration...")
|
||||
_ensure_tests_dir_exists(info)
|
||||
_generate(TEMPLATE_DIR / template / "integration", info.integration_dir, info)
|
||||
_generate(TEMPLATE_DIR / template / "tests", info.tests_dir, info)
|
||||
_custom_tasks(template, info)
|
||||
print()
|
||||
|
||||
|
||||
def _generate(src_dir: Path, target_dir: Path, info: Info) -> None:
|
||||
"""Generate an integration."""
|
||||
replaces = {"NEW_DOMAIN": info.domain, "NEW_NAME": info.name}
|
||||
|
||||
if not target_dir.exists():
|
||||
target_dir.mkdir()
|
||||
|
||||
for source_file in src_dir.glob("**/*"):
|
||||
content = source_file.read_text()
|
||||
|
||||
for to_search, to_replace in replaces.items():
|
||||
content = content.replace(to_search, to_replace)
|
||||
|
||||
target_file = target_dir / source_file.relative_to(src_dir)
|
||||
|
||||
# If the target file exists, create our template as EXAMPLE_<filename>.
|
||||
# Exception: If we are creating a new integration, we can end up running integration base
|
||||
# and a config flows on top of one another. In that case, we want to override the files.
|
||||
if not info.is_new and target_file.exists():
|
||||
new_name = f"EXAMPLE_{target_file.name}"
|
||||
print(f"File {target_file} already exists, creating {new_name} instead.")
|
||||
target_file = target_file.parent / new_name
|
||||
info.examples_added.add(target_file)
|
||||
elif src_dir.name == "integration":
|
||||
info.files_added.add(target_file)
|
||||
else:
|
||||
info.tests_added.add(target_file)
|
||||
|
||||
print(f"Writing {target_file}")
|
||||
target_file.write_text(content)
|
||||
|
||||
|
||||
def _ensure_tests_dir_exists(info: Info) -> None:
|
||||
"""Ensure a test dir exists."""
|
||||
if info.tests_dir.exists():
|
||||
return
|
||||
|
||||
info.tests_dir.mkdir()
|
||||
print(f"Writing {info.tests_dir / '__init__.py'}")
|
||||
(info.tests_dir / "__init__.py").write_text(
|
||||
f'"""Tests for the {info.name} integration."""\n'
|
||||
)
|
||||
|
||||
|
||||
def _append(path: Path, text):
|
||||
"""Append some text to a path."""
|
||||
path.write_text(path.read_text() + text)
|
||||
|
||||
|
||||
def _custom_tasks(template, info: Info) -> None:
|
||||
"""Handle custom tasks for templates."""
|
||||
if template == "integration":
|
||||
changes = {"codeowners": [info.codeowner], "iot_class": info.iot_class}
|
||||
|
||||
if info.requirement:
|
||||
changes["requirements"] = [info.requirement]
|
||||
|
||||
info.update_manifest(**changes)
|
||||
|
||||
elif template == "device_trigger":
|
||||
info.update_strings(
|
||||
device_automation={
|
||||
**info.strings().get("device_automation", {}),
|
||||
"trigger_type": {
|
||||
"turned_on": "{entity_name} turned on",
|
||||
"turned_off": "{entity_name} turned off",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
elif template == "device_condition":
|
||||
info.update_strings(
|
||||
device_automation={
|
||||
**info.strings().get("device_automation", {}),
|
||||
"condition_type": {
|
||||
"is_on": "{entity_name} is on",
|
||||
"is_off": "{entity_name} is off",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
elif template == "device_action":
|
||||
info.update_strings(
|
||||
device_automation={
|
||||
**info.strings().get("device_automation", {}),
|
||||
"action_type": {
|
||||
"turn_on": "Turn on {entity_name}",
|
||||
"turn_off": "Turn off {entity_name}",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
elif template == "config_flow":
|
||||
info.update_manifest(config_flow=True)
|
||||
info.update_strings(
|
||||
config={
|
||||
"step": {
|
||||
"user": {
|
||||
"data": {
|
||||
"host": "[%key:common::config_flow::data::host%]",
|
||||
"username": "[%key:common::config_flow::data::username%]",
|
||||
"password": "[%key:common::config_flow::data::password%]",
|
||||
},
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]",
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
elif template == "config_flow_discovery":
|
||||
info.update_manifest(config_flow=True)
|
||||
info.update_strings(
|
||||
config={
|
||||
"step": {
|
||||
"confirm": {
|
||||
"description": "[%key:common::config_flow::description::confirm_setup%]",
|
||||
}
|
||||
},
|
||||
"abort": {
|
||||
"single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]",
|
||||
"no_devices_found": "[%key:common::config_flow::abort::no_devices_found%]",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
elif template == "config_flow_helper":
|
||||
info.update_manifest(config_flow=True, integration_type="helper")
|
||||
info.update_strings(
|
||||
config={
|
||||
"step": {
|
||||
"user": {
|
||||
"description": "New NEW_NAME Sensor",
|
||||
"data": {"entity_id": "Input sensor", "name": "Name"},
|
||||
},
|
||||
},
|
||||
},
|
||||
options={
|
||||
"step": {
|
||||
"init": {
|
||||
"data": {
|
||||
"entity_id": "[%key:component::NEW_DOMAIN::config::step::user::description%]"
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
elif template == "config_flow_oauth2":
|
||||
info.update_manifest(config_flow=True, dependencies=["application_credentials"])
|
||||
info.update_strings(
|
||||
config={
|
||||
"step": {
|
||||
"pick_implementation": {
|
||||
"title": "[%key:common::config_flow::title::oauth2_pick_implementation%]"
|
||||
}
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
|
||||
"already_in_progress": "[%key:common::config_flow::abort::already_in_progress%]",
|
||||
"oauth_error": "[%key:common::config_flow::abort::oauth2_error%]",
|
||||
"oauth_failed": "[%key:common::config_flow::abort::oauth2_failed%]",
|
||||
"oauth_timeout": "[%key:common::config_flow::abort::oauth2_timeout%]",
|
||||
"oauth_unauthorized": "[%key:common::config_flow::abort::oauth2_unauthorized%]",
|
||||
"missing_configuration": "[%key:common::config_flow::abort::oauth2_missing_configuration%]",
|
||||
"authorize_url_timeout": "[%key:common::config_flow::abort::oauth2_authorize_url_timeout%]",
|
||||
"no_url_available": "[%key:common::config_flow::abort::oauth2_no_url_available%]",
|
||||
"user_rejected_authorize": "[%key:common::config_flow::abort::oauth2_user_rejected_authorize%]",
|
||||
},
|
||||
"create_entry": {
|
||||
"default": "[%key:common::config_flow::create_entry::authenticated%]"
|
||||
},
|
||||
},
|
||||
)
|
||||
74
home-assistant/script/scaffold/model.py
Normal file
74
home-assistant/script/scaffold/model.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""Models for scaffolding."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import attr
|
||||
|
||||
from .const import COMPONENT_DIR, TESTS_DIR
|
||||
|
||||
|
||||
@attr.s
|
||||
class Info:
|
||||
"""Info about new integration."""
|
||||
|
||||
domain: str = attr.ib()
|
||||
name: str = attr.ib()
|
||||
is_new: bool = attr.ib()
|
||||
codeowner: str = attr.ib(default=None)
|
||||
requirement: str = attr.ib(default=None)
|
||||
iot_class: str = attr.ib(default=None)
|
||||
authentication: str = attr.ib(default=None)
|
||||
discoverable: str = attr.ib(default=None)
|
||||
oauth2: str = attr.ib(default=None)
|
||||
helper: str = attr.ib(default=None)
|
||||
|
||||
files_added: set[Path] = attr.ib(factory=set)
|
||||
tests_added: set[Path] = attr.ib(factory=set)
|
||||
examples_added: set[Path] = attr.ib(factory=set)
|
||||
|
||||
@property
|
||||
def integration_dir(self) -> Path:
|
||||
"""Return directory if integration."""
|
||||
return COMPONENT_DIR / self.domain
|
||||
|
||||
@property
|
||||
def tests_dir(self) -> Path:
|
||||
"""Return test directory."""
|
||||
return TESTS_DIR / self.domain
|
||||
|
||||
@property
|
||||
def manifest_path(self) -> Path:
|
||||
"""Path to the manifest."""
|
||||
return COMPONENT_DIR / self.domain / "manifest.json"
|
||||
|
||||
def manifest(self) -> dict:
|
||||
"""Return integration manifest."""
|
||||
return json.loads(self.manifest_path.read_text())
|
||||
|
||||
def update_manifest(self, **kwargs) -> None:
|
||||
"""Update the integration manifest."""
|
||||
print(f"Updating {self.domain} manifest: {kwargs}")
|
||||
self.manifest_path.write_text(
|
||||
json.dumps({**self.manifest(), **kwargs}, indent=2) + "\n"
|
||||
)
|
||||
|
||||
@property
|
||||
def strings_path(self) -> Path:
|
||||
"""Path to the strings."""
|
||||
return COMPONENT_DIR / self.domain / "strings.json"
|
||||
|
||||
def strings(self) -> dict:
|
||||
"""Return integration strings."""
|
||||
if not self.strings_path.exists():
|
||||
return {}
|
||||
return json.loads(self.strings_path.read_text())
|
||||
|
||||
def update_strings(self, **kwargs) -> None:
|
||||
"""Update the integration strings."""
|
||||
print(f"Updating {self.domain} strings: {list(kwargs)}")
|
||||
self.strings_path.write_text(
|
||||
json.dumps({**self.strings(), **kwargs}, indent=2) + "\n"
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Backup platform for the NEW_NAME integration."""
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
async def async_pre_backup(hass: HomeAssistant) -> None:
|
||||
"""Perform operations before a backup starts."""
|
||||
|
||||
|
||||
async def async_post_backup(hass: HomeAssistant) -> None:
|
||||
"""Perform operations after a backup finishes."""
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Test the NEW_NAME backup platform."""
|
||||
|
||||
from homeassistant.components.NEW_DOMAIN.backup import (
|
||||
async_post_backup,
|
||||
async_pre_backup,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
async def test_async_post_backup(hass: HomeAssistant) -> None:
|
||||
"""Verify async_post_backup."""
|
||||
# TODO: verify that the async_post_backup function executes as expected
|
||||
assert await async_post_backup(hass)
|
||||
|
||||
|
||||
async def test_async_pre_backup(hass: HomeAssistant) -> None:
|
||||
"""Verify async_pre_backup."""
|
||||
# TODO: verify that the async_pre_backup function executes as expected
|
||||
assert await async_pre_backup(hass)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""The NEW_NAME integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
# TODO List the platforms that you want to support.
|
||||
# For your initial PR, limit it to 1 platform.
|
||||
PLATFORMS: list[Platform] = [Platform.LIGHT]
|
||||
|
||||
# TODO Create ConfigEntry type alias with API object
|
||||
# TODO Rename type alias and update all entry annotations
|
||||
type New_NameConfigEntry = ConfigEntry[MyApi] # noqa: F821
|
||||
|
||||
|
||||
# TODO Update entry annotation
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: New_NameConfigEntry) -> bool:
|
||||
"""Set up NEW_NAME from a config entry."""
|
||||
|
||||
# TODO 1. Create API instance
|
||||
# TODO 2. Validate the API connection (and authentication)
|
||||
# TODO 3. Store an API object for your platforms to access
|
||||
# entry.runtime_data = MyAPI(...)
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# TODO Update entry annotation
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: New_NameConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Config flow for the NEW_NAME integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# TODO adjust the data schema to the data that you need
|
||||
STEP_USER_DATA_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_HOST): str,
|
||||
vol.Required(CONF_USERNAME): str,
|
||||
vol.Required(CONF_PASSWORD): str,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class PlaceholderHub:
|
||||
"""Placeholder class to make tests pass.
|
||||
|
||||
TODO Remove this placeholder class and replace with things from your PyPI package.
|
||||
"""
|
||||
|
||||
def __init__(self, host: str) -> None:
|
||||
"""Initialize."""
|
||||
self.host = host
|
||||
|
||||
async def authenticate(self, username: str, password: str) -> bool:
|
||||
"""Test if we can authenticate with the host."""
|
||||
return True
|
||||
|
||||
|
||||
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Validate the user input allows us to connect.
|
||||
|
||||
Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
|
||||
"""
|
||||
# TODO validate the data can be used to set up a connection.
|
||||
|
||||
# If your PyPI package is not built with async, pass your methods
|
||||
# to the executor:
|
||||
# await hass.async_add_executor_job(
|
||||
# your_validate_func, data[CONF_USERNAME], data[CONF_PASSWORD]
|
||||
# )
|
||||
|
||||
hub = PlaceholderHub(data[CONF_HOST])
|
||||
|
||||
if not await hub.authenticate(data[CONF_USERNAME], data[CONF_PASSWORD]):
|
||||
raise InvalidAuth
|
||||
|
||||
# If you cannot connect:
|
||||
# throw CannotConnect
|
||||
# If the authentication is wrong:
|
||||
# InvalidAuth
|
||||
|
||||
# Return info that you want to store in the config entry.
|
||||
return {"title": "Name of the device"}
|
||||
|
||||
|
||||
class ConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for NEW_NAME."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the initial step."""
|
||||
errors: dict[str, str] = {}
|
||||
if user_input is not None:
|
||||
try:
|
||||
info = await validate_input(self.hass, user_input)
|
||||
except CannotConnect:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
return self.async_create_entry(title=info["title"], data=user_input)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
|
||||
)
|
||||
|
||||
|
||||
class CannotConnect(HomeAssistantError):
|
||||
"""Error to indicate we cannot connect."""
|
||||
|
||||
|
||||
class InvalidAuth(HomeAssistantError):
|
||||
"""Error to indicate there is invalid auth."""
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Constants for the NEW_NAME integration."""
|
||||
|
||||
DOMAIN = "NEW_DOMAIN"
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Common fixtures for the NEW_NAME tests."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
"""Override async_setup_entry."""
|
||||
with patch(
|
||||
"homeassistant.components.NEW_DOMAIN.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry:
|
||||
yield mock_setup_entry
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Test the NEW_NAME config flow."""
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.NEW_DOMAIN.config_flow import CannotConnect, InvalidAuth
|
||||
from homeassistant.components.NEW_DOMAIN.const import DOMAIN
|
||||
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
|
||||
async def test_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
|
||||
"""Test we get the form."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
|
||||
return_value=True,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: "1.1.1.1",
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "Name of the device"
|
||||
assert result["data"] == {
|
||||
CONF_HOST: "1.1.1.1",
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_form_invalid_auth(
|
||||
hass: HomeAssistant, mock_setup_entry: AsyncMock
|
||||
) -> None:
|
||||
"""Test we handle invalid auth."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
|
||||
side_effect=InvalidAuth,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: "1.1.1.1",
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "invalid_auth"}
|
||||
|
||||
# Make sure the config flow tests finish with either an
|
||||
# FlowResultType.CREATE_ENTRY or FlowResultType.ABORT so
|
||||
# we can show the config flow is able to recover from an error.
|
||||
with patch(
|
||||
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
|
||||
return_value=True,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: "1.1.1.1",
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "Name of the device"
|
||||
assert result["data"] == {
|
||||
CONF_HOST: "1.1.1.1",
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_form_cannot_connect(
|
||||
hass: HomeAssistant, mock_setup_entry: AsyncMock
|
||||
) -> None:
|
||||
"""Test we handle cannot connect error."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
|
||||
side_effect=CannotConnect,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: "1.1.1.1",
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "cannot_connect"}
|
||||
|
||||
# Make sure the config flow tests finish with either an
|
||||
# FlowResultType.CREATE_ENTRY or FlowResultType.ABORT so
|
||||
# we can show the config flow is able to recover from an error.
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.NEW_DOMAIN.config_flow.PlaceholderHub.authenticate",
|
||||
return_value=True,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_HOST: "1.1.1.1",
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "Name of the device"
|
||||
assert result["data"] == {
|
||||
CONF_HOST: "1.1.1.1",
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
@@ -0,0 +1,35 @@
|
||||
"""The NEW_NAME integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
# TODO List the platforms that you want to support.
|
||||
# For your initial PR, limit it to 1 platform.
|
||||
PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR]
|
||||
|
||||
# TODO Create ConfigEntry type alias with API object
|
||||
# Alias name should be prefixed by integration name
|
||||
type New_NameConfigEntry = ConfigEntry[MyApi] # noqa: F821
|
||||
|
||||
|
||||
# TODO Update entry annotation
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up NEW_NAME from a config entry."""
|
||||
|
||||
# TODO 1. Create API instance
|
||||
# TODO 2. Validate the API connection (and authentication)
|
||||
# TODO 3. Store an API object for your platforms to access
|
||||
# entry.runtime_data = MyAPI(...)
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# TODO Update entry annotation
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Config flow for the NEW_NAME integration."""
|
||||
|
||||
import my_pypi_dependency
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import config_entry_flow
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
|
||||
async def _async_has_devices(hass: HomeAssistant) -> bool:
|
||||
"""Return if there are devices that can be discovered."""
|
||||
# TODO Check if there are any devices that can be discovered in the network.
|
||||
devices = await hass.async_add_executor_job(my_pypi_dependency.discover)
|
||||
return len(devices) > 0
|
||||
|
||||
|
||||
config_entry_flow.register_discovery_flow(DOMAIN, "NEW_NAME", _async_has_devices)
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Constants for the NEW_NAME integration."""
|
||||
|
||||
DOMAIN = "NEW_DOMAIN"
|
||||
@@ -0,0 +1,33 @@
|
||||
"""The NEW_NAME integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up NEW_NAME from a config entry."""
|
||||
# TODO Optionally store an object for your platforms to access
|
||||
# entry.runtime_data = ...
|
||||
|
||||
# TODO Optionally validate config entry options before setting up platform
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, (Platform.SENSOR,))
|
||||
|
||||
# TODO Remove if the integration does not have an options flow
|
||||
entry.async_on_unload(entry.add_update_listener(config_entry_update_listener))
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# TODO Remove if the integration does not have an options flow
|
||||
async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
"""Update listener, called when the config entry options are changed."""
|
||||
await hass.config_entries.async_reload(entry.entry_id)
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.config_entries.async_unload_platforms(entry, (Platform.SENSOR,))
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Config flow for the NEW_NAME integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, cast
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
|
||||
from homeassistant.const import CONF_ENTITY_ID
|
||||
from homeassistant.helpers import selector
|
||||
from homeassistant.helpers.schema_config_entry_flow import (
|
||||
SchemaConfigFlowHandler,
|
||||
SchemaFlowFormStep,
|
||||
SchemaFlowMenuStep,
|
||||
)
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
OPTIONS_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_ENTITY_ID): selector.EntitySelector(
|
||||
selector.EntitySelectorConfig(domain=SENSOR_DOMAIN)
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required("name"): selector.TextSelector(),
|
||||
}
|
||||
).extend(OPTIONS_SCHEMA.schema)
|
||||
|
||||
CONFIG_FLOW: dict[str, SchemaFlowFormStep | SchemaFlowMenuStep] = {
|
||||
"user": SchemaFlowFormStep(CONFIG_SCHEMA)
|
||||
}
|
||||
|
||||
OPTIONS_FLOW: dict[str, SchemaFlowFormStep | SchemaFlowMenuStep] = {
|
||||
"init": SchemaFlowFormStep(OPTIONS_SCHEMA)
|
||||
}
|
||||
|
||||
|
||||
class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN):
|
||||
"""Handle a config or options flow for NEW_NAME."""
|
||||
|
||||
config_flow = CONFIG_FLOW
|
||||
# TODO remove the options_flow if the integration does not have an options flow
|
||||
options_flow = OPTIONS_FLOW
|
||||
|
||||
def async_config_entry_title(self, options: Mapping[str, Any]) -> str:
|
||||
"""Return config entry title."""
|
||||
return cast(str, options["name"]) if "name" in options else ""
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Constants for the NEW_NAME integration."""
|
||||
|
||||
DOMAIN = "NEW_DOMAIN"
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Sensor platform for NEW_NAME integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.components.sensor import SensorEntity
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_ENTITY_ID
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Initialize NEW_NAME config entry."""
|
||||
registry = er.async_get(hass)
|
||||
# Validate + resolve entity registry id to entity_id
|
||||
entity_id = er.async_validate_entity_id(
|
||||
registry, config_entry.options[CONF_ENTITY_ID]
|
||||
)
|
||||
# TODO Optionally validate config entry options before creating entity
|
||||
name = config_entry.title
|
||||
unique_id = config_entry.entry_id
|
||||
|
||||
async_add_entities([NEW_DOMAINSensorEntity(unique_id, name, entity_id)])
|
||||
|
||||
|
||||
class NEW_DOMAINSensorEntity(SensorEntity):
|
||||
"""NEW_DOMAIN Sensor."""
|
||||
|
||||
def __init__(self, unique_id: str, name: str, wrapped_entity_id: str) -> None:
|
||||
"""Initialize NEW_DOMAIN Sensor."""
|
||||
super().__init__()
|
||||
self._wrapped_entity_id = wrapped_entity_id
|
||||
self._attr_name = name
|
||||
self._attr_unique_id = unique_id
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Common fixtures for the NEW_NAME tests."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
"""Override async_setup_entry."""
|
||||
with patch(
|
||||
"homeassistant.components.NEW_DOMAIN.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry:
|
||||
yield mock_setup_entry
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Test the NEW_NAME config flow."""
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.NEW_DOMAIN.const import DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
pytestmark = pytest.mark.usefixtures("mock_setup_entry")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", ["sensor"])
|
||||
async def test_config_flow(
|
||||
hass: HomeAssistant, mock_setup_entry: AsyncMock, platform
|
||||
) -> None:
|
||||
"""Test the config flow."""
|
||||
input_sensor_entity_id = "sensor.input"
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["errors"] is None
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"name": "My NEW_DOMAIN", "entity_id": input_sensor_entity_id},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "My NEW_DOMAIN"
|
||||
assert result["data"] == {}
|
||||
assert result["options"] == {
|
||||
"entity_id": input_sensor_entity_id,
|
||||
"name": "My NEW_DOMAIN",
|
||||
}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
|
||||
assert config_entry.data == {}
|
||||
assert config_entry.options == {
|
||||
"entity_id": input_sensor_entity_id,
|
||||
"name": "My NEW_DOMAIN",
|
||||
}
|
||||
assert config_entry.title == "My NEW_DOMAIN"
|
||||
|
||||
|
||||
def get_suggested(schema, key):
|
||||
"""Get suggested value for key in voluptuous schema."""
|
||||
for k in schema:
|
||||
if k == key:
|
||||
if k.description is None or "suggested_value" not in k.description:
|
||||
return None
|
||||
return k.description["suggested_value"]
|
||||
# Wanted key absent from schema
|
||||
raise KeyError(f"Key `{key}` is missing from schema")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", ["sensor"])
|
||||
async def test_options(hass: HomeAssistant, platform) -> None:
|
||||
"""Test reconfiguring."""
|
||||
input_sensor_1_entity_id = "sensor.input1"
|
||||
input_sensor_2_entity_id = "sensor.input2"
|
||||
|
||||
# Setup the config entry
|
||||
config_entry = MockConfigEntry(
|
||||
data={},
|
||||
domain=DOMAIN,
|
||||
options={
|
||||
"entity_id": input_sensor_1_entity_id,
|
||||
"name": "My NEW_DOMAIN",
|
||||
},
|
||||
title="My NEW_DOMAIN",
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(config_entry.entry_id)
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
schema = result["data_schema"].schema
|
||||
assert get_suggested(schema, "entity_id") == input_sensor_1_entity_id
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"entity_id": input_sensor_2_entity_id,
|
||||
},
|
||||
)
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"entity_id": input_sensor_2_entity_id,
|
||||
"name": "My NEW_DOMAIN",
|
||||
}
|
||||
assert config_entry.data == {}
|
||||
assert config_entry.options == {
|
||||
"entity_id": input_sensor_2_entity_id,
|
||||
"name": "My NEW_DOMAIN",
|
||||
}
|
||||
assert config_entry.title == "My NEW_DOMAIN"
|
||||
|
||||
# Check config entry is reloaded with new options
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Check the entity was updated, no new entity was created
|
||||
assert len(hass.states.async_all()) == 1
|
||||
|
||||
# TODO Check the state of the entity has changed as expected
|
||||
state = hass.states.get(f"{platform}.my_NEW_DOMAIN")
|
||||
assert state.attributes == {}
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Test the NEW_NAME integration."""
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.NEW_DOMAIN.const import DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", ["sensor"])
|
||||
async def test_setup_and_remove_config_entry(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
platform: str,
|
||||
) -> None:
|
||||
"""Test setting up and removing a config entry."""
|
||||
input_sensor_entity_id = "sensor.input"
|
||||
NEW_DOMAIN_entity_id = f"{platform}.my_NEW_DOMAIN"
|
||||
|
||||
# Setup the config entry
|
||||
config_entry = MockConfigEntry(
|
||||
data={},
|
||||
domain=DOMAIN,
|
||||
options={
|
||||
"entity_id": input_sensor_entity_id,
|
||||
"name": "My NEW_DOMAIN",
|
||||
},
|
||||
title="My NEW_DOMAIN",
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Check the entity is registered in the entity registry
|
||||
assert entity_registry.async_get(NEW_DOMAIN_entity_id) is not None
|
||||
|
||||
# Check the platform is setup correctly
|
||||
state = hass.states.get(NEW_DOMAIN_entity_id)
|
||||
# TODO Check the state of the entity has changed as expected
|
||||
assert state.state == "unknown"
|
||||
assert state.attributes == {}
|
||||
|
||||
# Remove the config entry
|
||||
assert await hass.config_entries.async_remove(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Check the state and entity registry entry are removed
|
||||
assert hass.states.get(NEW_DOMAIN_entity_id) is None
|
||||
assert entity_registry.async_get(NEW_DOMAIN_entity_id) is None
|
||||
@@ -0,0 +1,48 @@
|
||||
"""The NEW_NAME integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import aiohttp_client, config_entry_oauth2_flow
|
||||
|
||||
from . import api
|
||||
|
||||
# TODO List the platforms that you want to support.
|
||||
# For your initial PR, limit it to 1 platform.
|
||||
PLATFORMS: list[Platform] = [Platform.LIGHT]
|
||||
|
||||
# TODO Create ConfigEntry type alias with ConfigEntryAuth or AsyncConfigEntryAuth object
|
||||
# TODO Rename type alias and update all entry annotations
|
||||
type New_NameConfigEntry = ConfigEntry[api.AsyncConfigEntryAuth]
|
||||
|
||||
|
||||
# # TODO Update entry annotation
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: New_NameConfigEntry) -> bool:
|
||||
"""Set up NEW_NAME from a config entry."""
|
||||
implementation = (
|
||||
await config_entry_oauth2_flow.async_get_config_entry_implementation(
|
||||
hass, entry
|
||||
)
|
||||
)
|
||||
|
||||
session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
|
||||
|
||||
# If using a requests-based API lib
|
||||
entry.runtime_data = api.ConfigEntryAuth(hass, session)
|
||||
|
||||
# If using an aiohttp-based API lib
|
||||
entry.runtime_data = api.AsyncConfigEntryAuth(
|
||||
aiohttp_client.async_get_clientsession(hass), session
|
||||
)
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# TODO Update entry annotation
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: New_NameConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""API for NEW_NAME bound to Home Assistant OAuth."""
|
||||
|
||||
from asyncio import run_coroutine_threadsafe
|
||||
|
||||
from aiohttp import ClientSession
|
||||
import my_pypi_package
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import config_entry_oauth2_flow
|
||||
|
||||
# TODO the following two API examples are based on our suggested best practices
|
||||
# for libraries using OAuth2 with requests or aiohttp. Delete the one you won't use.
|
||||
# For more info see the docs at https://developers.home-assistant.io/docs/api_lib_auth/#oauth2.
|
||||
|
||||
|
||||
class ConfigEntryAuth(my_pypi_package.AbstractAuth):
|
||||
"""Provide NEW_NAME authentication tied to an OAuth2 based config entry."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
oauth_session: config_entry_oauth2_flow.OAuth2Session,
|
||||
) -> None:
|
||||
"""Initialize NEW_NAME Auth."""
|
||||
self.hass = hass
|
||||
self.session = oauth_session
|
||||
super().__init__(self.session.token)
|
||||
|
||||
def refresh_tokens(self) -> str:
|
||||
"""Refresh and return new NEW_NAME tokens using Home Assistant OAuth2 session."""
|
||||
run_coroutine_threadsafe(
|
||||
self.session.async_ensure_token_valid(), self.hass.loop
|
||||
).result()
|
||||
|
||||
return self.session.token["access_token"]
|
||||
|
||||
|
||||
class AsyncConfigEntryAuth(my_pypi_package.AbstractAuth):
|
||||
"""Provide NEW_NAME authentication tied to an OAuth2 based config entry."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
websession: ClientSession,
|
||||
oauth_session: config_entry_oauth2_flow.OAuth2Session,
|
||||
) -> None:
|
||||
"""Initialize NEW_NAME auth."""
|
||||
super().__init__(websession)
|
||||
self._oauth_session = oauth_session
|
||||
|
||||
async def async_get_access_token(self) -> str:
|
||||
"""Return a valid access token."""
|
||||
await self._oauth_session.async_ensure_token_valid()
|
||||
|
||||
return self._oauth_session.token["access_token"]
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Application credentials platform for the NEW_NAME integration."""
|
||||
|
||||
from homeassistant.components.application_credentials import AuthorizationServer
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .const import OAUTH2_AUTHORIZE, OAUTH2_TOKEN
|
||||
|
||||
|
||||
async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer:
|
||||
"""Return authorization server."""
|
||||
return AuthorizationServer(
|
||||
authorize_url=OAUTH2_AUTHORIZE,
|
||||
token_url=OAUTH2_TOKEN,
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Config flow for NEW_NAME."""
|
||||
|
||||
import logging
|
||||
|
||||
from homeassistant.helpers import config_entry_oauth2_flow
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
|
||||
class OAuth2FlowHandler(
|
||||
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
|
||||
):
|
||||
"""Config flow to handle NEW_NAME OAuth2 authentication."""
|
||||
|
||||
DOMAIN = DOMAIN
|
||||
|
||||
@property
|
||||
def logger(self) -> logging.Logger:
|
||||
"""Return logger."""
|
||||
return logging.getLogger(__name__)
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Constants for the NEW_NAME integration."""
|
||||
|
||||
DOMAIN = "NEW_DOMAIN"
|
||||
|
||||
# TODO Update with your own urls
|
||||
OAUTH2_AUTHORIZE = "https://www.example.com/auth/authorize"
|
||||
OAUTH2_TOKEN = "https://www.example.com/auth/token"
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Test the NEW_NAME config flow."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.application_credentials import (
|
||||
ClientCredential,
|
||||
async_import_client_credential,
|
||||
)
|
||||
from homeassistant.components.NEW_DOMAIN.const import (
|
||||
DOMAIN,
|
||||
OAUTH2_AUTHORIZE,
|
||||
OAUTH2_TOKEN,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import config_entry_oauth2_flow
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
CLIENT_ID = "1234"
|
||||
CLIENT_SECRET = "5678"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def setup_credentials(hass: HomeAssistant) -> None:
|
||||
"""Fixture to setup credentials."""
|
||||
assert await async_setup_component(hass, "application_credentials", {})
|
||||
await async_import_client_credential(
|
||||
hass,
|
||||
DOMAIN,
|
||||
ClientCredential(CLIENT_ID, CLIENT_SECRET),
|
||||
)
|
||||
|
||||
|
||||
async def test_full_flow(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth,
|
||||
aioclient_mock,
|
||||
current_request_with_host,
|
||||
setup_credentials,
|
||||
) -> None:
|
||||
"""Check full flow."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
state = config_entry_oauth2_flow._encode_jwt( # noqa: SLF001
|
||||
hass,
|
||||
{
|
||||
"flow_id": result["flow_id"],
|
||||
"redirect_uri": "https://example.com/auth/external/callback",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["url"] == (
|
||||
f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}"
|
||||
"&redirect_uri=https://example.com/auth/external/callback"
|
||||
f"&state={state}"
|
||||
)
|
||||
|
||||
client = await hass_client_no_auth()
|
||||
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
||||
assert resp.status == 200
|
||||
assert resp.headers["content-type"] == "text/html; charset=utf-8"
|
||||
|
||||
aioclient_mock.post(
|
||||
OAUTH2_TOKEN,
|
||||
json={
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "mock-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.NEW_DOMAIN.async_setup_entry", return_value=True
|
||||
) as mock_setup:
|
||||
await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
|
||||
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
|
||||
assert len(mock_setup.mock_calls) == 1
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Provides device actions for NEW_NAME."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
CONF_DEVICE_ID,
|
||||
CONF_DOMAIN,
|
||||
CONF_ENTITY_ID,
|
||||
CONF_TYPE,
|
||||
SERVICE_TURN_OFF,
|
||||
SERVICE_TURN_ON,
|
||||
)
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.helpers import config_validation as cv, entity_registry as er
|
||||
|
||||
from . import DOMAIN
|
||||
|
||||
# TODO specify your supported action types.
|
||||
ACTION_TYPES = {"turn_on", "turn_off"}
|
||||
|
||||
ACTION_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend(
|
||||
{
|
||||
vol.Required(CONF_TYPE): vol.In(ACTION_TYPES),
|
||||
vol.Required(CONF_ENTITY_ID): cv.entity_domain(DOMAIN),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def async_get_actions(
|
||||
hass: HomeAssistant, device_id: str
|
||||
) -> list[dict[str, str]]:
|
||||
"""List device actions for NEW_NAME devices."""
|
||||
registry = er.async_get(hass)
|
||||
actions = []
|
||||
|
||||
# TODO Read this comment and remove it.
|
||||
# This example shows how to iterate over the entities of this device
|
||||
# that match this integration. If your actions instead rely on
|
||||
# calling services, do something like:
|
||||
# zha_device = await _async_get_zha_device(hass, device_id)
|
||||
# return zha_device.device_actions
|
||||
|
||||
# Get all the integrations entities for this device
|
||||
for entry in er.async_entries_for_device(registry, device_id):
|
||||
if entry.domain != DOMAIN:
|
||||
continue
|
||||
|
||||
# Add actions for each entity that belongs to this integration
|
||||
# TODO add your own actions.
|
||||
base_action = {
|
||||
CONF_DEVICE_ID: device_id,
|
||||
CONF_DOMAIN: DOMAIN,
|
||||
CONF_ENTITY_ID: entry.entity_id,
|
||||
}
|
||||
|
||||
actions.append({**base_action, CONF_TYPE: "turn_on"})
|
||||
actions.append({**base_action, CONF_TYPE: "turn_off"})
|
||||
|
||||
return actions
|
||||
|
||||
|
||||
async def async_call_action_from_config(
|
||||
hass: HomeAssistant, config: dict, variables: dict, context: Context | None
|
||||
) -> None:
|
||||
"""Execute a device action."""
|
||||
service_data = {ATTR_ENTITY_ID: config[CONF_ENTITY_ID]}
|
||||
|
||||
if config[CONF_TYPE] == "turn_on":
|
||||
service = SERVICE_TURN_ON
|
||||
elif config[CONF_TYPE] == "turn_off":
|
||||
service = SERVICE_TURN_OFF
|
||||
|
||||
await hass.services.async_call(
|
||||
DOMAIN, service, service_data, blocking=True, context=context
|
||||
)
|
||||
@@ -0,0 +1,144 @@
|
||||
"""The tests for NEW_NAME device actions."""
|
||||
|
||||
import pytest
|
||||
from pytest_unordered import unordered
|
||||
|
||||
from homeassistant.components import automation
|
||||
from homeassistant.components.device_automation import DeviceAutomationType
|
||||
from homeassistant.components.NEW_DOMAIN import DOMAIN
|
||||
from homeassistant.const import EntityCategory
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import (
|
||||
MockConfigEntry,
|
||||
async_get_device_automations,
|
||||
async_mock_service,
|
||||
)
|
||||
|
||||
|
||||
async def test_get_actions(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test we get the expected actions from a NEW_DOMAIN."""
|
||||
config_entry = MockConfigEntry(domain="test", data={})
|
||||
config_entry.add_to_hass(hass)
|
||||
device_entry = device_registry.async_get_or_create(
|
||||
config_entry_id=config_entry.entry_id,
|
||||
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
|
||||
)
|
||||
entity_registry.async_get_or_create(
|
||||
DOMAIN, "test", "5678", device_id=device_entry.id
|
||||
)
|
||||
expected_actions = [
|
||||
{
|
||||
"domain": DOMAIN,
|
||||
"type": action,
|
||||
"device_id": device_entry.id,
|
||||
"entity_id": f"{DOMAIN}.test_5678",
|
||||
}
|
||||
for action in ["turn_off", "turn_on"]
|
||||
]
|
||||
actions = await async_get_device_automations(
|
||||
hass, DeviceAutomationType.ACTION, device_entry.id
|
||||
)
|
||||
assert actions == unordered(expected_actions)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("hidden_by", "entity_category"),
|
||||
[
|
||||
(er.RegistryEntryHider.INTEGRATION, None),
|
||||
(er.RegistryEntryHider.USER, None),
|
||||
(None, EntityCategory.CONFIG),
|
||||
(None, EntityCategory.DIAGNOSTIC),
|
||||
],
|
||||
)
|
||||
async def test_get_actions_hidden_auxiliary(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
hidden_by: er.RegistryEntryHider | None,
|
||||
entity_category: EntityCategory | None,
|
||||
):
|
||||
"""Test we get the expected actions from a hidden or auxiliary entity."""
|
||||
config_entry = MockConfigEntry(domain="test", data={})
|
||||
config_entry.add_to_hass(hass)
|
||||
device_entry = device_registry.async_get_or_create(
|
||||
config_entry_id=config_entry.entry_id,
|
||||
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
|
||||
)
|
||||
entity_registry.async_get_or_create(
|
||||
DOMAIN,
|
||||
"test",
|
||||
"5678",
|
||||
device_id=device_entry.id,
|
||||
entity_category=entity_category,
|
||||
hidden_by=hidden_by,
|
||||
)
|
||||
expected_actions = [
|
||||
{
|
||||
"domain": DOMAIN,
|
||||
"type": action,
|
||||
"device_id": device_entry.id,
|
||||
"entity_id": f"{DOMAIN}.test_5678",
|
||||
"metadata": {"secondary": True},
|
||||
}
|
||||
for action in ["turn_off", "turn_on", "toggle"]
|
||||
]
|
||||
actions = await async_get_device_automations(
|
||||
hass, DeviceAutomationType.ACTION, device_entry.id
|
||||
)
|
||||
assert actions == unordered(expected_actions)
|
||||
|
||||
|
||||
async def test_action(hass: HomeAssistant) -> None:
|
||||
"""Test for turn_on and turn_off actions."""
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
automation.DOMAIN,
|
||||
{
|
||||
automation.DOMAIN: [
|
||||
{
|
||||
"trigger": {
|
||||
"platform": "event",
|
||||
"event_type": "test_event_turn_off",
|
||||
},
|
||||
"action": {
|
||||
"domain": DOMAIN,
|
||||
"device_id": "abcdefgh",
|
||||
"entity_id": "NEW_DOMAIN.entity",
|
||||
"type": "turn_off",
|
||||
},
|
||||
},
|
||||
{
|
||||
"trigger": {
|
||||
"platform": "event",
|
||||
"event_type": "test_event_turn_on",
|
||||
},
|
||||
"action": {
|
||||
"domain": DOMAIN,
|
||||
"device_id": "abcdefgh",
|
||||
"entity_id": "NEW_DOMAIN.entity",
|
||||
"type": "turn_on",
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
turn_off_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_off")
|
||||
turn_on_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_on")
|
||||
|
||||
hass.bus.async_fire("test_event_turn_off")
|
||||
await hass.async_block_till_done()
|
||||
assert len(turn_off_calls) == 1
|
||||
assert len(turn_on_calls) == 0
|
||||
|
||||
hass.bus.async_fire("test_event_turn_on")
|
||||
await hass.async_block_till_done()
|
||||
assert len(turn_off_calls) == 1
|
||||
assert len(turn_on_calls) == 1
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Provide the device conditions for NEW_NAME."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
CONF_CONDITION,
|
||||
CONF_DEVICE_ID,
|
||||
CONF_DOMAIN,
|
||||
CONF_ENTITY_ID,
|
||||
CONF_TYPE,
|
||||
STATE_OFF,
|
||||
STATE_ON,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers import (
|
||||
condition,
|
||||
config_validation as cv,
|
||||
entity_registry as er,
|
||||
)
|
||||
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
|
||||
|
||||
from . import DOMAIN
|
||||
|
||||
# TODO specify your supported condition types.
|
||||
CONDITION_TYPES = {"is_on", "is_off"}
|
||||
|
||||
CONDITION_SCHEMA = cv.DEVICE_CONDITION_BASE_SCHEMA.extend(
|
||||
{
|
||||
vol.Required(CONF_ENTITY_ID): cv.entity_id,
|
||||
vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def async_get_conditions(
|
||||
hass: HomeAssistant, device_id: str
|
||||
) -> list[dict[str, str]]:
|
||||
"""List device conditions for NEW_NAME devices."""
|
||||
registry = er.async_get(hass)
|
||||
conditions = []
|
||||
|
||||
# Get all the integrations entities for this device
|
||||
for entry in er.async_entries_for_device(registry, device_id):
|
||||
if entry.domain != DOMAIN:
|
||||
continue
|
||||
|
||||
# Add conditions for each entity that belongs to this integration
|
||||
# TODO add your own conditions.
|
||||
base_condition = {
|
||||
CONF_CONDITION: "device",
|
||||
CONF_DEVICE_ID: device_id,
|
||||
CONF_DOMAIN: DOMAIN,
|
||||
CONF_ENTITY_ID: entry.entity_id,
|
||||
}
|
||||
|
||||
conditions += [{**base_condition, CONF_TYPE: cond} for cond in CONDITION_TYPES]
|
||||
|
||||
return conditions
|
||||
|
||||
|
||||
@callback
|
||||
def async_condition_from_config(
|
||||
hass: HomeAssistant, config: ConfigType
|
||||
) -> condition.ConditionCheckerType:
|
||||
"""Create a function to test a device condition."""
|
||||
if config[CONF_TYPE] == "is_on":
|
||||
state = STATE_ON
|
||||
else:
|
||||
state = STATE_OFF
|
||||
|
||||
@callback
|
||||
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
|
||||
"""Test if an entity is a certain state."""
|
||||
return condition.state(hass, config[ATTR_ENTITY_ID], state)
|
||||
|
||||
return test_is_state
|
||||
@@ -0,0 +1,114 @@
|
||||
"""The tests for NEW_NAME device conditions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pytest_unordered import unordered
|
||||
|
||||
from homeassistant.components import automation
|
||||
from homeassistant.components.device_automation import DeviceAutomationType
|
||||
from homeassistant.components.NEW_DOMAIN import DOMAIN
|
||||
from homeassistant.const import STATE_OFF, STATE_ON
|
||||
from homeassistant.core import HomeAssistant, ServiceCall
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import MockConfigEntry, async_get_device_automations
|
||||
|
||||
|
||||
async def test_get_conditions(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test we get the expected conditions from a NEW_DOMAIN."""
|
||||
config_entry = MockConfigEntry(domain="test", data={})
|
||||
config_entry.add_to_hass(hass)
|
||||
device_entry = device_registry.async_get_or_create(
|
||||
config_entry_id=config_entry.entry_id,
|
||||
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
|
||||
)
|
||||
entity_registry.async_get_or_create(
|
||||
DOMAIN, "test", "5678", device_id=device_entry.id
|
||||
)
|
||||
expected_conditions = [
|
||||
{
|
||||
"condition": "device",
|
||||
"domain": DOMAIN,
|
||||
"type": "is_off",
|
||||
"device_id": device_entry.id,
|
||||
"entity_id": f"{DOMAIN}.test_5678",
|
||||
},
|
||||
{
|
||||
"condition": "device",
|
||||
"domain": DOMAIN,
|
||||
"type": "is_on",
|
||||
"device_id": device_entry.id,
|
||||
"entity_id": f"{DOMAIN}.test_5678",
|
||||
},
|
||||
]
|
||||
conditions = await async_get_device_automations(
|
||||
hass, DeviceAutomationType.CONDITION, device_entry.id
|
||||
)
|
||||
assert conditions == unordered(expected_conditions)
|
||||
|
||||
|
||||
async def test_if_state(hass: HomeAssistant, service_calls: list[ServiceCall]) -> None:
|
||||
"""Test for turn_on and turn_off conditions."""
|
||||
hass.states.async_set("NEW_DOMAIN.entity", STATE_ON)
|
||||
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
automation.DOMAIN,
|
||||
{
|
||||
automation.DOMAIN: [
|
||||
{
|
||||
"trigger": {"platform": "event", "event_type": "test_event1"},
|
||||
"condition": [
|
||||
{
|
||||
"condition": "device",
|
||||
"domain": DOMAIN,
|
||||
"device_id": "",
|
||||
"entity_id": "NEW_DOMAIN.entity",
|
||||
"type": "is_on",
|
||||
}
|
||||
],
|
||||
"action": {
|
||||
"service": "test.automation",
|
||||
"data_template": {
|
||||
"some": "is_on - {{ trigger.platform }} - {{ trigger.event.event_type }}"
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"trigger": {"platform": "event", "event_type": "test_event2"},
|
||||
"condition": [
|
||||
{
|
||||
"condition": "device",
|
||||
"domain": DOMAIN,
|
||||
"device_id": "",
|
||||
"entity_id": "NEW_DOMAIN.entity",
|
||||
"type": "is_off",
|
||||
}
|
||||
],
|
||||
"action": {
|
||||
"service": "test.automation",
|
||||
"data_template": {
|
||||
"some": "is_off - {{ trigger.platform }} - {{ trigger.event.event_type }}"
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
)
|
||||
hass.bus.async_fire("test_event1")
|
||||
hass.bus.async_fire("test_event2")
|
||||
await hass.async_block_till_done()
|
||||
assert len(service_calls) == 1
|
||||
assert service_calls[0].data["some"] == "is_on - event - test_event1"
|
||||
|
||||
hass.states.async_set("NEW_DOMAIN.entity", STATE_OFF)
|
||||
hass.bus.async_fire("test_event1")
|
||||
hass.bus.async_fire("test_event2")
|
||||
await hass.async_block_till_done()
|
||||
assert len(service_calls) == 2
|
||||
assert service_calls[1].data["some"] == "is_off - event - test_event2"
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Provides device triggers for NEW_NAME."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
|
||||
from homeassistant.components.homeassistant.triggers import state as state_trigger
|
||||
from homeassistant.const import (
|
||||
CONF_DEVICE_ID,
|
||||
CONF_DOMAIN,
|
||||
CONF_ENTITY_ID,
|
||||
CONF_PLATFORM,
|
||||
CONF_TYPE,
|
||||
STATE_OFF,
|
||||
STATE_ON,
|
||||
)
|
||||
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
|
||||
from homeassistant.helpers import config_validation as cv, entity_registry as er
|
||||
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
from . import DOMAIN
|
||||
|
||||
# TODO specify your supported trigger types.
|
||||
TRIGGER_TYPES = {"turned_on", "turned_off"}
|
||||
|
||||
TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
|
||||
{
|
||||
vol.Required(CONF_ENTITY_ID): cv.entity_id,
|
||||
vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def async_get_triggers(
|
||||
hass: HomeAssistant, device_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
"""List device triggers for NEW_NAME devices."""
|
||||
registry = er.async_get(hass)
|
||||
triggers = []
|
||||
|
||||
# TODO Read this comment and remove it.
|
||||
# This example shows how to iterate over the entities of this device
|
||||
# that match this integration. If your triggers instead rely on
|
||||
# events fired by devices without entities, do something like:
|
||||
# zha_device = await _async_get_zha_device(hass, device_id)
|
||||
# return zha_device.device_triggers
|
||||
|
||||
# Get all the integrations entities for this device
|
||||
for entry in er.async_entries_for_device(registry, device_id):
|
||||
if entry.domain != DOMAIN:
|
||||
continue
|
||||
|
||||
# Add triggers for each entity that belongs to this integration
|
||||
# TODO add your own triggers.
|
||||
base_trigger = {
|
||||
CONF_PLATFORM: "device",
|
||||
CONF_DEVICE_ID: device_id,
|
||||
CONF_DOMAIN: DOMAIN,
|
||||
CONF_ENTITY_ID: entry.entity_id,
|
||||
}
|
||||
triggers.append({**base_trigger, CONF_TYPE: "turned_on"})
|
||||
triggers.append({**base_trigger, CONF_TYPE: "turned_off"})
|
||||
|
||||
return triggers
|
||||
|
||||
|
||||
async def async_attach_trigger(
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
action: TriggerActionType,
|
||||
trigger_info: TriggerInfo,
|
||||
) -> CALLBACK_TYPE:
|
||||
"""Attach a trigger."""
|
||||
# TODO Implement your own logic to attach triggers.
|
||||
# Use the existing state or event triggers from the automation integration.
|
||||
|
||||
if config[CONF_TYPE] == "turned_on":
|
||||
to_state = STATE_ON
|
||||
else:
|
||||
to_state = STATE_OFF
|
||||
|
||||
state_config = {
|
||||
state_trigger.CONF_PLATFORM: "state",
|
||||
CONF_ENTITY_ID: config[CONF_ENTITY_ID],
|
||||
state_trigger.CONF_TO: to_state,
|
||||
}
|
||||
state_config = await state_trigger.async_validate_trigger_config(hass, state_config)
|
||||
return await state_trigger.async_attach_trigger(
|
||||
hass, state_config, action, trigger_info, platform_type="device"
|
||||
)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""The tests for NEW_NAME device triggers."""
|
||||
|
||||
from pytest_unordered import unordered
|
||||
|
||||
from homeassistant.components import automation
|
||||
from homeassistant.components.device_automation import DeviceAutomationType
|
||||
from homeassistant.components.NEW_DOMAIN import DOMAIN
|
||||
from homeassistant.const import STATE_OFF, STATE_ON
|
||||
from homeassistant.core import HomeAssistant, ServiceCall
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import MockConfigEntry, async_get_device_automations
|
||||
|
||||
|
||||
async def test_get_triggers(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test we get the expected triggers from a NEW_DOMAIN."""
|
||||
config_entry = MockConfigEntry(domain="test", data={})
|
||||
config_entry.add_to_hass(hass)
|
||||
device_entry = device_registry.async_get_or_create(
|
||||
config_entry_id=config_entry.entry_id,
|
||||
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
|
||||
)
|
||||
entity_registry.async_get_or_create(
|
||||
DOMAIN, "test", "5678", device_id=device_entry.id
|
||||
)
|
||||
expected_triggers = [
|
||||
{
|
||||
"platform": "device",
|
||||
"domain": DOMAIN,
|
||||
"type": "turned_off",
|
||||
"device_id": device_entry.id,
|
||||
"entity_id": f"{DOMAIN}.test_5678",
|
||||
},
|
||||
{
|
||||
"platform": "device",
|
||||
"domain": DOMAIN,
|
||||
"type": "turned_on",
|
||||
"device_id": device_entry.id,
|
||||
"entity_id": f"{DOMAIN}.test_5678",
|
||||
},
|
||||
]
|
||||
triggers = await async_get_device_automations(
|
||||
hass, DeviceAutomationType.TRIGGER, device_entry.id
|
||||
)
|
||||
assert triggers == unordered(expected_triggers)
|
||||
|
||||
|
||||
async def test_if_fires_on_state_change(
|
||||
hass: HomeAssistant, service_calls: list[ServiceCall]
|
||||
) -> None:
|
||||
"""Test for turn_on and turn_off triggers firing."""
|
||||
hass.states.async_set("NEW_DOMAIN.entity", STATE_OFF)
|
||||
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
automation.DOMAIN,
|
||||
{
|
||||
automation.DOMAIN: [
|
||||
{
|
||||
"trigger": {
|
||||
"platform": "device",
|
||||
"domain": DOMAIN,
|
||||
"device_id": "",
|
||||
"entity_id": "NEW_DOMAIN.entity",
|
||||
"type": "turned_on",
|
||||
},
|
||||
"action": {
|
||||
"service": "test.automation",
|
||||
"data_template": {
|
||||
"some": (
|
||||
"turn_on - {{ trigger.platform}} - "
|
||||
"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - "
|
||||
"{{ trigger.to_state.state}} - {{ trigger.for }} - "
|
||||
"{{ trigger.id}}"
|
||||
)
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"trigger": {
|
||||
"platform": "device",
|
||||
"domain": DOMAIN,
|
||||
"device_id": "",
|
||||
"entity_id": "NEW_DOMAIN.entity",
|
||||
"type": "turned_off",
|
||||
},
|
||||
"action": {
|
||||
"service": "test.automation",
|
||||
"data_template": {
|
||||
"some": (
|
||||
"turn_off - {{ trigger.platform}} - "
|
||||
"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - "
|
||||
"{{ trigger.to_state.state}} - {{ trigger.for }} - "
|
||||
"{{ trigger.id}}"
|
||||
)
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
# Fake that the entity is turning on.
|
||||
hass.states.async_set("NEW_DOMAIN.entity", STATE_ON)
|
||||
await hass.async_block_till_done()
|
||||
assert len(service_calls) == 1
|
||||
assert (
|
||||
service_calls[0].data["some"]
|
||||
== "turn_on - device - NEW_DOMAIN.entity - off - on - None - 0"
|
||||
)
|
||||
|
||||
# Fake that the entity is turning off.
|
||||
hass.states.async_set("NEW_DOMAIN.entity", STATE_OFF)
|
||||
await hass.async_block_till_done()
|
||||
assert len(service_calls) == 2
|
||||
assert (
|
||||
service_calls[1].data["some"]
|
||||
== "turn_off - device - NEW_DOMAIN.entity - on - off - None - 0"
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
"""The NEW_NAME integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema({vol.Optional(DOMAIN): {}}, extra=vol.ALLOW_EXTRA)
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
"""Set up the NEW_NAME integration."""
|
||||
return True
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Constants for the NEW_NAME integration."""
|
||||
|
||||
DOMAIN = "NEW_DOMAIN"
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"domain": "NEW_DOMAIN",
|
||||
"name": "NEW_NAME",
|
||||
"codeowners": [],
|
||||
"config_flow": false,
|
||||
"dependencies": [],
|
||||
"documentation": "https://www.home-assistant.io/integrations/NEW_DOMAIN",
|
||||
"homekit": {},
|
||||
"iot_class": "IOT_CLASS",
|
||||
"requirements": [],
|
||||
"ssdp": [],
|
||||
"zeroconf": []
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
rules:
|
||||
# Bronze
|
||||
action-setup: todo
|
||||
appropriate-polling: todo
|
||||
brands: todo
|
||||
common-modules: todo
|
||||
config-flow-test-coverage: todo
|
||||
config-flow: todo
|
||||
dependency-transparency: todo
|
||||
docs-actions: todo
|
||||
docs-high-level-description: todo
|
||||
docs-installation-instructions: todo
|
||||
docs-removal-instructions: todo
|
||||
entity-event-setup: todo
|
||||
entity-unique-id: todo
|
||||
has-entity-name: todo
|
||||
runtime-data: todo
|
||||
test-before-configure: todo
|
||||
test-before-setup: todo
|
||||
unique-config-entry: todo
|
||||
|
||||
# Silver
|
||||
action-exceptions: todo
|
||||
config-entry-unloading: todo
|
||||
docs-configuration-parameters: todo
|
||||
docs-installation-parameters: todo
|
||||
entity-unavailable: todo
|
||||
integration-owner: todo
|
||||
log-when-unavailable: todo
|
||||
parallel-updates: todo
|
||||
reauthentication-flow: todo
|
||||
test-coverage: todo
|
||||
|
||||
# Gold
|
||||
devices: todo
|
||||
diagnostics: todo
|
||||
discovery-update-info: todo
|
||||
discovery: todo
|
||||
docs-data-update: todo
|
||||
docs-examples: todo
|
||||
docs-known-limitations: todo
|
||||
docs-supported-devices: todo
|
||||
docs-supported-functions: todo
|
||||
docs-troubleshooting: todo
|
||||
docs-use-cases: todo
|
||||
dynamic-devices: todo
|
||||
entity-category: todo
|
||||
entity-device-class: todo
|
||||
entity-disabled-by-default: todo
|
||||
entity-translations: todo
|
||||
exception-translations: todo
|
||||
icon-translations: todo
|
||||
reconfiguration-flow: todo
|
||||
repair-issues: todo
|
||||
stale-devices: todo
|
||||
|
||||
# Platinum
|
||||
async-dependency: todo
|
||||
inject-websession: todo
|
||||
strict-typing: todo
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Reproduce an NEW_NAME state."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Iterable
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
SERVICE_TURN_OFF,
|
||||
SERVICE_TURN_ON,
|
||||
STATE_OFF,
|
||||
STATE_ON,
|
||||
)
|
||||
from homeassistant.core import Context, HomeAssistant, State
|
||||
|
||||
from . import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# TODO add valid states here
|
||||
VALID_STATES = {STATE_ON, STATE_OFF}
|
||||
|
||||
|
||||
async def _async_reproduce_state(
|
||||
hass: HomeAssistant,
|
||||
state: State,
|
||||
*,
|
||||
context: Context | None = None,
|
||||
reproduce_options: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""Reproduce a single state."""
|
||||
cur_state = hass.states.get(state.entity_id)
|
||||
|
||||
if cur_state is None:
|
||||
_LOGGER.warning("Unable to find entity %s", state.entity_id)
|
||||
return
|
||||
|
||||
if state.state not in VALID_STATES:
|
||||
_LOGGER.warning(
|
||||
"Invalid state specified for %s: %s", state.entity_id, state.state
|
||||
)
|
||||
return
|
||||
|
||||
# Return if we are already at the right state.
|
||||
if (
|
||||
cur_state.state == state.state
|
||||
and
|
||||
# TODO this is an example attribute
|
||||
cur_state.attributes.get("color") == state.attributes.get("color")
|
||||
):
|
||||
return
|
||||
|
||||
service_data = {ATTR_ENTITY_ID: state.entity_id}
|
||||
|
||||
# TODO determine the services to call to achieve desired state
|
||||
if state.state == STATE_ON:
|
||||
service = SERVICE_TURN_ON
|
||||
if "color" in state.attributes:
|
||||
service_data["color"] = state.attributes["color"]
|
||||
|
||||
elif state.state == STATE_OFF:
|
||||
service = SERVICE_TURN_OFF
|
||||
|
||||
await hass.services.async_call(
|
||||
DOMAIN, service, service_data, context=context, blocking=True
|
||||
)
|
||||
|
||||
|
||||
async def async_reproduce_states(
|
||||
hass: HomeAssistant,
|
||||
states: Iterable[State],
|
||||
*,
|
||||
context: Context | None = None,
|
||||
reproduce_options: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""Reproduce NEW_NAME states."""
|
||||
# TODO pick one and remove other one
|
||||
|
||||
# Reproduce states in parallel.
|
||||
await asyncio.gather(
|
||||
*(
|
||||
_async_reproduce_state(
|
||||
hass, state, context=context, reproduce_options=reproduce_options
|
||||
)
|
||||
for state in states
|
||||
)
|
||||
)
|
||||
|
||||
# Alternative: Reproduce states in sequence
|
||||
# for state in states:
|
||||
# await _async_reproduce_state(hass, state, context=context, reproduce_options=reproduce_options)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Test reproduce state for NEW_NAME."""
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.core import HomeAssistant, State
|
||||
from homeassistant.helpers.state import async_reproduce_state
|
||||
|
||||
from tests.common import async_mock_service
|
||||
|
||||
|
||||
async def test_reproducing_states(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test reproducing NEW_NAME states."""
|
||||
hass.states.async_set("NEW_DOMAIN.entity_off", "off", {})
|
||||
hass.states.async_set("NEW_DOMAIN.entity_on", "on", {"color": "red"})
|
||||
|
||||
turn_on_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_on")
|
||||
turn_off_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_off")
|
||||
|
||||
# These calls should do nothing as entities already in desired state
|
||||
await async_reproduce_state(
|
||||
hass,
|
||||
[
|
||||
State("NEW_DOMAIN.entity_off", "off"),
|
||||
State("NEW_DOMAIN.entity_on", "on", {"color": "red"}),
|
||||
],
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
assert len(turn_on_calls) == 0
|
||||
assert len(turn_off_calls) == 0
|
||||
|
||||
# Test invalid state is handled
|
||||
await async_reproduce_state(
|
||||
hass, [State("NEW_DOMAIN.entity_off", "not_supported")], blocking=True
|
||||
)
|
||||
|
||||
assert "not_supported" in caplog.text
|
||||
assert len(turn_on_calls) == 0
|
||||
assert len(turn_off_calls) == 0
|
||||
|
||||
# Make sure correct services are called
|
||||
await async_reproduce_state(
|
||||
hass,
|
||||
[
|
||||
State("NEW_DOMAIN.entity_on", "off"),
|
||||
State("NEW_DOMAIN.entity_off", "on", {"color": "red"}),
|
||||
# Should not raise
|
||||
State("NEW_DOMAIN.non_existing", "on"),
|
||||
],
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
assert len(turn_on_calls) == 1
|
||||
assert turn_on_calls[0].domain == "NEW_DOMAIN"
|
||||
assert turn_on_calls[0].data == {
|
||||
"entity_id": "NEW_DOMAIN.entity_off",
|
||||
"color": "red",
|
||||
}
|
||||
|
||||
assert len(turn_off_calls) == 1
|
||||
assert turn_off_calls[0].domain == "NEW_DOMAIN"
|
||||
assert turn_off_calls[0].data == {"entity_id": "NEW_DOMAIN.entity_on"}
|
||||
6
home-assistant/script/scaffold/templates/ruff.toml
Normal file
6
home-assistant/script/scaffold/templates/ruff.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
extend = "../../ruff.toml"
|
||||
|
||||
[lint]
|
||||
extend-ignore = [
|
||||
"INP001", # File is part of an implicit namespace package. Add an `__init__.py`.
|
||||
]
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Helper to test significant NEW_NAME state changes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.const import ATTR_DEVICE_CLASS
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
|
||||
|
||||
@callback
|
||||
def async_check_significant_change(
|
||||
hass: HomeAssistant,
|
||||
old_state: str,
|
||||
old_attrs: dict,
|
||||
new_state: str,
|
||||
new_attrs: dict,
|
||||
**kwargs: Any,
|
||||
) -> bool | None:
|
||||
"""Test if state significantly changed."""
|
||||
device_class = new_attrs.get(ATTR_DEVICE_CLASS)
|
||||
|
||||
if device_class is None:
|
||||
return None
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Test the NEW_NAME significant change platform."""
|
||||
|
||||
from homeassistant.components.NEW_DOMAIN.significant_change import (
|
||||
async_check_significant_change,
|
||||
)
|
||||
|
||||
|
||||
async def test_significant_change() -> None:
|
||||
"""Detect NEW_NAME significant changes."""
|
||||
attrs = {}
|
||||
assert not async_check_significant_change(None, "on", attrs, "on", attrs)
|
||||
assert async_check_significant_change(None, "on", attrs, "off", attrs)
|
||||
Reference in New Issue
Block a user