response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Ensure exactly 2 of CONF_PERIOD_KEYS are provided. | def exactly_two_period_keys(conf: _T) -> _T:
"""Ensure exactly 2 of CONF_PERIOD_KEYS are provided."""
if sum(param in conf for param in CONF_PERIOD_KEYS) != 2:
raise vol.Invalid(
"You must provide exactly 2 of the following: start, end, duration"
)
return conf |
Validate the configuration and return a Hitron CODA-4582U scanner. | def get_scanner(
_hass: HomeAssistant, config: ConfigType
) -> HitronCODADeviceScanner | None:
"""Validate the configuration and return a Hitron CODA-4582U scanner."""
scanner = HitronCODADeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None |
Force update all entities after state change. | def refresh_system(
func: Callable[Concatenate[_HiveEntityT, _P], Awaitable[Any]],
) -> Callable[Concatenate[_HiveEntityT, _P], Coroutine[Any, Any, None]]:
"""Force update all entities after state change."""
@wraps(func)
async def wrapper(self: _HiveEntityT, *args: _P.args, **kwargs: _P.kwargs) -> None:
await func(self, *args, **kwargs)
async_dispatcher_send(self.hass, DOMAIN)
return wrapper |
Return an array of supported locations. | def get_loc_name(item):
"""Return an array of supported locations."""
return item[KEY_LOCATION] |
Parse configuration and add HLK-SW16 switch devices. | def devices_from_entities(hass, entry):
"""Parse configuration and add HLK-SW16 switch devices."""
device_client = hass.data[DOMAIN][entry.entry_id][DATA_DEVICE_REGISTER]
devices = []
for i in range(16):
device_port = f"{i:01x}"
device = SW16Switch(device_port, entry.entry_id, device_client)
devices.append(device)
return devices |
Expose an entity to an assistant. | def ws_expose_entity(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Expose an entity to an assistant."""
entity_ids: str = msg["entity_ids"]
if blocked := next(
(
entity_id
for entity_id in entity_ids
if entity_id in CLOUD_NEVER_EXPOSED_ENTITIES
),
None,
):
connection.send_error(
msg["id"], websocket_api.const.ERR_NOT_ALLOWED, f"can't expose '{blocked}'"
)
return
for entity_id in entity_ids:
for assistant in msg["assistants"]:
async_expose_entity(hass, assistant, entity_id, msg["should_expose"])
connection.send_result(msg["id"]) |
Expose an entity to an assistant. | def ws_list_exposed_entities(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Expose an entity to an assistant."""
result: dict[str, Any] = {}
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
entity_registry = er.async_get(hass)
for entity_id in chain(exposed_entities.entities, entity_registry.entities):
result[entity_id] = {}
entity_settings = async_get_entity_settings(hass, entity_id)
for assistant, settings in entity_settings.items():
if "should_expose" not in settings:
continue
result[entity_id][assistant] = settings["should_expose"]
connection.send_result(msg["id"], {"exposed_entities": result}) |
Check if new entities are exposed to an assistant. | def ws_expose_new_entities_get(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Check if new entities are exposed to an assistant."""
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
expose_new = exposed_entities.async_get_expose_new_entities(msg["assistant"])
connection.send_result(msg["id"], {"expose_new": expose_new}) |
Expose new entities to an assistant. | def ws_expose_new_entities_set(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Expose new entities to an assistant."""
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
exposed_entities.async_set_expose_new_entities(msg["assistant"], msg["expose_new"])
connection.send_result(msg["id"]) |
Listen for updates to entity expose settings. | def async_listen_entity_updates(
hass: HomeAssistant, assistant: str, listener: Callable[[], None]
) -> CALLBACK_TYPE:
"""Listen for updates to entity expose settings."""
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
return exposed_entities.async_listen_entity_updates(assistant, listener) |
Get all entity expose settings for an assistant. | def async_get_assistant_settings(
hass: HomeAssistant, assistant: str
) -> dict[str, Mapping[str, Any]]:
"""Get all entity expose settings for an assistant."""
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
return exposed_entities.async_get_assistant_settings(assistant) |
Get assistant expose settings for an entity. | def async_get_entity_settings(
hass: HomeAssistant, entity_id: str
) -> dict[str, Mapping[str, Any]]:
"""Get assistant expose settings for an entity."""
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
return exposed_entities.async_get_entity_settings(entity_id) |
Get assistant expose settings for an entity. | def async_expose_entity(
hass: HomeAssistant,
assistant: str,
entity_id: str,
should_expose: bool,
) -> None:
"""Get assistant expose settings for an entity."""
async_set_assistant_option(
hass, assistant, entity_id, "should_expose", should_expose
) |
Return True if an entity should be exposed to an assistant. | def async_should_expose(hass: HomeAssistant, assistant: str, entity_id: str) -> bool:
"""Return True if an entity should be exposed to an assistant."""
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
return exposed_entities.async_should_expose(assistant, entity_id) |
Set an option for an assistant.
Notify listeners if expose flag was changed. | def async_set_assistant_option(
hass: HomeAssistant, assistant: str, entity_id: str, option: str, value: Any
) -> None:
"""Set an option for an assistant.
Notify listeners if expose flag was changed.
"""
exposed_entities: ExposedEntities = hass.data[DATA_EXPOSED_ENTITIES]
exposed_entities.async_set_assistant_option(assistant, entity_id, option, value) |
Describe logbook events. | def async_describe_events(
hass: HomeAssistant,
async_describe_event: Callable[
[str, EventType[NoEventData] | str, Callable[[Event], dict[str, str]]], None
],
) -> None:
"""Describe logbook events."""
@callback
def async_describe_hass_event(event: Event[NoEventData]) -> dict[str, str]:
"""Describe homeassistant logbook event."""
return {
LOGBOOK_ENTRY_NAME: "Home Assistant",
LOGBOOK_ENTRY_MESSAGE: EVENT_TO_NAME[event.event_type],
LOGBOOK_ENTRY_ICON: "mdi:home-assistant",
}
async_describe_event(DOMAIN, EVENT_HOMEASSISTANT_STOP, async_describe_hass_event)
async_describe_event(DOMAIN, EVENT_HOMEASSISTANT_START, async_describe_hass_event) |
Convert state definitions to State objects. | def _convert_states(states: dict[str, Any]) -> dict[str, State]:
"""Convert state definitions to State objects."""
result: dict[str, State] = {}
for entity_id, info in states.items():
entity_id = cv.entity_id(entity_id)
if isinstance(info, dict):
entity_attrs = info.copy()
state = entity_attrs.pop(ATTR_STATE, None)
attributes = entity_attrs
else:
state = info
attributes = {}
# YAML translates 'on' to a boolean
# http://yaml.org/type/bool.html
if isinstance(state, bool):
state = STATE_ON if state else STATE_OFF
elif not isinstance(state, str):
raise vol.Invalid(f"State for {entity_id} should be a string")
result[entity_id] = State(entity_id, state, attributes)
return result |
Validate that entities and snapshot_entities do not overlap. | def _ensure_no_intersection(value: dict[str, Any]) -> dict[str, Any]:
"""Validate that entities and snapshot_entities do not overlap."""
if (
CONF_SNAPSHOT not in value
or CONF_ENTITIES not in value
or all(
entity_id not in value[CONF_SNAPSHOT] for entity_id in value[CONF_ENTITIES]
)
):
return value
raise vol.Invalid("entities and snapshot_entities must not overlap") |
Return all scenes that reference the entity. | def scenes_with_entity(hass: HomeAssistant, entity_id: str) -> list[str]:
"""Return all scenes that reference the entity."""
if DATA_PLATFORM not in hass.data:
return []
platform: EntityPlatform = hass.data[DATA_PLATFORM]
scene_entities = cast(ValuesView[HomeAssistantScene], platform.entities.values())
return [
scene_entity.entity_id
for scene_entity in scene_entities
if entity_id in scene_entity.scene_config.states
] |
Return all entities in a scene. | def entities_in_scene(hass: HomeAssistant, entity_id: str) -> list[str]:
"""Return all entities in a scene."""
if DATA_PLATFORM not in hass.data:
return []
platform: EntityPlatform = hass.data[DATA_PLATFORM]
if (entity := platform.entities.get(entity_id)) is None:
return []
return list(cast(HomeAssistantScene, entity).scene_config.states) |
Process multiple scenes and add them. | def _process_scenes_config(
hass: HomeAssistant, async_add_entities: AddEntitiesCallback, config: dict[str, Any]
) -> None:
"""Process multiple scenes and add them."""
# Check empty list
scene_config: list[dict[str, Any]]
if not (scene_config := config[STATES]):
return
async_add_entities(
HomeAssistantScene(
hass,
SceneConfig(
scene.get(CONF_ID),
scene[CONF_NAME],
scene.get(CONF_ICON),
scene[CONF_ENTITIES],
),
)
for scene in scene_config
) |
Register system health callbacks. | def async_register(
hass: HomeAssistant, register: system_health.SystemHealthRegistration
) -> None:
"""Register system health callbacks."""
register.async_register_info(system_health_info) |
Set function which is called by the stop and restart services. | def async_set_stop_handler(
hass: ha.HomeAssistant,
stop_handler: Callable[[ha.HomeAssistant, bool], Coroutine[Any, Any, None]],
) -> None:
"""Set function which is called by the stop and restart services."""
hass.data[DATA_STOP_HANDLER] = stop_handler |
Validate the event types.
If the event types are templated, we check when attaching the trigger. | def _validate_event_types(value: Any) -> Any:
"""Validate the event types.
If the event types are templated, we check when attaching the trigger.
"""
templates: list[template.Template] = value
if any(tpl.is_static and tpl.template == EVENT_STATE_REPORTED for tpl in templates):
raise vol.Invalid(f"Can't listen to {EVENT_STATE_REPORTED} in event trigger")
return value |
Validate that above and below can co-exist. | def validate_above_below(value: _T) -> _T:
"""Validate that above and below can co-exist."""
above = value.get(CONF_ABOVE)
below = value.get(CONF_BELOW)
if above is None or below is None:
return value
if isinstance(above, str) or isinstance(below, str):
return value
if above > below:
raise vol.Invalid(
(
f"A value can never be above {above} and below {below} at the same"
" time. You probably want two different triggers."
),
)
return value |
Return board info. | def async_info(hass: HomeAssistant) -> list[HardwareInfo]:
"""Return board info."""
if (os_info := get_os_info(hass)) is None:
raise HomeAssistantError
board: str | None
if (board := os_info.get("board")) is None:
raise HomeAssistantError
if not board == "green":
raise HomeAssistantError
config_entries = [
entry.entry_id for entry in hass.config_entries.async_entries(DOMAIN)
]
return [
HardwareInfo(
board=BoardInfo(
hassio_board_id=board,
manufacturer=MANUFACTURER,
model=MODEL,
revision=None,
),
config_entries=config_entries,
dongle=None,
name=BOARD_NAME,
url=DOCUMENTATION_URL,
)
] |
Get the flasher add-on manager. | def get_flasher_addon_manager(hass: HomeAssistant) -> WaitingAddonManager:
"""Get the flasher add-on manager."""
return WaitingAddonManager(
hass,
LOGGER,
"Silicon Labs Flasher",
SILABS_FLASHER_ADDON_SLUG,
) |
Return the zigbee socket.
Raises AddonError on error | def get_zigbee_socket() -> str:
"""Return the zigbee socket.
Raises AddonError on error
"""
hostname = hostname_from_addon_slug(SILABS_MULTIPROTOCOL_ADDON_SLUG)
return f"socket://{hostname}:9999" |
Return if the URL points at the Multiprotocol add-on. | def is_multiprotocol_url(url: str) -> bool:
"""Return if the URL points at the Multiprotocol add-on."""
parsed = yarl.URL(url)
hostname = hostname_from_addon_slug(SILABS_MULTIPROTOCOL_ADDON_SLUG)
return parsed.host == hostname |
Return board info. | def async_info(hass: HomeAssistant) -> list[HardwareInfo]:
"""Return board info."""
entries = hass.config_entries.async_entries(DOMAIN)
return [
HardwareInfo(
board=None,
config_entries=[entry.entry_id],
dongle=USBInfo(
vid=entry.data["vid"],
pid=entry.data["pid"],
serial_number=entry.data["serial_number"],
manufacturer=entry.data["manufacturer"],
description=entry.data["product"],
),
name=get_hardware_variant(entry).full_name,
url=DOCUMENTATION_URL,
)
for entry in entries
] |
Return UsbServiceInfo. | def get_usb_service_info(config_entry: ConfigEntry) -> usb.UsbServiceInfo:
"""Return UsbServiceInfo."""
return usb.UsbServiceInfo(
device=config_entry.data["device"],
vid=config_entry.data["vid"],
pid=config_entry.data["pid"],
serial_number=config_entry.data["serial_number"],
manufacturer=config_entry.data["manufacturer"],
description=config_entry.data["product"],
) |
Get the hardware variant from the config entry. | def get_hardware_variant(config_entry: ConfigEntry) -> HardwareVariant:
"""Get the hardware variant from the config entry."""
return HardwareVariant.from_usb_product_name(config_entry.data["product"]) |
Get the device path from a ZHA config entry. | def get_zha_device_path(config_entry: ConfigEntry) -> str:
"""Get the device path from a ZHA config entry."""
return cast(str, config_entry.data["device"]["path"]) |
Get the OTBR add-on manager. | def get_otbr_addon_manager(hass: HomeAssistant) -> WaitingAddonManager:
"""Get the OTBR add-on manager."""
return WaitingAddonManager(
hass,
_LOGGER,
OTBR_ADDON_NAME,
OTBR_ADDON_SLUG,
) |
Get the flasher add-on manager. | def get_zigbee_flasher_addon_manager(hass: HomeAssistant) -> WaitingAddonManager:
"""Get the flasher add-on manager."""
return WaitingAddonManager(
hass,
_LOGGER,
ZIGBEE_FLASHER_ADDON_NAME,
ZIGBEE_FLASHER_ADDON_SLUG,
) |
Return board info. | def async_info(hass: HomeAssistant) -> list[HardwareInfo]:
"""Return board info."""
if (os_info := get_os_info(hass)) is None:
raise HomeAssistantError
board: str | None
if (board := os_info.get("board")) is None:
raise HomeAssistantError
if not board == "yellow":
raise HomeAssistantError
config_entries = [
entry.entry_id for entry in hass.config_entries.async_entries(DOMAIN)
]
return [
HardwareInfo(
board=BoardInfo(
hassio_board_id=board,
manufacturer=MANUFACTURER,
model=MODEL,
revision=None,
),
config_entries=config_entries,
dongle=None,
name=BOARD_NAME,
url=DOCUMENTATION_URL,
)
] |
Take state and return an accessory object if supported. | def get_accessory( # noqa: C901
hass: HomeAssistant, driver: HomeDriver, state: State, aid: int | None, config: dict
) -> HomeAccessory | None:
"""Take state and return an accessory object if supported."""
if not aid:
_LOGGER.warning(
(
'The entity "%s" is not supported, since it '
"generates an invalid aid, please change it"
),
state.entity_id,
)
return None
a_type = None
name = config.get(CONF_NAME, state.name)
features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if state.domain == "alarm_control_panel":
a_type = "SecuritySystem"
elif state.domain in ("binary_sensor", "device_tracker", "person"):
a_type = "BinarySensor"
elif state.domain == "climate":
a_type = "Thermostat"
elif state.domain == "cover":
device_class = state.attributes.get(ATTR_DEVICE_CLASS)
if device_class in (
CoverDeviceClass.GARAGE,
CoverDeviceClass.GATE,
) and features & (CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE):
a_type = "GarageDoorOpener"
elif (
device_class == CoverDeviceClass.WINDOW
and features & CoverEntityFeature.SET_POSITION
):
a_type = "Window"
elif (
device_class == CoverDeviceClass.DOOR
and features & CoverEntityFeature.SET_POSITION
):
a_type = "Door"
elif features & CoverEntityFeature.SET_POSITION:
a_type = "WindowCovering"
elif features & (CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE):
a_type = "WindowCoveringBasic"
elif features & CoverEntityFeature.SET_TILT_POSITION:
# WindowCovering and WindowCoveringBasic both support tilt
# only WindowCovering can handle the covers that are missing
# CoverEntityFeature.SET_POSITION, CoverEntityFeature.OPEN,
# and CoverEntityFeature.CLOSE
a_type = "WindowCovering"
elif state.domain == "fan":
a_type = "Fan"
elif state.domain == "humidifier":
a_type = "HumidifierDehumidifier"
elif state.domain == "light":
a_type = "Light"
elif state.domain == "lock":
a_type = "Lock"
elif state.domain == "media_player":
device_class = state.attributes.get(ATTR_DEVICE_CLASS)
feature_list = config.get(CONF_FEATURE_LIST, [])
if device_class == MediaPlayerDeviceClass.RECEIVER:
a_type = "ReceiverMediaPlayer"
elif device_class == MediaPlayerDeviceClass.TV:
a_type = "TelevisionMediaPlayer"
elif validate_media_player_features(state, feature_list):
a_type = "MediaPlayer"
elif state.domain == "sensor":
device_class = state.attributes.get(ATTR_DEVICE_CLASS)
unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
if device_class == SensorDeviceClass.TEMPERATURE or unit in (
UnitOfTemperature.CELSIUS,
UnitOfTemperature.FAHRENHEIT,
):
a_type = "TemperatureSensor"
elif device_class == SensorDeviceClass.HUMIDITY and unit == PERCENTAGE:
a_type = "HumiditySensor"
elif (
device_class == SensorDeviceClass.PM10
or SensorDeviceClass.PM10 in state.entity_id
):
a_type = "PM10Sensor"
elif (
device_class == SensorDeviceClass.PM25
or SensorDeviceClass.PM25 in state.entity_id
):
a_type = "PM25Sensor"
elif device_class == SensorDeviceClass.NITROGEN_DIOXIDE:
a_type = "NitrogenDioxideSensor"
elif device_class == SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS:
a_type = "VolatileOrganicCompoundsSensor"
elif (
device_class == SensorDeviceClass.GAS
or SensorDeviceClass.GAS in state.entity_id
):
a_type = "AirQualitySensor"
elif device_class == SensorDeviceClass.CO:
a_type = "CarbonMonoxideSensor"
elif device_class == SensorDeviceClass.CO2 or "co2" in state.entity_id:
a_type = "CarbonDioxideSensor"
elif device_class == SensorDeviceClass.ILLUMINANCE or unit == LIGHT_LUX:
a_type = "LightSensor"
elif state.domain == "switch":
if switch_type := config.get(CONF_TYPE):
a_type = SWITCH_TYPES[switch_type]
elif state.attributes.get(ATTR_DEVICE_CLASS) == SwitchDeviceClass.OUTLET:
a_type = "Outlet"
else:
a_type = "Switch"
elif state.domain == "vacuum":
a_type = "Vacuum"
elif state.domain == "remote" and features & RemoteEntityFeature.ACTIVITY:
a_type = "ActivityRemote"
elif state.domain in (
"automation",
"button",
"input_boolean",
"input_button",
"remote",
"scene",
"script",
):
a_type = "Switch"
elif state.domain in ("input_select", "select"):
a_type = "SelectSwitch"
elif state.domain == "water_heater":
a_type = "WaterHeater"
elif state.domain == "camera":
a_type = "Camera"
if a_type is None:
return None
_LOGGER.debug('Add "%s" as "%s"', state.entity_id, a_type)
return TYPES[a_type](hass, driver, name, state.entity_id, aid, config) |
Determine the system wide unique_id for an entity. | def get_system_unique_id(entity: er.RegistryEntry, entity_unique_id: str) -> str:
"""Determine the system wide unique_id for an entity."""
return f"{entity.platform}.{entity.domain}.{entity_unique_id}" |
Generate accessory aid. | def _generate_aids(unique_id: str | None, entity_id: str) -> Generator[int, None, None]:
"""Generate accessory aid."""
if unique_id:
# Use fnv1a_32 of the unique id as
# fnv1a_32 has less collisions than
# adler32
yield fnv1a_32(unique_id.encode("utf-8"))
# If there is no unique id we use
# fnv1a_32 as it is unlikely to collide
yield fnv1a_32(entity_id.encode("utf-8"))
# If called again resort to random allocations.
# Given the size of the range its unlikely we'll encounter duplicates
# But try a few times regardless
for _ in range(5):
yield random.randrange(AID_MIN, AID_MAX) |
Create a filter dict. | def _make_entity_filter(
include_domains: list[str] | None = None,
include_entities: list[str] | None = None,
exclude_domains: list[str] | None = None,
exclude_entities: list[str] | None = None,
) -> EntityFilterDict:
"""Create a filter dict."""
return EntityFilterDict(
include_domains=include_domains or [],
include_entities=include_entities or [],
exclude_domains=exclude_domains or [],
exclude_entities=exclude_entities or [],
) |
Build an entities filter from domains and entities. | def _async_build_entities_filter(
domains: list[str], entities: list[str]
) -> EntityFilterDict:
"""Build an entities filter from domains and entities."""
# Include all of the domain if there are no entities
# explicitly included as the user selected the domain
return _make_entity_filter(
include_domains=sorted(
set(domains).difference(_domains_set_from_entities(entities))
),
include_entities=entities,
) |
Filter out hidden entities and ones with entity category (unless specified). | def _exclude_by_entity_registry(
ent_reg: er.EntityRegistry,
entity_id: str,
include_entity_category: bool,
include_hidden: bool,
) -> bool:
"""Filter out hidden entities and ones with entity category (unless specified)."""
return bool(
(entry := ent_reg.async_get(entity_id))
and (
(not include_hidden and entry.hidden_by is not None)
or (not include_entity_category and entry.entity_category is not None)
)
) |
Fetch all entities or entities in the given domains. | def _async_get_matching_entities(
hass: HomeAssistant,
domains: list[str] | None = None,
include_entity_category: bool = False,
include_hidden: bool = False,
) -> dict[str, str]:
"""Fetch all entities or entities in the given domains."""
ent_reg = er.async_get(hass)
return {
state.entity_id: (
f"{state.attributes.get(ATTR_FRIENDLY_NAME, state.entity_id)} ({state.entity_id})"
)
for state in sorted(
hass.states.async_all(domains and set(domains)),
key=lambda item: item.entity_id,
)
if not _exclude_by_entity_registry(
ent_reg, state.entity_id, include_entity_category, include_hidden
)
} |
Build a set of domains for the given entity ids. | def _domains_set_from_entities(entity_ids: Iterable[str]) -> set[str]:
"""Build a set of domains for the given entity ids."""
return {split_entity_id(entity_id)[0] for entity_id in entity_ids} |
Build a list of entities that should be paired in accessory mode. | def _async_get_entity_ids_for_accessory_mode(
hass: HomeAssistant, include_domains: Iterable[str]
) -> list[str]:
"""Build a list of entities that should be paired in accessory mode."""
accessory_mode_domains = {
domain for domain in include_domains if domain in DOMAINS_NEED_ACCESSORY_MODE
}
if not accessory_mode_domains:
return []
return [
state.entity_id
for state in hass.states.async_all(accessory_mode_domains)
if state_needs_accessory_mode(state)
] |
Return a set of entity ids that have config entries in accessory mode. | def _async_entity_ids_with_accessory_mode(hass: HomeAssistant) -> set[str]:
"""Return a set of entity ids that have config entries in accessory mode."""
entity_ids: set[str] = set()
current_entries = hass.config_entries.async_entries(DOMAIN)
for entry in current_entries:
# We have to handle the case where the data has not yet
# been migrated to options because the data was just
# imported and the entry was never started
target = entry.options if CONF_HOMEKIT_MODE in entry.options else entry.data
if target.get(CONF_HOMEKIT_MODE) != HOMEKIT_MODE_ACCESSORY:
continue
entity_ids.add(target[CONF_FILTER][CONF_INCLUDE_ENTITIES][0])
return entity_ids |
Return diagnostics for a bridge. | def _get_bridge_diagnostics(hass: HomeAssistant, bridge: HomeBridge) -> dict[int, Any]:
"""Return diagnostics for a bridge."""
return {
aid: _get_accessory_diagnostics(hass, accessory)
for aid, accessory in bridge.accessories.items()
} |
Return diagnostics for an accessory. | def _get_accessory_diagnostics(
hass: HomeAssistant, accessory: HomeAccessory
) -> dict[str, Any]:
"""Return diagnostics for an accessory."""
entity_state = None
if accessory.entity_id:
entity_state = hass.states.get(accessory.entity_id)
data = {
"aid": accessory.aid,
"config": accessory.config,
"category": accessory.category,
"name": accessory.display_name,
"entity_id": accessory.entity_id,
}
if entity_state:
data["entity_state"] = async_redact_data(entity_state, TO_REDACT)
return data |
Describe logbook events. | def async_describe_events(
hass: HomeAssistant,
async_describe_event: Callable[[str, str, Callable[[Event], dict[str, Any]]], None],
) -> None:
"""Describe logbook events."""
@callback
def async_describe_logbook_event(event: Event) -> dict[str, Any]:
"""Describe a logbook event."""
data = event.data
entity_id = data.get(ATTR_ENTITY_ID)
value = data.get(ATTR_VALUE)
value_msg = f" to {value}" if value else ""
message = (
f"send command {data[ATTR_SERVICE]}{value_msg} for"
f" {data[ATTR_DISPLAY_NAME]}"
)
return {
LOGBOOK_ENTRY_NAME: "HomeKit",
LOGBOOK_ENTRY_MESSAGE: message,
LOGBOOK_ENTRY_ENTITY_ID: entity_id,
}
async_describe_event(DOMAIN, EVENT_HOMEKIT_CHANGED, async_describe_logbook_event) |
Convert hass state to homekit position state. | def _hass_state_to_position_start(state: str) -> int:
"""Convert hass state to homekit position state."""
if state == STATE_OPENING:
return HK_POSITION_GOING_TO_MAX
if state == STATE_CLOSING:
return HK_POSITION_GOING_TO_MIN
return HK_POSITION_STOPPED |
Return the equivalent HomeKit HVAC mode for a given state. | def _hk_hvac_mode_from_state(state: State) -> int | None:
"""Return the equivalent HomeKit HVAC mode for a given state."""
if (current_state := state.state) in (STATE_UNKNOWN, STATE_UNAVAILABLE):
return None
if not (hvac_mode := try_parse_enum(HVACMode, current_state)):
_LOGGER.error(
"%s: Received invalid HVAC mode: %s", state.entity_id, state.state
)
return None
return HC_HASS_TO_HOMEKIT.get(hvac_mode) |
Calculate the temperature range from a state. | def _get_temperature_range_from_state(
state: State, unit: str, default_min: float, default_max: float
) -> tuple[float, float]:
"""Calculate the temperature range from a state."""
if min_temp := state.attributes.get(ATTR_MIN_TEMP):
min_temp = round(temperature_to_homekit(min_temp, unit) * 2) / 2
else:
min_temp = default_min
if max_temp := state.attributes.get(ATTR_MAX_TEMP):
max_temp = round(temperature_to_homekit(max_temp, unit) * 2) / 2
else:
max_temp = default_max
# Homekit only supports 10-38, overwriting
# the max to appears to work, but less than 0 causes
# a crash on the home app
min_temp = max(min_temp, 0)
max_temp = max(max_temp, min_temp)
return min_temp, max_temp |
Calculate the target temperature from a state. | def _get_target_temperature(state: State, unit: str) -> float | None:
"""Calculate the target temperature from a state."""
target_temp = state.attributes.get(ATTR_TEMPERATURE)
if isinstance(target_temp, (int, float)):
return temperature_to_homekit(target_temp, unit)
return None |
Calculate the current temperature from a state. | def _get_current_temperature(state: State, unit: str) -> float | None:
"""Calculate the current temperature from a state."""
target_temp = state.attributes.get(ATTR_CURRENT_TEMPERATURE)
if isinstance(target_temp, (int, float)):
return temperature_to_homekit(target_temp, unit)
return None |
Validate config entry for CONF_ENTITY. | def validate_entity_config(values: dict) -> dict[str, dict]:
"""Validate config entry for CONF_ENTITY."""
if not isinstance(values, dict):
raise vol.Invalid("expected a dictionary")
entities = {}
for entity_id, config in values.items():
entity = cv.entity_id(entity_id)
domain, _ = split_entity_id(entity)
if not isinstance(config, dict):
raise vol.Invalid(f"The configuration for {entity} must be a dictionary.")
if domain in ("alarm_control_panel", "lock"):
config = CODE_SCHEMA(config)
elif domain == media_player.const.DOMAIN:
config = FEATURE_SCHEMA(config)
feature_list = {}
for feature in config[CONF_FEATURE_LIST]:
params = MEDIA_PLAYER_SCHEMA(feature)
key = params.pop(CONF_FEATURE)
if key in feature_list:
raise vol.Invalid(f"A feature can be added only once for {entity}")
feature_list[key] = params
config[CONF_FEATURE_LIST] = feature_list
elif domain == "camera":
config = CAMERA_SCHEMA(config)
elif domain == "switch":
config = SWITCH_TYPE_SCHEMA(config)
elif domain == "humidifier":
config = HUMIDIFIER_SCHEMA(config)
elif domain == "cover":
config = COVER_SCHEMA(config)
else:
config = BASIC_INFO_SCHEMA(config)
entities[entity] = config
return entities |
Determine features for media players. | def get_media_player_features(state: State) -> list[str]:
"""Determine features for media players."""
features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
supported_modes = []
if features & (
MediaPlayerEntityFeature.TURN_ON | MediaPlayerEntityFeature.TURN_OFF
):
supported_modes.append(FEATURE_ON_OFF)
if features & (MediaPlayerEntityFeature.PLAY | MediaPlayerEntityFeature.PAUSE):
supported_modes.append(FEATURE_PLAY_PAUSE)
if features & (MediaPlayerEntityFeature.PLAY | MediaPlayerEntityFeature.STOP):
supported_modes.append(FEATURE_PLAY_STOP)
if features & MediaPlayerEntityFeature.VOLUME_MUTE:
supported_modes.append(FEATURE_TOGGLE_MUTE)
return supported_modes |
Validate features for media players. | def validate_media_player_features(state: State, feature_list: str) -> bool:
"""Validate features for media players."""
if not (supported_modes := get_media_player_features(state)):
_LOGGER.error("%s does not support any media_player features", state.entity_id)
return False
if not feature_list:
# Auto detected
return True
error_list = [feature for feature in feature_list if feature not in supported_modes]
if error_list:
_LOGGER.error(
"%s does not support media_player features: %s", state.entity_id, error_list
)
return False
return True |
Display persistent notification with setup information. | def async_show_setup_message(
hass: HomeAssistant, entry_id: str, bridge_name: str, pincode: bytes, uri: str
) -> None:
"""Display persistent notification with setup information."""
pin = pincode.decode()
_LOGGER.info("Pincode: %s", pin)
buffer = io.BytesIO()
url = pyqrcode.create(uri)
url.svg(buffer, scale=5, module_color="#000", background="#FFF")
pairing_secret = secrets.token_hex(32)
entry_data: HomeKitEntryData = hass.data[DOMAIN][entry_id]
entry_data.pairing_qr = buffer.getvalue()
entry_data.pairing_qr_secret = pairing_secret
message = (
f"To set up {bridge_name} in the Home App, "
"scan the QR code or enter the following code:\n"
f"### {pin}\n"
f""
)
persistent_notification.async_create(hass, message, "HomeKit Pairing", entry_id) |
Dismiss persistent notification and remove QR code. | def async_dismiss_setup_message(hass: HomeAssistant, entry_id: str) -> None:
"""Dismiss persistent notification and remove QR code."""
persistent_notification.async_dismiss(hass, entry_id) |
Return float of state, catch errors. | def convert_to_float(state: Any) -> float | None:
"""Return float of state, catch errors."""
try:
return float(state)
except (ValueError, TypeError):
return None |
Return int. | def coerce_int(state: str) -> int:
"""Return int."""
try:
return int(state)
except (ValueError, TypeError):
return 0 |
Ensure the name of the device will not crash homekit. | def cleanup_name_for_homekit(name: str | None) -> str:
"""Ensure the name of the device will not crash homekit."""
#
# This is not a security measure.
#
# UNICODE_EMOJI is also not allowed but that
# likely isn't a problem
if name is None:
return "None" # None crashes apple watches
return name.translate(HOMEKIT_CHAR_TRANSLATIONS)[:MAX_NAME_LENGTH] |
Convert temperature to Celsius for HomeKit. | def temperature_to_homekit(temperature: float, unit: str) -> float:
"""Convert temperature to Celsius for HomeKit."""
return round(
TemperatureConverter.convert(temperature, unit, UnitOfTemperature.CELSIUS), 1
) |
Convert temperature back from Celsius to Home Assistant unit. | def temperature_to_states(temperature: float, unit: str) -> float:
"""Convert temperature back from Celsius to Home Assistant unit."""
return (
round(
TemperatureConverter.convert(temperature, UnitOfTemperature.CELSIUS, unit)
* 2
)
/ 2
) |
Map PM2.5 µg/m3 density to HomeKit AirQuality level. | def density_to_air_quality(density: float) -> int:
"""Map PM2.5 µg/m3 density to HomeKit AirQuality level."""
if density <= 12: # US AQI 0-50 (HomeKit: Excellent)
return 1
if density <= 35.4: # US AQI 51-100 (HomeKit: Good)
return 2
if density <= 55.4: # US AQI 101-150 (HomeKit: Fair)
return 3
if density <= 150.4: # US AQI 151-200 (HomeKit: Inferior)
return 4
return 5 |
Map PM10 µg/m3 density to HomeKit AirQuality level. | def density_to_air_quality_pm10(density: float) -> int:
"""Map PM10 µg/m3 density to HomeKit AirQuality level."""
if density <= 54: # US AQI 0-50 (HomeKit: Excellent)
return 1
if density <= 154: # US AQI 51-100 (HomeKit: Good)
return 2
if density <= 254: # US AQI 101-150 (HomeKit: Fair)
return 3
if density <= 354: # US AQI 151-200 (HomeKit: Inferior)
return 4
return 5 |
Map nitrogen dioxide µg/m3 to HomeKit AirQuality level. | def density_to_air_quality_nitrogen_dioxide(density: float) -> int:
"""Map nitrogen dioxide µg/m3 to HomeKit AirQuality level."""
if density <= 30:
return 1
if density <= 60:
return 2
if density <= 80:
return 3
if density <= 90:
return 4
return 5 |
Map VOCs µg/m3 to HomeKit AirQuality level.
The VOC mappings use the IAQ guidelines for Europe released by the WHO (World Health Organization).
Referenced from Sensirion_Gas_Sensors_SGP3x_TVOC_Concept.pdf
https://github.com/paulvha/svm30/blob/master/extras/Sensirion_Gas_Sensors_SGP3x_TVOC_Concept.pdf | def density_to_air_quality_voc(density: float) -> int:
"""Map VOCs µg/m3 to HomeKit AirQuality level.
The VOC mappings use the IAQ guidelines for Europe released by the WHO (World Health Organization).
Referenced from Sensirion_Gas_Sensors_SGP3x_TVOC_Concept.pdf
https://github.com/paulvha/svm30/blob/master/extras/Sensirion_Gas_Sensors_SGP3x_TVOC_Concept.pdf
"""
if density <= 250: # WHO IAQ 1 (HomeKit: Excellent)
return 1
if density <= 500: # WHO IAQ 2 (HomeKit: Good)
return 2
if density <= 1000: # WHO IAQ 3 (HomeKit: Fair)
return 3
if density <= 3000: # WHO IAQ 4 (HomeKit: Inferior)
return 4
return 5 |
Determine the filename of the homekit state file. | def get_persist_filename_for_entry_id(entry_id: str) -> str:
"""Determine the filename of the homekit state file."""
return f"{DOMAIN}.{entry_id}.state" |
Determine the filename of homekit aid storage file. | def get_aid_storage_filename_for_entry_id(entry_id: str) -> str:
"""Determine the filename of homekit aid storage file."""
return f"{DOMAIN}.{entry_id}.aids" |
Determine the filename of homekit iid storage file. | def get_iid_storage_filename_for_entry_id(entry_id: str) -> str:
"""Determine the filename of homekit iid storage file."""
return f"{DOMAIN}.{entry_id}.iids" |
Determine the path to the homekit state file. | def get_persist_fullpath_for_entry_id(hass: HomeAssistant, entry_id: str) -> str:
"""Determine the path to the homekit state file."""
return hass.config.path(STORAGE_DIR, get_persist_filename_for_entry_id(entry_id)) |
Determine the path to the homekit aid storage file. | def get_aid_storage_fullpath_for_entry_id(hass: HomeAssistant, entry_id: str) -> str:
"""Determine the path to the homekit aid storage file."""
return hass.config.path(
STORAGE_DIR, get_aid_storage_filename_for_entry_id(entry_id)
) |
Determine the path to the homekit iid storage file. | def get_iid_storage_fullpath_for_entry_id(hass: HomeAssistant, entry_id: str) -> str:
"""Determine the path to the homekit iid storage file."""
return hass.config.path(
STORAGE_DIR, get_iid_storage_filename_for_entry_id(entry_id)
) |
Extract the version string in a format homekit can consume. | def format_version(version: str) -> str | None:
"""Extract the version string in a format homekit can consume."""
split_ver = str(version).replace("-", ".").replace(" ", ".")
num_only = NUMBERS_ONLY_RE.sub("", split_ver)
if (match := VERSION_RE.search(num_only)) is None:
return None
value = ".".join(map(_format_version_part, match.group(0).split(".")))
return None if _is_zero_but_true(value) else value |
Zero but true values can crash apple watches. | def _is_zero_but_true(value: Any) -> bool:
"""Zero but true values can crash apple watches."""
return convert_to_float(value) == 0 |
Remove the state files from disk. | def remove_state_files_for_entry_id(hass: HomeAssistant, entry_id: str) -> None:
"""Remove the state files from disk."""
for path in (
get_persist_fullpath_for_entry_id(hass, entry_id),
get_aid_storage_fullpath_for_entry_id(hass, entry_id),
get_iid_storage_fullpath_for_entry_id(hass, entry_id),
):
if os.path.exists(path):
os.unlink(path) |
Create a socket to test binding ports. | def _get_test_socket() -> socket.socket:
"""Create a socket to test binding ports."""
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_socket.setblocking(False)
test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return test_socket |
Check to see if a port is available. | def async_port_is_available(port: int) -> bool:
"""Check to see if a port is available."""
try:
_get_test_socket().bind(("", port))
except OSError:
return False
return True |
Find the next available port not assigned to a config entry. | def async_find_next_available_port(hass: HomeAssistant, start_port: int) -> int:
"""Find the next available port not assigned to a config entry."""
exclude_ports = {
entry.data[CONF_PORT]
for entry in hass.config_entries.async_entries(DOMAIN)
if CONF_PORT in entry.data
}
return _async_find_next_available_port(start_port, exclude_ports) |
Find the next available port starting with the given port. | def _async_find_next_available_port(start_port: int, exclude_ports: set) -> int:
"""Find the next available port starting with the given port."""
test_socket = _get_test_socket()
for port in range(start_port, MAX_PORT + 1):
if port in exclude_ports:
continue
try:
test_socket.bind(("", port))
except OSError:
if port == MAX_PORT:
raise
continue
else:
return port
raise RuntimeError("unreachable") |
Check to see if a process is alive. | def pid_is_alive(pid: int) -> bool:
"""Check to see if a process is alive."""
try:
os.kill(pid, 0)
except OSError:
return False
return True |
Return the combined name for the accessory.
The mDNS name and the Home Assistant config entry
name are usually different which means they need to
see both to identify the accessory. | def accessory_friendly_name(hass_name: str, accessory: Accessory) -> str:
"""Return the combined name for the accessory.
The mDNS name and the Home Assistant config entry
name are usually different which means they need to
see both to identify the accessory.
"""
accessory_mdns_name = cast(str, accessory.display_name)
if hass_name.casefold().startswith(accessory_mdns_name.casefold()):
return hass_name
if accessory_mdns_name.casefold().startswith(hass_name.casefold()):
return accessory_mdns_name
return f"{hass_name} ({accessory_mdns_name})" |
Return if the entity represented by the state must be paired in accessory mode. | def state_needs_accessory_mode(state: State) -> bool:
"""Return if the entity represented by the state must be paired in accessory mode."""
if state.domain in (CAMERA_DOMAIN, LOCK_DOMAIN):
return True
return (
state.domain == MEDIA_PLAYER_DOMAIN
and state.attributes.get(ATTR_DEVICE_CLASS)
in (MediaPlayerDeviceClass.TV, MediaPlayerDeviceClass.RECEIVER)
or state.domain == REMOTE_DOMAIN
and state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
& RemoteEntityFeature.ACTIVITY
) |
Check if a state changed event is the same state. | def state_changed_event_is_same_state(event: Event[EventStateChangedData]) -> bool:
"""Check if a state changed event is the same state."""
event_data = event.data
old_state = event_data["old_state"]
new_state = event_data["new_state"]
return bool(new_state and old_state and new_state.state == old_state.state) |
Validate that each homekit bridge configured has a unique name. | def _has_all_unique_names_and_ports(
bridges: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Validate that each homekit bridge configured has a unique name."""
names = [bridge[CONF_NAME] for bridge in bridges]
ports = [bridge[CONF_PORT] for bridge in bridges]
vol.Schema(vol.Unique())(names)
vol.Schema(vol.Unique())(ports)
return bridges |
All active HomeKit instances. | def _async_all_homekit_instances(hass: HomeAssistant) -> list[HomeKit]:
"""All active HomeKit instances."""
domain_data: dict[str, HomeKitEntryData] = hass.data[DOMAIN]
return [data.homekit for data in domain_data.values()] |
Return a dicts of the entries by name and port. | def _async_get_imported_entries_indices(
current_entries: list[ConfigEntry],
) -> tuple[dict[str, ConfigEntry], dict[int, ConfigEntry]]:
"""Return a dicts of the entries by name and port."""
# For backwards compat, its possible the first bridge is using the default
# name.
entries_by_name: dict[str, ConfigEntry] = {}
entries_by_port: dict[int, ConfigEntry] = {}
for entry in current_entries:
if entry.source != SOURCE_IMPORT:
continue
entries_by_name[entry.data.get(CONF_NAME, BRIDGE_NAME)] = entry
entries_by_port[entry.data.get(CONF_PORT, DEFAULT_PORT)] = entry
return entries_by_name, entries_by_port |
Update a config entry with the latest yaml.
Returns True if a matching config entry was found
Returns False if there is no matching config entry | def _async_update_config_entry_from_yaml(
hass: HomeAssistant,
entries_by_name: dict[str, ConfigEntry],
entries_by_port: dict[int, ConfigEntry],
conf: ConfigType,
) -> bool:
"""Update a config entry with the latest yaml.
Returns True if a matching config entry was found
Returns False if there is no matching config entry
"""
if not (
matching_entry := entries_by_name.get(conf.get(CONF_NAME, BRIDGE_NAME))
or entries_by_port.get(conf.get(CONF_PORT, DEFAULT_PORT))
):
return False
# If they alter the yaml config we import the changes
# since there currently is no practical way to support
# all the options in the UI at this time.
data = conf.copy()
options = {}
for key in CONFIG_OPTIONS:
if key in data:
options[key] = data[key]
del data[key]
hass.config_entries.async_update_entry(matching_entry, data=data, options=options)
return True |
Register events and services for HomeKit. | def _async_register_events_and_services(hass: HomeAssistant) -> None:
"""Register events and services for HomeKit."""
hass.http.register_view(HomeKitPairingQRView)
async def async_handle_homekit_reset_accessory(service: ServiceCall) -> None:
"""Handle reset accessory HomeKit service call."""
for homekit in _async_all_homekit_instances(hass):
if homekit.status != STATUS_RUNNING:
_LOGGER.warning(
"HomeKit is not running. Either it is waiting to be "
"started or has been stopped"
)
continue
entity_ids = cast(list[str], service.data.get("entity_id"))
await homekit.async_reset_accessories(entity_ids)
hass.services.async_register(
DOMAIN,
SERVICE_HOMEKIT_RESET_ACCESSORY,
async_handle_homekit_reset_accessory,
schema=RESET_ACCESSORY_SERVICE_SCHEMA,
)
async def async_handle_homekit_unpair(service: ServiceCall) -> None:
"""Handle unpair HomeKit service call."""
referenced = async_extract_referenced_entity_ids(hass, service)
dev_reg = dr.async_get(hass)
for device_id in referenced.referenced_devices:
if not (dev_reg_ent := dev_reg.async_get(device_id)):
raise HomeAssistantError(f"No device found for device id: {device_id}")
macs = [
cval
for ctype, cval in dev_reg_ent.connections
if ctype == dr.CONNECTION_NETWORK_MAC
]
matching_instances = [
homekit
for homekit in _async_all_homekit_instances(hass)
if homekit.driver and dr.format_mac(homekit.driver.state.mac) in macs
]
if not matching_instances:
raise HomeAssistantError(
f"No homekit accessory found for device id: {device_id}"
)
for homekit in matching_instances:
homekit.async_unpair()
hass.services.async_register(
DOMAIN,
SERVICE_HOMEKIT_UNPAIR,
async_handle_homekit_unpair,
schema=UNPAIR_SERVICE_SCHEMA,
)
async def _handle_homekit_reload(service: ServiceCall) -> None:
"""Handle start HomeKit service call."""
config = await async_integration_yaml_config(hass, DOMAIN)
if not config or DOMAIN not in config:
return
current_entries = hass.config_entries.async_entries(DOMAIN)
entries_by_name, entries_by_port = _async_get_imported_entries_indices(
current_entries
)
for conf in config[DOMAIN]:
_async_update_config_entry_from_yaml(
hass, entries_by_name, entries_by_port, conf
)
reload_tasks = [
hass.config_entries.async_reload(entry.entry_id)
for entry in current_entries
]
await asyncio.gather(*reload_tasks)
async_register_admin_service(
hass,
DOMAIN,
SERVICE_RELOAD,
_handle_homekit_reload,
) |
Normalize a hkid so that it is safe to compare with other normalized hkids. | def normalize_hkid(hkid: str) -> str:
"""Normalize a hkid so that it is safe to compare with other normalized hkids."""
return hkid.lower() |
Return a human readable category name. | def formatted_category(category: Categories) -> str:
"""Return a human readable category name."""
return str(category.name).replace("_", " ").title() |
Ensure a pin code is correctly formatted.
Ensures a pin code is in the format 111-11-111.
Handles codes with and without dashes.
If incorrect code is entered, an exception is raised. | def ensure_pin_format(pin: str, allow_insecure_setup_codes: Any = None) -> str:
"""Ensure a pin code is correctly formatted.
Ensures a pin code is in the format 111-11-111.
Handles codes with and without dashes.
If incorrect code is entered, an exception is raised.
"""
if not (match := PIN_FORMAT.search(pin.strip())):
raise aiohomekit.exceptions.MalformedPinError(f"Invalid PIN code f{pin}")
pin_without_dashes = "".join(match.groups())
if not allow_insecure_setup_codes and pin_without_dashes in INSECURE_CODES:
raise InsecureSetupCode(f"Invalid PIN code f{pin}")
return "-".join(match.groups()) |
Return if the serial number appears to be valid. | def valid_serial_number(serial: str) -> bool:
"""Return if the serial number appears to be valid."""
if not serial:
return False
try:
return float("".join(serial.rsplit(".", 1))) > 1
except ValueError:
return True |
Enumerate a stateless switch, like a single button. | def enumerate_stateless_switch(service: Service) -> list[dict[str, Any]]:
"""Enumerate a stateless switch, like a single button."""
# A stateless switch that has a SERVICE_LABEL_INDEX is part of a group
# And is handled separately
if (
service.has(CharacteristicsTypes.SERVICE_LABEL_INDEX)
and len(service.linked) > 0
):
return []
char = service[CharacteristicsTypes.INPUT_EVENT]
# HomeKit itself supports single, double and long presses. But the
# manufacturer might not - clamp options to what they say.
all_values = clamp_enum_to_char(InputEventValues, char)
return [
{
"characteristic": char.iid,
"value": event_type,
"type": "button1",
"subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type],
}
for event_type in all_values
] |
Enumerate a group of stateless switches, like a remote control. | def enumerate_stateless_switch_group(service: Service) -> list[dict[str, Any]]:
"""Enumerate a group of stateless switches, like a remote control."""
switches = list(
service.accessory.services.filter(
service_type=ServicesTypes.STATELESS_PROGRAMMABLE_SWITCH,
child_service=service,
order_by=[CharacteristicsTypes.SERVICE_LABEL_INDEX],
)
)
results: list[dict[str, Any]] = []
for idx, switch in enumerate(switches):
char = switch[CharacteristicsTypes.INPUT_EVENT]
# HomeKit itself supports single, double and long presses. But the
# manufacturer might not - clamp options to what they say.
all_values = clamp_enum_to_char(InputEventValues, char)
results.extend(
{
"characteristic": char.iid,
"value": event_type,
"type": f"button{idx + 1}",
"subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type],
}
for event_type in all_values
)
return results |
Enumerate doorbell buttons. | def enumerate_doorbell(service: Service) -> list[dict[str, Any]]:
"""Enumerate doorbell buttons."""
input_event = service[CharacteristicsTypes.INPUT_EVENT]
# HomeKit itself supports single, double and long presses. But the
# manufacturer might not - clamp options to what they say.
all_values = clamp_enum_to_char(InputEventValues, input_event)
return [
{
"characteristic": input_event.iid,
"value": event_type,
"type": "doorbell",
"subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type],
}
for event_type in all_values
] |
Get or create a trigger source for a device id. | def async_get_or_create_trigger_source(
hass: HomeAssistant, device_id: str
) -> TriggerSource:
"""Get or create a trigger source for a device id."""
trigger_sources: dict[str, TriggerSource] = hass.data.setdefault(TRIGGERS, {})
if not (source := trigger_sources.get(device_id)):
source = TriggerSource(hass)
trigger_sources[device_id] = source
return source |
Process events generated by a HomeKit accessory into automation triggers. | def async_fire_triggers(
conn: HKDevice, events: dict[tuple[int, int], dict[str, Any]]
) -> None:
"""Process events generated by a HomeKit accessory into automation triggers."""
trigger_sources: dict[str, TriggerSource] = conn.hass.data.get(TRIGGERS, {})
if not trigger_sources:
return
for (aid, iid), ev in events.items():
if aid in conn.devices:
device_id = conn.devices[aid]
if source := trigger_sources.get(device_id):
# If the value is None, we received the event via polling
# and we don't want to trigger on that
if ev.get("value") is not None:
source.fire(iid, ev) |
Return diagnostics for a config entry. | def _async_get_diagnostics(
hass: HomeAssistant, entry: ConfigEntry, device: DeviceEntry | None = None
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
hkid = entry.data["AccessoryPairingID"]
connection: HKDevice = hass.data[KNOWN_DEVICES][hkid]
data: dict[str, Any] = {
"config-entry": {
"title": entry.title,
"version": entry.version,
"data": async_redact_data(entry.data, REDACTED_CONFIG_ENTRY_KEYS),
}
}
# This is the raw data as returned by homekit
# It is roughly equivalent to what is in .storage/homekit_controller-entity-map
# But it also has the latest values seen by the polling or events
data["entity-map"] = accessories = connection.entity_map.serialize()
data["config-num"] = connection.config_num
# It contains serial numbers, which we should strip out
for accessory in accessories:
for service in accessory.get("services", []):
for char in service.get("characteristics", []):
if char["type"] in REDACTED_CHARACTERISTICS:
char["value"] = REDACTED
if device:
data["device"] = _async_get_diagnostics_for_device(hass, device)
else:
device_registry = dr.async_get(hass)
devices = data["devices"] = []
for device_id in connection.devices.values():
if not (device := device_registry.async_get(device_id)):
continue
devices.append(_async_get_diagnostics_for_device(hass, device))
return data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.