response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Get the zone ID for the target zone name. | def get_zone_id(target_zone_name: str, zones: list[pycfdns.ZoneModel]) -> str | None:
"""Get the zone ID for the target zone name."""
for zone in zones:
if zone["name"] == target_zone_name:
return zone["id"]
return None |
Set up the CMUS platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discover_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the CMUS platform."""
host = config.get(CONF_HOST)
password = config.get(CONF_PASSWORD)
port = config[CONF_PORT]
name = config[CONF_NAME]
cmus_remote = CmusRemote(server=host, port=port, password=password)
cmus_remote.connect()
if cmus_remote.cmus is None:
return
add_entities([CmusDevice(device=cmus_remote, name=name, server=host)], True) |
Return the extra name describing the location if not home. | def get_extra_name(config: Mapping[str, Any]) -> str | None:
"""Return the extra name describing the location if not home."""
if CONF_COUNTRY_CODE in config:
return config[CONF_COUNTRY_CODE] # type: ignore[no-any-return]
if CONF_LATITUDE in config:
return f"{round(config[CONF_LATITUDE], 2)}, {round(config[CONF_LONGITUDE], 2)}"
return None |
Get the user name from Coinbase API credentials. | def get_user_from_client(api_key, api_token):
"""Get the user name from Coinbase API credentials."""
client = Client(api_key, api_token)
return client.get_current_user() |
Create and update a Coinbase Data instance. | def create_and_update_instance(entry: ConfigEntry) -> CoinbaseData:
"""Create and update a Coinbase Data instance."""
client = Client(entry.data[CONF_API_KEY], entry.data[CONF_API_TOKEN])
base_rate = entry.options.get(CONF_EXCHANGE_BASE, "USD")
instance = CoinbaseData(client, base_rate)
instance.update()
return instance |
Handle paginated accounts. | def get_accounts(client):
"""Handle paginated accounts."""
response = client.get_accounts()
accounts = response[API_ACCOUNTS_DATA]
next_starting_after = response.pagination.next_starting_after
while next_starting_after:
response = client.get_accounts(starting_after=next_starting_after)
accounts += response[API_ACCOUNTS_DATA]
next_starting_after = response.pagination.next_starting_after
return accounts |
Get a PIL acceptable input file reference.
Allows us to mock patch during testing to make BytesIO stream. | def _get_file(file_path):
"""Get a PIL acceptable input file reference.
Allows us to mock patch during testing to make BytesIO stream.
"""
return file_path |
Given an image file, extract the predominant color from it. | def _get_color(file_handler) -> tuple:
"""Given an image file, extract the predominant color from it."""
color_thief = ColorThief(file_handler)
# get_color returns a SINGLE RGB value for the given image
color = color_thief.get_color(quality=1)
_LOGGER.debug("Extracted RGB color %s from image", color)
return color |
Return user form schema. | def user_form_schema(user_input: dict[str, Any] | None) -> vol.Schema:
"""Return user form schema."""
user_input = user_input or {}
return vol.Schema(
{
vol.Required(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_PIN, default=DEFAULT_PIN): cv.positive_int,
vol.Required(CONF_TYPE, default=BRIDGE): vol.In(DEVICE_TYPE_LIST),
}
) |
Set up the ComfoConnect fan platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the ComfoConnect fan platform."""
ccb = hass.data[DOMAIN]
add_entities([ComfoConnectFan(ccb)], True) |
Set up the ComfoConnect sensor platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the ComfoConnect sensor platform."""
ccb = hass.data[DOMAIN]
sensors = [
ComfoConnectSensor(ccb=ccb, description=description)
for description in SENSOR_TYPES
if description.key in config[CONF_RESOURCES]
]
add_entities(sensors, True) |
Set up the ComfoConnect bridge. | def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the ComfoConnect bridge."""
conf = config[DOMAIN]
host = conf[CONF_HOST]
name = conf[CONF_NAME]
token = conf[CONF_TOKEN]
user_agent = conf[CONF_USER_AGENT]
pin = conf[CONF_PIN]
# Run discovery on the configured ip
bridges = Bridge.discover(host)
if not bridges:
_LOGGER.error("Could not connect to ComfoConnect bridge on %s", host)
return False
bridge = bridges[0]
_LOGGER.info("Bridge found: %s (%s)", bridge.uuid.hex(), bridge.host)
# Setup ComfoConnect Bridge
ccb = ComfoConnectBridge(hass, bridge, name, token, user_agent, pin)
hass.data[DOMAIN] = ccb
# Start connection with bridge
ccb.connect()
# Schedule disconnect on shutdown
def _shutdown(_event):
ccb.disconnect()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _shutdown)
# Load platforms
discovery.load_platform(hass, Platform.FAN, DOMAIN, {}, config)
return True |
Get the Command Line notification service. | def get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> CommandLineNotificationService:
"""Get the Command Line notification service."""
discovery_info = cast(DiscoveryInfoType, discovery_info)
notify_config = discovery_info
command: str = notify_config[CONF_COMMAND]
timeout: int = notify_config[CONF_COMMAND_TIMEOUT]
return CommandLineNotificationService(command, timeout) |
Validate data point list is greater than polynomial degrees. | def datapoints_greater_than_degree(value: dict) -> dict:
"""Validate data point list is greater than polynomial degrees."""
if len(value[CONF_DATAPOINTS]) <= value[CONF_DEGREE]:
raise vol.Invalid(
f"{CONF_DATAPOINTS} must have at least"
f" {value[CONF_DEGREE]+1} {CONF_DATAPOINTS}"
)
return value |
Set up the Concord232 alarm control panel platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Concord232 alarm control panel platform."""
name = config[CONF_NAME]
code = config.get(CONF_CODE)
mode = config[CONF_MODE]
host = config[CONF_HOST]
port = config[CONF_PORT]
url = f"http://{host}:{port}"
try:
add_entities([Concord232Alarm(url, name, code, mode)], True)
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to Concord232: %s", str(ex)) |
Set up the Concord232 binary sensor platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Concord232 binary sensor platform."""
host = config[CONF_HOST]
port = config[CONF_PORT]
exclude = config[CONF_EXCLUDE_ZONES]
zone_types = config[CONF_ZONE_TYPES]
sensors = []
try:
_LOGGER.debug("Initializing client")
client = concord232_client.Client(f"http://{host}:{port}")
client.zones = client.list_zones()
client.last_zone_update = dt_util.utcnow()
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to Concord232: %s", str(ex))
return
# The order of zones returned by client.list_zones() can vary.
# When the zones are not named, this can result in the same entity
# name mapping to different sensors in an unpredictable way. Sort
# the zones by zone number to prevent this.
client.zones.sort(key=lambda zone: zone["number"])
for zone in client.zones:
_LOGGER.info("Loading Zone found: %s", zone["name"])
if zone["number"] not in exclude:
sensors.append(
Concord232ZoneSensor(
hass,
client,
zone,
zone_types.get(zone["number"], get_opening_type(zone)),
)
)
add_entities(sensors, True) |
Return the result of the type guessing from name. | def get_opening_type(zone):
"""Return the result of the type guessing from name."""
if "MOTION" in zone["name"]:
return BinarySensorDeviceClass.MOTION
if "KEY" in zone["name"]:
return BinarySensorDeviceClass.SAFETY
if "SMOKE" in zone["name"]:
return BinarySensorDeviceClass.SMOKE
if "WATER" in zone["name"]:
return "water"
return BinarySensorDeviceClass.OPENING |
Enable the Area Registry views. | def async_setup(hass: HomeAssistant) -> bool:
"""Enable the Area Registry views."""
websocket_api.async_register_command(hass, websocket_list_areas)
websocket_api.async_register_command(hass, websocket_create_area)
websocket_api.async_register_command(hass, websocket_delete_area)
websocket_api.async_register_command(hass, websocket_update_area)
return True |
Handle list areas command. | def websocket_list_areas(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle list areas command."""
registry = async_get(hass)
connection.send_result(
msg["id"],
[_entry_dict(entry) for entry in registry.async_list_areas()],
) |
Create area command. | def websocket_create_area(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Create area command."""
registry = async_get(hass)
data = dict(msg)
data.pop("type")
data.pop("id")
if "aliases" in data:
# Convert aliases to a set
data["aliases"] = set(data["aliases"])
if "labels" in data:
# Convert labels to a set
data["labels"] = set(data["labels"])
try:
entry = registry.async_create(**data)
except ValueError as err:
connection.send_error(msg["id"], "invalid_info", str(err))
else:
connection.send_result(msg["id"], _entry_dict(entry)) |
Delete area command. | def websocket_delete_area(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Delete area command."""
registry = async_get(hass)
try:
registry.async_delete(msg["area_id"])
except KeyError:
connection.send_error(msg["id"], "invalid_info", "Area ID doesn't exist")
else:
connection.send_message(websocket_api.result_message(msg["id"], "success")) |
Handle update area websocket command. | def websocket_update_area(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle update area websocket command."""
registry = async_get(hass)
data = dict(msg)
data.pop("type")
data.pop("id")
if "aliases" in data:
# Convert aliases to a set
data["aliases"] = set(data["aliases"])
if "labels" in data:
# Convert labels to a set
data["labels"] = set(data["labels"])
try:
entry = registry.async_update(**data)
except ValueError as err:
connection.send_error(msg["id"], "invalid_info", str(err))
else:
connection.send_result(msg["id"], _entry_dict(entry)) |
Convert entry to API format. | def _entry_dict(entry: AreaEntry) -> dict[str, Any]:
"""Convert entry to API format."""
return {
"aliases": list(entry.aliases),
"area_id": entry.id,
"floor_id": entry.floor_id,
"icon": entry.icon,
"labels": list(entry.labels),
"name": entry.name,
"picture": entry.picture,
} |
Enable the Home Assistant views. | def async_setup(hass: HomeAssistant) -> bool:
"""Enable the Home Assistant views."""
websocket_api.async_register_command(
hass, WS_TYPE_LIST, websocket_list, SCHEMA_WS_LIST
)
websocket_api.async_register_command(
hass, WS_TYPE_DELETE, websocket_delete, SCHEMA_WS_DELETE
)
websocket_api.async_register_command(hass, websocket_create)
websocket_api.async_register_command(hass, websocket_update)
return True |
Format a user. | def _user_info(user: User) -> dict[str, Any]:
"""Format a user."""
ha_username = next(
(
cred.data.get("username")
for cred in user.credentials
if cred.auth_provider_type == "homeassistant"
),
None,
)
return {
"id": user.id,
"username": ha_username,
"name": user.name,
"is_owner": user.is_owner,
"is_active": user.is_active,
"local_only": user.local_only,
"system_generated": user.system_generated,
"group_ids": [group.id for group in user.groups],
"credentials": [{"type": c.auth_provider_type} for c in user.credentials],
} |
Enable the Home Assistant views. | def async_setup(hass: HomeAssistant) -> bool:
"""Enable the Home Assistant views."""
websocket_api.async_register_command(hass, websocket_create)
websocket_api.async_register_command(hass, websocket_delete)
websocket_api.async_register_command(hass, websocket_change_password)
websocket_api.async_register_command(hass, websocket_admin_change_password)
return True |
Set up the Automation config API. | def async_setup(hass: HomeAssistant) -> bool:
"""Set up the Automation config API."""
async def hook(action: str, config_key: str) -> None:
"""post_write_hook for Config View that reloads automations."""
if action != ACTION_DELETE:
await hass.services.async_call(
DOMAIN, SERVICE_RELOAD, {CONF_ID: config_key}
)
return
ent_reg = er.async_get(hass)
entity_id = ent_reg.async_get_entity_id(DOMAIN, DOMAIN, config_key)
if entity_id is None:
return
ent_reg.async_remove(entity_id)
hass.http.register_view(
EditAutomationConfigView(
DOMAIN,
"config",
AUTOMATION_CONFIG_PATH,
cv.string,
PLATFORM_SCHEMA,
post_write_hook=hook,
data_validator=async_validate_config_item,
)
)
return True |
Register the category registry WS commands. | def async_setup(hass: HomeAssistant) -> bool:
"""Register the category registry WS commands."""
websocket_api.async_register_command(hass, websocket_list_categories)
websocket_api.async_register_command(hass, websocket_create_category)
websocket_api.async_register_command(hass, websocket_delete_category)
websocket_api.async_register_command(hass, websocket_update_category)
return True |
Handle list categories command. | def websocket_list_categories(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle list categories command."""
category_registry = cr.async_get(hass)
connection.send_result(
msg["id"],
[
_entry_dict(entry)
for entry in category_registry.async_list_categories(scope=msg["scope"])
],
) |
Create category command. | def websocket_create_category(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Create category command."""
category_registry = cr.async_get(hass)
data = dict(msg)
data.pop("type")
data.pop("id")
try:
entry = category_registry.async_create(**data)
except ValueError as err:
connection.send_error(msg["id"], "invalid_info", str(err))
else:
connection.send_result(msg["id"], _entry_dict(entry)) |
Delete category command. | def websocket_delete_category(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Delete category command."""
category_registry = cr.async_get(hass)
try:
category_registry.async_delete(
scope=msg["scope"], category_id=msg["category_id"]
)
except KeyError:
connection.send_error(msg["id"], "invalid_info", "Category ID doesn't exist")
else:
connection.send_result(msg["id"]) |
Handle update category websocket command. | def websocket_update_category(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle update category websocket command."""
category_registry = cr.async_get(hass)
data = dict(msg)
data.pop("type")
data.pop("id")
try:
entry = category_registry.async_update(**data)
except ValueError as err:
connection.send_error(msg["id"], "invalid_info", str(err))
except KeyError:
connection.send_error(msg["id"], "invalid_info", "Category ID doesn't exist")
else:
connection.send_result(msg["id"], _entry_dict(entry)) |
Convert entry to API format. | def _entry_dict(entry: cr.CategoryEntry) -> dict[str, Any]:
"""Convert entry to API format."""
return {
"category_id": entry.category_id,
"icon": entry.icon,
"name": entry.name,
} |
Enable the Home Assistant views. | def async_setup(hass: HomeAssistant) -> bool:
"""Enable the Home Assistant views."""
hass.http.register_view(ConfigManagerEntryIndexView)
hass.http.register_view(ConfigManagerEntryResourceView)
hass.http.register_view(ConfigManagerEntryResourceReloadView)
hass.http.register_view(ConfigManagerFlowIndexView(hass.config_entries.flow))
hass.http.register_view(ConfigManagerFlowResourceView(hass.config_entries.flow))
hass.http.register_view(ConfigManagerAvailableFlowView)
hass.http.register_view(OptionManagerFlowIndexView(hass.config_entries.options))
hass.http.register_view(OptionManagerFlowResourceView(hass.config_entries.options))
websocket_api.async_register_command(hass, config_entries_get)
websocket_api.async_register_command(hass, config_entry_disable)
websocket_api.async_register_command(hass, config_entry_get_single)
websocket_api.async_register_command(hass, config_entry_update)
websocket_api.async_register_command(hass, config_entries_subscribe)
websocket_api.async_register_command(hass, config_entries_progress)
websocket_api.async_register_command(hass, ignore_config_flow)
return True |
Convert result to JSON. | def _prepare_config_flow_result_json(
result: data_entry_flow.FlowResult,
prepare_result_json: Callable[
[data_entry_flow.FlowResult], data_entry_flow.FlowResult
],
) -> data_entry_flow.FlowResult:
"""Convert result to JSON."""
if result["type"] != data_entry_flow.FlowResultType.CREATE_ENTRY:
return prepare_result_json(result)
data = result.copy()
entry: config_entries.ConfigEntry = data["result"]
data["result"] = entry.as_json_fragment
data.pop("data")
data.pop("context")
return data |
List flows that are in progress but not started by a user.
Example of a non-user initiated flow is a discovered Hue hub that
requires user interaction to finish setup. | def config_entries_progress(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""List flows that are in progress but not started by a user.
Example of a non-user initiated flow is a discovered Hue hub that
requires user interaction to finish setup.
"""
connection.send_result(
msg["id"],
[
flw
for flw in hass.config_entries.flow.async_progress()
if flw["context"]["source"] != config_entries.SOURCE_USER
],
) |
Send Config entry not found error. | def send_entry_not_found(
connection: websocket_api.ActiveConnection, msg_id: int
) -> None:
"""Send Config entry not found error."""
connection.send_error(
msg_id, websocket_api.const.ERR_NOT_FOUND, "Config entry not found"
) |
Get entry, send error message if it doesn't exist. | def get_entry(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
entry_id: str,
msg_id: int,
) -> config_entries.ConfigEntry | None:
"""Get entry, send error message if it doesn't exist."""
if (entry := hass.config_entries.async_get_entry(entry_id)) is None:
send_entry_not_found(connection, msg_id)
return entry |
Set up the Hassbian config. | def async_setup(hass: HomeAssistant) -> bool:
"""Set up the Hassbian config."""
hass.http.register_view(CheckConfigView)
websocket_api.async_register_command(hass, websocket_update_config)
websocket_api.async_register_command(hass, websocket_detect_config)
return True |
Enable the Device Registry views. | def async_setup(hass: HomeAssistant) -> bool:
"""Enable the Device Registry views."""
websocket_api.async_register_command(hass, websocket_list_devices)
websocket_api.async_register_command(hass, websocket_update_device)
websocket_api.async_register_command(
hass, websocket_remove_config_entry_from_device
)
return True |
Handle list devices command. | def websocket_list_devices(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle list devices command."""
registry = async_get(hass)
# Build start of response message
msg_json_prefix = (
f'{{"id":{msg["id"]},"type": "{websocket_api.const.TYPE_RESULT}",'
f'"success":true,"result": ['
).encode()
# Concatenate cached entity registry item JSON serializations
inner = b",".join(
[
entry.json_repr
for entry in registry.devices.values()
if entry.json_repr is not None
]
)
msg_json = b"".join((msg_json_prefix, inner, b"]}"))
connection.send_message(msg_json) |
Handle update device websocket command. | def websocket_update_device(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle update device websocket command."""
registry = async_get(hass)
msg.pop("type")
msg_id = msg.pop("id")
if msg.get("disabled_by") is not None:
msg["disabled_by"] = DeviceEntryDisabler(msg["disabled_by"])
if "labels" in msg:
# Convert labels to a set
msg["labels"] = set(msg["labels"])
entry = cast(DeviceEntry, registry.async_update_device(**msg))
connection.send_message(websocket_api.result_message(msg_id, entry.dict_repr)) |
Enable the Entity Registry views. | def async_setup(hass: HomeAssistant) -> bool:
"""Enable the Entity Registry views."""
websocket_api.async_register_command(hass, websocket_get_entities)
websocket_api.async_register_command(hass, websocket_get_entity)
websocket_api.async_register_command(hass, websocket_list_entities_for_display)
websocket_api.async_register_command(hass, websocket_list_entities)
websocket_api.async_register_command(hass, websocket_remove_entity)
websocket_api.async_register_command(hass, websocket_update_entity)
return True |
Handle list registry entries command. | def websocket_list_entities(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle list registry entries command."""
registry = er.async_get(hass)
# Build start of response message
msg_json_prefix = (
f'{{"id":{msg["id"]},"type": "{websocket_api.const.TYPE_RESULT}",'
'"success":true,"result": ['
).encode()
# Concatenate cached entity registry item JSON serializations
inner = b",".join(
[
entry.partial_json_repr
for entry in registry.entities.values()
if entry.partial_json_repr is not None
]
)
msg_json = b"".join((msg_json_prefix, inner, b"]}"))
connection.send_message(msg_json) |
Handle list registry entries command. | def websocket_list_entities_for_display(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle list registry entries command."""
registry = er.async_get(hass)
# Build start of response message
msg_json_prefix = (
f'{{"id":{msg["id"]},"type":"{websocket_api.const.TYPE_RESULT}","success":true,'
f'"result":{{"entity_categories":{_ENTITY_CATEGORIES_JSON},"entities":['
).encode()
# Concatenate cached entity registry item JSON serializations
inner = b",".join(
[
entry.display_json_repr
for entry in registry.entities.values()
if entry.disabled_by is None and entry.display_json_repr is not None
]
)
msg_json = b"".join((msg_json_prefix, inner, b"]}}"))
connection.send_message(msg_json) |
Handle get entity registry entry command.
Async friendly. | def websocket_get_entity(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle get entity registry entry command.
Async friendly.
"""
registry = er.async_get(hass)
if (entry := registry.entities.get(msg["entity_id"])) is None:
connection.send_message(
websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found")
)
return
connection.send_message(
websocket_api.result_message(msg["id"], entry.extended_dict)
) |
Handle get entity registry entries command.
Async friendly. | def websocket_get_entities(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle get entity registry entries command.
Async friendly.
"""
registry = er.async_get(hass)
entity_ids = msg["entity_ids"]
entries: dict[str, dict[str, Any] | None] = {}
for entity_id in entity_ids:
entry = registry.entities.get(entity_id)
entries[entity_id] = entry.extended_dict if entry else None
connection.send_message(websocket_api.result_message(msg["id"], entries)) |
Handle update entity websocket command.
Async friendly. | def websocket_update_entity(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle update entity websocket command.
Async friendly.
"""
registry = er.async_get(hass)
entity_id = msg["entity_id"]
if not (entity_entry := registry.async_get(entity_id)):
connection.send_message(
websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found")
)
return
changes = {}
for key in (
"area_id",
"device_class",
"disabled_by",
"hidden_by",
"icon",
"name",
"new_entity_id",
):
if key in msg:
changes[key] = msg[key]
if "aliases" in msg:
# Convert aliases to a set
changes["aliases"] = set(msg["aliases"])
if "labels" in msg:
# Convert labels to a set
changes["labels"] = set(msg["labels"])
if "disabled_by" in msg and msg["disabled_by"] is None:
# Don't allow enabling an entity of a disabled device
if entity_entry.device_id:
device_registry = dr.async_get(hass)
device = device_registry.async_get(entity_entry.device_id)
if device and device.disabled:
connection.send_message(
websocket_api.error_message(
msg["id"], "invalid_info", "Device is disabled"
)
)
return
# Update the categories if provided
if "categories" in msg:
categories = entity_entry.categories.copy()
for scope, category_id in msg["categories"].items():
if scope in categories and category_id is None:
# Remove the category from the scope as it was unset
del categories[scope]
elif category_id is not None:
# Add or update the category for the given scope
categories[scope] = category_id
changes["categories"] = categories
try:
if changes:
entity_entry = registry.async_update_entity(entity_id, **changes)
except ValueError as err:
connection.send_message(
websocket_api.error_message(msg["id"], "invalid_info", str(err))
)
return
if "new_entity_id" in msg:
entity_id = msg["new_entity_id"]
try:
if "options_domain" in msg:
entity_entry = registry.async_update_entity_options(
entity_id, msg["options_domain"], msg["options"]
)
except ValueError as err:
connection.send_message(
websocket_api.error_message(msg["id"], "invalid_info", str(err))
)
return
result: dict[str, Any] = {"entity_entry": entity_entry.extended_dict}
if "disabled_by" in changes and changes["disabled_by"] is None:
# Enabling an entity requires a config entry reload, or HA restart
if (
not (config_entry_id := entity_entry.config_entry_id)
or (config_entry := hass.config_entries.async_get_entry(config_entry_id))
and not config_entry.supports_unload
):
result["require_restart"] = True
else:
result["reload_delay"] = config_entries.RELOAD_AFTER_UPDATE_DELAY
connection.send_result(msg["id"], result) |
Handle remove entity websocket command.
Async friendly. | def websocket_remove_entity(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Handle remove entity websocket command.
Async friendly.
"""
registry = er.async_get(hass)
if msg["entity_id"] not in registry.entities:
connection.send_message(
websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found")
)
return
registry.async_remove(msg["entity_id"])
connection.send_message(websocket_api.result_message(msg["id"])) |
Register the floor registry WS commands. | def async_setup(hass: HomeAssistant) -> bool:
"""Register the floor registry WS commands."""
websocket_api.async_register_command(hass, websocket_list_floors)
websocket_api.async_register_command(hass, websocket_create_floor)
websocket_api.async_register_command(hass, websocket_delete_floor)
websocket_api.async_register_command(hass, websocket_update_floor)
return True |
Handle list floors command. | def websocket_list_floors(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle list floors command."""
registry = async_get(hass)
connection.send_result(
msg["id"],
[_entry_dict(entry) for entry in registry.async_list_floors()],
) |
Create floor command. | def websocket_create_floor(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Create floor command."""
registry = async_get(hass)
data = dict(msg)
data.pop("type")
data.pop("id")
if "aliases" in data:
# Convert aliases to a set
data["aliases"] = set(data["aliases"])
try:
entry = registry.async_create(**data)
except ValueError as err:
connection.send_error(msg["id"], "invalid_info", str(err))
else:
connection.send_result(msg["id"], _entry_dict(entry)) |
Delete floor command. | def websocket_delete_floor(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Delete floor command."""
registry = async_get(hass)
try:
registry.async_delete(msg["floor_id"])
except KeyError:
connection.send_error(msg["id"], "invalid_info", "Floor ID doesn't exist")
else:
connection.send_result(msg["id"]) |
Handle update floor websocket command. | def websocket_update_floor(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle update floor websocket command."""
registry = async_get(hass)
data = dict(msg)
data.pop("type")
data.pop("id")
if "aliases" in data:
# Convert aliases to a set
data["aliases"] = set(data["aliases"])
try:
entry = registry.async_update(**data)
except ValueError as err:
connection.send_error(msg["id"], "invalid_info", str(err))
else:
connection.send_result(msg["id"], _entry_dict(entry)) |
Convert entry to API format. | def _entry_dict(entry: FloorEntry) -> dict[str, Any]:
"""Convert entry to API format."""
return {
"aliases": list(entry.aliases),
"floor_id": entry.floor_id,
"icon": entry.icon,
"level": entry.level,
"name": entry.name,
} |
Register the Label Registry WS commands. | def async_setup(hass: HomeAssistant) -> bool:
"""Register the Label Registry WS commands."""
websocket_api.async_register_command(hass, websocket_list_labels)
websocket_api.async_register_command(hass, websocket_create_label)
websocket_api.async_register_command(hass, websocket_delete_label)
websocket_api.async_register_command(hass, websocket_update_label)
return True |
Handle list labels command. | def websocket_list_labels(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle list labels command."""
registry = async_get(hass)
connection.send_result(
msg["id"],
[_entry_dict(entry) for entry in registry.async_list_labels()],
) |
Create label command. | def websocket_create_label(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Create label command."""
registry = async_get(hass)
data = dict(msg)
data.pop("type")
data.pop("id")
try:
entry = registry.async_create(**data)
except ValueError as err:
connection.send_error(msg["id"], "invalid_info", str(err))
else:
connection.send_result(msg["id"], _entry_dict(entry)) |
Delete label command. | def websocket_delete_label(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Delete label command."""
registry = async_get(hass)
try:
registry.async_delete(msg["label_id"])
except KeyError:
connection.send_error(msg["id"], "invalid_info", "Label ID doesn't exist")
else:
connection.send_result(msg["id"]) |
Handle update label websocket command. | def websocket_update_label(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle update label websocket command."""
registry = async_get(hass)
data = dict(msg)
data.pop("type")
data.pop("id")
try:
entry = registry.async_update(**data)
except ValueError as err:
connection.send_error(msg["id"], "invalid_info", str(err))
else:
connection.send_result(msg["id"], _entry_dict(entry)) |
Convert entry to API format. | def _entry_dict(entry: LabelEntry) -> dict[str, Any]:
"""Convert entry to API format."""
return {
"color": entry.color,
"description": entry.description,
"icon": entry.icon,
"label_id": entry.label_id,
"name": entry.name,
} |
Set up the Scene config API. | def async_setup(hass: HomeAssistant) -> bool:
"""Set up the Scene config API."""
async def hook(action: str, config_key: str) -> None:
"""post_write_hook for Config View that reloads scenes."""
if action != ACTION_DELETE:
await hass.services.async_call(DOMAIN, SERVICE_RELOAD)
return
ent_reg = er.async_get(hass)
entity_id = ent_reg.async_get_entity_id(DOMAIN, HA_DOMAIN, config_key)
if entity_id is None:
return
ent_reg.async_remove(entity_id)
hass.http.register_view(
EditSceneConfigView(
DOMAIN,
"config",
SCENE_CONFIG_PATH,
cv.string,
PLATFORM_SCHEMA,
post_write_hook=hook,
)
)
return True |
Set up the script config API. | def async_setup(hass: HomeAssistant) -> bool:
"""Set up the script config API."""
async def hook(action: str, config_key: str) -> None:
"""post_write_hook for Config View that reloads scripts."""
if action != ACTION_DELETE:
await hass.services.async_call(DOMAIN, SERVICE_RELOAD)
return
ent_reg = er.async_get(hass)
entity_id = ent_reg.async_get_entity_id(DOMAIN, DOMAIN, config_key)
if entity_id is None:
return
ent_reg.async_remove(entity_id)
hass.http.register_view(
EditScriptConfigView(
DOMAIN,
"config",
SCRIPT_CONFIG_PATH,
cv.slug,
SCRIPT_ENTITY_SCHEMA,
post_write_hook=hook,
data_validator=async_validate_config_item,
)
)
return True |
Read YAML helper. | def _read(path: str) -> JSON_TYPE | None:
"""Read YAML helper."""
if not os.path.isfile(path):
return None
return load_yaml(path) |
Write YAML helper. | def _write(path: str, data: dict | list) -> None:
"""Write YAML helper."""
# Do it before opening file. If dump causes error it will now not
# truncate the file.
contents = dump(data)
write_utf8_file_atomic(path, contents) |
Create a new request for configuration.
Will return an ID to be used for sequent calls. | def async_request_config(
hass: HomeAssistant,
name: str,
callback: ConfiguratorCallback | None = None,
description: str | None = None,
description_image: str | None = None,
submit_caption: str | None = None,
fields: list[dict[str, str]] | None = None,
link_name: str | None = None,
link_url: str | None = None,
entity_picture: str | None = None,
) -> str:
"""Create a new request for configuration.
Will return an ID to be used for sequent calls.
"""
if description and link_name is not None and link_url is not None:
description += f"\n\n[{link_name}]({link_url})"
if description and description_image is not None:
description += f"\n\n"
if (instance := hass.data.get(_KEY_INSTANCE)) is None:
instance = hass.data[_KEY_INSTANCE] = Configurator(hass)
request_id = instance.async_request_config(
name, callback, description, submit_caption, fields, entity_picture
)
if DATA_REQUESTS not in hass.data:
hass.data[DATA_REQUESTS] = {}
_get_requests(hass)[request_id] = instance
return request_id |
Create a new request for configuration.
Will return an ID to be used for sequent calls. | def request_config(hass: HomeAssistant, *args: Any, **kwargs: Any) -> str:
"""Create a new request for configuration.
Will return an ID to be used for sequent calls.
"""
return run_callback_threadsafe(
hass.loop, ft.partial(async_request_config, hass, *args, **kwargs)
).result() |
Add errors to a config request. | def async_notify_errors(hass: HomeAssistant, request_id: str, error: str) -> None:
"""Add errors to a config request."""
with suppress(KeyError): # If request_id does not exist
_get_requests(hass)[request_id].async_notify_errors(request_id, error) |
Add errors to a config request. | def notify_errors(hass: HomeAssistant, request_id: str, error: str) -> None:
"""Add errors to a config request."""
return run_callback_threadsafe(
hass.loop, async_notify_errors, hass, request_id, error
).result() |
Mark a configuration request as done. | def async_request_done(hass: HomeAssistant, request_id: str) -> None:
"""Mark a configuration request as done."""
with suppress(KeyError): # If request_id does not exist
_get_requests(hass).pop(request_id).async_request_done(request_id) |
Mark a configuration request as done. | def request_done(hass: HomeAssistant, request_id: str) -> None:
"""Mark a configuration request as done."""
return run_callback_threadsafe(
hass.loop, async_request_done, hass, request_id
).result() |
Return typed configurator_requests data. | def _get_requests(hass: HomeAssistant) -> dict[str, Configurator]:
"""Return typed configurator_requests data."""
return hass.data[DATA_REQUESTS] |
Get the active agent. | def get_agent_manager(hass: HomeAssistant) -> AgentManager:
"""Get the active agent."""
return AgentManager(hass) |
Validate agent ID. | def agent_id_validator(value: Any) -> str:
"""Validate agent ID."""
hass = async_get_hass()
if async_get_agent(hass, cv.string(value)) is None:
raise vol.Invalid("invalid agent ID")
return value |
Get specified agent. | def async_get_agent(
hass: HomeAssistant, agent_id: str | None = None
) -> AbstractConversationAgent | ConversationEntity | None:
"""Get specified agent."""
if agent_id is None or agent_id in (HOME_ASSISTANT_AGENT, OLD_HOME_ASSISTANT_AGENT):
return async_get_default_agent(hass)
if "." in agent_id:
entity_component: EntityComponent[ConversationEntity] = hass.data[DOMAIN]
return entity_component.get_entity(agent_id)
manager = get_agent_manager(hass)
if not manager.async_is_valid_agent_id(agent_id):
return None
return manager.async_get_agent(agent_id) |
Get the default agent. | def async_get_default_agent(hass: core.HomeAssistant) -> DefaultAgent:
"""Get the default agent."""
return hass.data[DATA_DEFAULT_ENTITY] |
Wrap json_loads for get_intents. | def json_load(fp: IO[str]) -> JsonObjectType:
"""Wrap json_loads for get_intents."""
return json_loads_object(fp.read()) |
Generate language codes with and without region. | def _get_language_variations(language: str) -> Iterable[str]:
"""Generate language codes with and without region."""
yield language
parts = re.split(r"([-_])", language)
if len(parts) == 3:
lang, sep, region = parts
if sep == "_":
# en_US -> en-US
yield f"{lang}-{region}"
# en-US -> en
yield lang |
Create conversation result with error code and text. | def _make_error_result(
language: str,
error_code: intent.IntentResponseErrorCode,
response_text: str,
conversation_id: str | None = None,
) -> ConversationResult:
"""Create conversation result with error code and text."""
response = intent.IntentResponse(language=language)
response.async_set_error(error_code, response_text)
return ConversationResult(response, conversation_id) |
Get key and template arguments for error when there are unmatched intent entities/slots. | def _get_unmatched_response(result: RecognizeResult) -> tuple[ErrorKey, dict[str, Any]]:
"""Get key and template arguments for error when there are unmatched intent entities/slots."""
# Filter out non-text and missing context entities
unmatched_text: dict[str, str] = {
key: entity.text.strip()
for key, entity in result.unmatched_entities.items()
if isinstance(entity, UnmatchedTextEntity) and entity.text != MISSING_ENTITY
}
if unmatched_area := unmatched_text.get("area"):
# area only
return ErrorKey.NO_AREA, {"area": unmatched_area}
if unmatched_floor := unmatched_text.get("floor"):
# floor only
return ErrorKey.NO_FLOOR, {"floor": unmatched_floor}
# Area may still have matched
matched_area: str | None = None
if matched_area_entity := result.entities.get("area"):
matched_area = matched_area_entity.text.strip()
if unmatched_name := unmatched_text.get("name"):
if matched_area:
# device in area
return ErrorKey.NO_ENTITY_IN_AREA, {
"entity": unmatched_name,
"area": matched_area,
}
# device only
return ErrorKey.NO_ENTITY, {"entity": unmatched_name}
# Default error
return ErrorKey.NO_INTENT, {} |
Return key and template arguments for error when intent returns no matching states. | def _get_no_states_matched_response(
no_states_error: intent.NoStatesMatchedError,
) -> tuple[ErrorKey, dict[str, Any]]:
"""Return key and template arguments for error when intent returns no matching states."""
# Device classes should be checked before domains
if no_states_error.device_classes:
device_class = next(iter(no_states_error.device_classes)) # first device class
if no_states_error.area:
# device_class in area
return ErrorKey.NO_DEVICE_CLASS_IN_AREA, {
"device_class": device_class,
"area": no_states_error.area,
}
# device_class only
return ErrorKey.NO_DEVICE_CLASS, {"device_class": device_class}
if no_states_error.domains:
domain = next(iter(no_states_error.domains)) # first domain
if no_states_error.area:
# domain in area
return ErrorKey.NO_DOMAIN_IN_AREA, {
"domain": domain,
"area": no_states_error.area,
}
if no_states_error.floor:
# domain in floor
return ErrorKey.NO_DOMAIN_IN_FLOOR, {
"domain": domain,
"floor": no_states_error.floor,
}
# domain only
return ErrorKey.NO_DOMAIN, {"domain": domain}
# Default error
return ErrorKey.NO_INTENT, {} |
Return key and template arguments for error when intent returns duplicate matches. | def _get_duplicate_names_matched_response(
duplicate_names_error: intent.DuplicateNamesMatchedError,
) -> tuple[ErrorKey, dict[str, Any]]:
"""Return key and template arguments for error when intent returns duplicate matches."""
if duplicate_names_error.area:
return ErrorKey.DUPLICATE_ENTITIES_IN_AREA, {
"entity": duplicate_names_error.name,
"area": duplicate_names_error.area,
}
return ErrorKey.DUPLICATE_ENTITIES, {"entity": duplicate_names_error.name} |
Collect list reference names recursively. | def _collect_list_references(expression: Expression, list_names: set[str]) -> None:
"""Collect list reference names recursively."""
if isinstance(expression, Sequence):
seq: Sequence = expression
for item in seq.items:
_collect_list_references(item, list_names)
elif isinstance(expression, ListReference):
# {list}
list_ref: ListReference = expression
list_names.add(list_ref.slot_name) |
Set up the HTTP API for the conversation integration. | def async_setup(hass: HomeAssistant) -> None:
"""Set up the HTTP API for the conversation integration."""
hass.http.register_view(ConversationProcessView())
websocket_api.async_register_command(hass, websocket_process)
websocket_api.async_register_command(hass, websocket_prepare)
websocket_api.async_register_command(hass, websocket_list_agents)
websocket_api.async_register_command(hass, websocket_hass_agent_debug) |
Yield state/is_matched pairs for a hassil recognition. | def _get_debug_targets(
hass: HomeAssistant,
result: RecognizeResult,
) -> Iterable[tuple[State, bool]]:
"""Yield state/is_matched pairs for a hassil recognition."""
entities = result.entities
name: str | None = None
area_name: str | None = None
domains: set[str] | None = None
device_classes: set[str] | None = None
state_names: set[str] | None = None
if "name" in entities:
name = str(entities["name"].value)
if "area" in entities:
area_name = str(entities["area"].value)
if "domain" in entities:
domains = set(cv.ensure_list(entities["domain"].value))
if "device_class" in entities:
device_classes = set(cv.ensure_list(entities["device_class"].value))
if "state" in entities:
# HassGetState only
state_names = set(cv.ensure_list(entities["state"].value))
if (
(name is None)
and (area_name is None)
and (not domains)
and (not device_classes)
and (not state_names)
):
# Avoid "matching" all entities when there is no filter
return
states = intent.async_match_states(
hass,
name=name,
area_name=area_name,
domains=domains,
device_classes=device_classes,
)
for state in states:
# For queries, a target is "matched" based on its state
is_matched = (state_names is None) or (state.state in state_names)
yield state, is_matched |
Return a dict of unmatched text/range slot entities. | def _get_unmatched_slots(
result: RecognizeResult,
) -> dict[str, str | int]:
"""Return a dict of unmatched text/range slot entities."""
unmatched_slots: dict[str, str | int] = {}
for entity in result.unmatched_entities_list:
if isinstance(entity, UnmatchedTextEntity):
if entity.text == MISSING_ENTITY:
# Don't report <missing> since these are just missing context
# slots.
continue
unmatched_slots[entity.name] = entity.text
elif isinstance(entity, UnmatchedRangeEntity):
unmatched_slots[entity.name] = entity.value
return unmatched_slots |
Validate result does not contain punctuation. | def has_no_punctuation(value: list[str]) -> list[str]:
"""Validate result does not contain punctuation."""
for sentence in value:
if PUNCTUATION.search(sentence):
raise vol.Invalid("sentence should not contain punctuation")
return value |
Validate result has at least one item. | def has_one_non_empty_item(value: list[str]) -> list[str]:
"""Validate result has at least one item."""
if len(value) < 1:
raise vol.Invalid("at least one sentence is required")
for sentence in value:
if not sentence:
raise vol.Invalid(f"sentence too short: '{sentence}'")
return value |
Create a regex that matches the utterance. | def create_matcher(utterance: str) -> re.Pattern[str]:
"""Create a regex that matches the utterance."""
# Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL
# Pattern matches (GROUP|OPTIONAL): Change light to [the color] {name}
parts = re.split(r"({\w+}|\[[\w\s]+\] *)", utterance)
# Pattern to extract name from GROUP part. Matches {name}
group_matcher = re.compile(r"{(\w+)}")
# Pattern to extract text from OPTIONAL part. Matches [the color]
optional_matcher = re.compile(r"\[([\w ]+)\] *")
pattern = ["^"]
for part in parts:
group_match = group_matcher.match(part)
optional_match = optional_matcher.match(part)
# Normal part
if group_match is None and optional_match is None:
pattern.append(part)
continue
# Group part
if group_match is not None:
pattern.append(rf"(?P<{group_match.groups()[0]}>[\w ]+?)\s*")
# Optional part
elif optional_match is not None:
pattern.append(rf"(?:{optional_match.groups()[0]} *)?")
pattern.append("$")
return re.compile("".join(pattern), re.I) |
Set the agent to handle the conversations. | def async_set_agent(
hass: HomeAssistant,
config_entry: ConfigEntry,
agent: AbstractConversationAgent,
) -> None:
"""Set the agent to handle the conversations."""
get_agent_manager(hass).async_set_agent(config_entry.entry_id, agent) |
Set the agent to handle the conversations. | def async_unset_agent(
hass: HomeAssistant,
config_entry: ConfigEntry,
) -> None:
"""Set the agent to handle the conversations."""
get_agent_manager(hass).async_unset_agent(config_entry.entry_id) |
Get information on the agent or None if not found. | def async_get_agent_info(
hass: HomeAssistant,
agent_id: str | None = None,
) -> AgentInfo | None:
"""Get information on the agent or None if not found."""
agent = async_get_agent(hass, agent_id)
if agent is None:
return None
if isinstance(agent, ConversationEntity):
name = agent.name
if not isinstance(name, str):
name = agent.entity_id
return AgentInfo(id=agent.entity_id, name=name)
manager = get_agent_manager(hass)
for agent_info in manager.async_get_agent_info():
if agent_info.id == agent_id:
return agent_info
return None |
Create a function to test a device condition. | def async_condition_from_config(
hass: HomeAssistant, config: ConfigType
) -> condition.ConditionCheckerType:
"""Create a function to test a device condition."""
registry = er.async_get(hass)
entity_id = er.async_resolve_entity_id(registry, config[CONF_ENTITY_ID])
if config[CONF_TYPE] in STATE_CONDITION_TYPES:
if config[CONF_TYPE] == "is_open":
state = STATE_OPEN
elif config[CONF_TYPE] == "is_closed":
state = STATE_CLOSED
elif config[CONF_TYPE] == "is_opening":
state = STATE_OPENING
elif config[CONF_TYPE] == "is_closing":
state = STATE_CLOSING
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
return condition.state(hass, entity_id, state)
return test_is_state
if config[CONF_TYPE] == "is_position":
position_attr = "current_position"
if config[CONF_TYPE] == "is_tilt_position":
position_attr = "current_tilt_position"
min_pos = config.get(CONF_ABOVE)
max_pos = config.get(CONF_BELOW)
@callback
def check_numeric_state(
hass: HomeAssistant, variables: TemplateVarsType = None
) -> bool:
"""Return whether the criteria are met."""
return condition.async_numeric_state(
hass, entity_id, max_pos, min_pos, attribute=position_attr
)
return check_numeric_state |
Describe group on off states. | def async_describe_on_off_states(
hass: HomeAssistant, registry: "GroupIntegrationRegistry"
) -> None:
"""Describe group on off states."""
# On means open, Off means closed
registry.on_off_states(DOMAIN, {STATE_OPEN}, STATE_OPEN, STATE_CLOSED) |
Test if state significantly changed. | 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."""
if old_state != new_state:
return True
old_attrs_s = set(
{k: v for k, v in old_attrs.items() if k in SIGNIFICANT_ATTRIBUTES}.items()
)
new_attrs_s = set(
{k: v for k, v in new_attrs.items() if k in SIGNIFICANT_ATTRIBUTES}.items()
)
changed_attrs: set[str] = {item[0] for item in old_attrs_s ^ new_attrs_s}
for attr_name in changed_attrs:
old_attr_value = old_attrs.get(attr_name)
new_attr_value = new_attrs.get(attr_name)
if new_attr_value is None or not check_valid_float(new_attr_value):
# New attribute value is invalid, ignore it
continue
if old_attr_value is None or not check_valid_float(old_attr_value):
# Old attribute value was invalid, we should report again
return True
if check_absolute_change(old_attr_value, new_attr_value, 1.0):
return True
# no significant attribute change detected
return False |
Return if the cover is closed based on the statemachine. | def is_closed(hass: HomeAssistant, entity_id: str) -> bool:
"""Return if the cover is closed based on the statemachine."""
return hass.states.is_state(entity_id, STATE_CLOSED) |
Initialize Scanner. | def get_scanner(hass: HomeAssistant, config: ConfigType) -> CPPMDeviceScanner | None:
"""Initialize Scanner."""
data = {
"server": config[DOMAIN][CONF_HOST],
"grant_type": GRANT_TYPE,
"secret": config[DOMAIN][CONF_API_KEY],
"client": config[DOMAIN][CONF_CLIENT_ID],
}
cppm = ClearPass(data)
if cppm.access_token is None:
return None
_LOGGER.debug("Successfully received Access Token")
return CPPMDeviceScanner(cppm) |
Represent currently available serial ports as string.
Adds option to not use usb on top of the list,
option to use manual path or refresh list at the end. | def list_ports_as_str(
serial_ports: list[ListPortInfo], no_usb_option: bool = True
) -> list[str]:
"""Represent currently available serial ports as string.
Adds option to not use usb on top of the list,
option to use manual path or refresh list at the end.
"""
ports_as_string: list[str] = []
if no_usb_option:
ports_as_string.append(DONT_USE_USB)
ports_as_string.extend(
usb.human_readable_device_name(
port.device,
port.serial_number,
port.manufacturer,
port.description,
f"{hex(port.vid)[2:]:0>4}".upper() if port.vid else None,
f"{hex(port.pid)[2:]:0>4}".upper() if port.pid else None,
)
for port in serial_ports
)
ports_as_string.append(MANUAL_PATH)
ports_as_string.append(REFRESH_LIST)
return ports_as_string |
Get the port that the by-id link points to. | def get_port(dev_path: str) -> str | None:
"""Get the port that the by-id link points to."""
# not a by-id link, but just given path
by_id = "/dev/serial/by-id"
if by_id not in dev_path:
return dev_path
try:
return f"/dev/{os.path.basename(os.readlink(dev_path))}"
except FileNotFoundError:
return None |
Map a value from a range to another. | def map_from_to(val: int, in_min: int, in_max: int, out_min: int, out_max: int) -> int:
"""Map a value from a range to another."""
return int((val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.