response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Suppress any properties that will cause zeroconf to fail to startup.
def _suppress_invalid_properties(properties: dict) -> None: """Suppress any properties that will cause zeroconf to fail to startup.""" for prop, prop_value in properties.items(): if not isinstance(prop_value, str): continue if len(prop_value.encode("utf-8")) > MAX_PROPERTY_VALUE_LEN: _LOGGER.error( ( "The property '%s' was suppressed because it is longer than the" " maximum length of %d bytes: %s" ), prop, MAX_PROPERTY_VALUE_LEN, prop_value, ) properties[prop] = ""
Truncate or return the location name usable for zeroconf.
def _truncate_location_name_to_valid(location_name: str) -> str: """Truncate or return the location name usable for zeroconf.""" if len(location_name.encode("utf-8")) < MAX_NAME_LEN: return location_name _LOGGER.warning( ( "The location name was truncated because it is longer than the maximum" " length of %d bytes: %s" ), MAX_NAME_LEN, location_name, ) return location_name.encode("utf-8")[:MAX_NAME_LEN].decode("utf-8", "ignore")
Compile a fnmatch pattern.
def _compile_fnmatch(pattern: str) -> re.Pattern: """Compile a fnmatch pattern.""" return re.compile(translate(pattern))
Memorized version of fnmatch that has a larger lru_cache. The default version of fnmatch only has a lru_cache of 256 entries. With many devices we quickly reach that limit and end up compiling the same pattern over and over again. Zeroconf has its own memorized fnmatch with its own lru_cache since the data is going to be relatively the same since the devices will not change frequently
def _memorized_fnmatch(name: str, pattern: str) -> bool: """Memorized version of fnmatch that has a larger lru_cache. The default version of fnmatch only has a lru_cache of 256 entries. With many devices we quickly reach that limit and end up compiling the same pattern over and over again. Zeroconf has its own memorized fnmatch with its own lru_cache since the data is going to be relatively the same since the devices will not change frequently """ return bool(_compile_fnmatch(pattern).match(name))
Set up the Zestimate sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Zestimate sensor.""" name = config.get(CONF_NAME) properties = config[CONF_ZPID] sensors = [] for zpid in properties: params = {"zws-id": config[CONF_API_KEY]} params["zpid"] = zpid sensors.append(ZestimateDataSensor(name, params)) add_entities(sensors, True)
Find the singleton ZHA config entry, if one exists.
def _get_config_entry(hass: HomeAssistant) -> ConfigEntry: """Find the singleton ZHA config entry, if one exists.""" # If ZHA is already running, use its config entry try: zha_gateway = get_zha_gateway(hass) except ValueError: pass else: return zha_gateway.config_entry # Otherwise, find one entries = hass.config_entries.async_entries(DOMAIN) if len(entries) != 1: raise ValueError(f"Invalid number of ZHA config entries: {entries!r}") return entries[0]
Get the network settings for the currently active ZHA network.
def async_get_active_network_settings(hass: HomeAssistant) -> NetworkBackup: """Get the network settings for the currently active ZHA network.""" app = get_zha_gateway(hass).application_controller return NetworkBackup( node_info=app.state.node_info, network_info=app.state.network_info, )
Get ZHA radio type.
def async_get_radio_type( hass: HomeAssistant, config_entry: ConfigEntry | None = None ) -> RadioType: """Get ZHA radio type.""" if config_entry is None: config_entry = _get_config_entry(hass) return RadioType[config_entry.data[CONF_RADIO_TYPE]]
Get ZHA radio path.
def async_get_radio_path( hass: HomeAssistant, config_entry: ConfigEntry | None = None ) -> str: """Get ZHA radio path.""" if config_entry is None: config_entry = _get_config_entry(hass) return config_entry.data[CONF_DEVICE][CONF_DEVICE_PATH]
Format network backup info into a short piece of text.
def _format_backup_choice( backup: zigpy.backups.NetworkBackup, *, pan_ids: bool = True ) -> str: """Format network backup info into a short piece of text.""" if not pan_ids: return dt_util.as_local(backup.backup_time).strftime("%c") identifier = ( # PAN ID f"{str(backup.network_info.pan_id)[2:]}" # EPID f":{str(backup.network_info.extended_pan_id).replace(':', '')}" ).lower() return f"{dt_util.as_local(backup.backup_time).strftime('%c')} ({identifier})"
Get device trigger data for a device, falling back to the cache if possible.
def _get_device_trigger_data(hass: HomeAssistant, device_id: str) -> tuple[str, dict]: """Get device trigger data for a device, falling back to the cache if possible.""" # First, try checking to see if the device itself is accessible try: zha_device = async_get_zha_device(hass, device_id) except ValueError: pass else: return str(zha_device.ieee), zha_device.device_automation_triggers # If not, check the trigger cache but allow any `KeyError`s to propagate return get_zha_data(hass).device_trigger_cache[device_id]
Return a shallow copy of a dataclass as a dict.
def shallow_asdict(obj: Any) -> dict: """Return a shallow copy of a dataclass as a dict.""" if hasattr(obj, "__dataclass_fields__"): result = {} for field in dataclasses.fields(obj): result[field.name] = shallow_asdict(getattr(obj, field.name)) return result if hasattr(obj, "as_dict"): return obj.as_dict() return obj
Return endpoint cluster attribute data.
def get_endpoint_cluster_attr_data(zha_device: ZHADevice) -> dict: """Return endpoint cluster attribute data.""" cluster_details = {} for ep_id, endpoint in zha_device.device.endpoints.items(): if ep_id == 0: continue endpoint_key = ( f"{PROFILES.get(endpoint.profile_id).DeviceType(endpoint.device_type).name}" if PROFILES.get(endpoint.profile_id) is not None and endpoint.device_type is not None else UNKNOWN ) cluster_details[ep_id] = { ATTR_DEVICE_TYPE: { CONF_NAME: endpoint_key, CONF_ID: endpoint.device_type, }, ATTR_PROFILE_ID: endpoint.profile_id, ATTR_IN_CLUSTERS: { f"0x{cluster_id:04x}": { "endpoint_attribute": cluster.ep_attribute, **get_cluster_attr_data(cluster), } for cluster_id, cluster in endpoint.in_clusters.items() }, ATTR_OUT_CLUSTERS: { f"0x{cluster_id:04x}": { "endpoint_attribute": cluster.ep_attribute, **get_cluster_attr_data(cluster), } for cluster_id, cluster in endpoint.out_clusters.items() }, } return cluster_details
Return cluster attribute data.
def get_cluster_attr_data(cluster: Cluster) -> dict: """Return cluster attribute data.""" unsupported_attributes = {} for u_attr in cluster.unsupported_attributes: try: u_attr_def = cluster.find_attribute(u_attr) unsupported_attributes[f"0x{u_attr_def.id:04x}"] = { ATTR_ATTRIBUTE_NAME: u_attr_def.name } except KeyError: if isinstance(u_attr, int): unsupported_attributes[f"0x{u_attr:04x}"] = {} else: unsupported_attributes[u_attr] = {} return { ATTRIBUTES: { f"0x{attr_id:04x}": { ATTR_ATTRIBUTE_NAME: attr_def.name, ATTR_VALUE: attr_value, } for attr_id, attr_def in cluster.attributes.items() if (attr_value := cluster.get(attr_def.name)) is not None }, UNSUPPORTED_ATTRIBUTES: unsupported_attributes, }
Describe logbook events.
def async_describe_events( hass: HomeAssistant, async_describe_event: Callable[[str, str, Callable[[Event], dict[str, str]]], None], ) -> None: """Describe logbook events.""" device_registry = dr.async_get(hass) @callback def async_describe_zha_event(event: Event) -> dict[str, str]: """Describe ZHA logbook event.""" device: dr.DeviceEntry | None = None device_name: str = "Unknown device" zha_device: ZHADevice | None = None event_data = event.data event_type: str | None = None event_subtype: str | None = None try: device = device_registry.devices[event.data[ATTR_DEVICE_ID]] if device: device_name = device.name_by_user or device.name or "Unknown device" zha_device = async_get_zha_device(hass, event.data[ATTR_DEVICE_ID]) except (KeyError, AttributeError): pass if ( zha_device and (command := event_data.get(ATTR_COMMAND)) and (command_to_etype_subtype := zha_device.device_automation_commands) and (etype_subtypes := command_to_etype_subtype.get(command)) ): all_triggers = zha_device.device_automation_triggers for etype_subtype in etype_subtypes: trigger = all_triggers[etype_subtype] if not all( event_data.get(key) == value for key, value in trigger.items() ): continue event_type, event_subtype = etype_subtype break if event_type is None: event_type = event_data.get(ATTR_COMMAND, ZHA_EVENT) if event_subtype is not None and event_subtype != event_type: event_type = f"{event_type} - {event_subtype}" if event_type is not None: event_type = event_type.replace("_", " ").title() if "event" in event_type.lower(): message = f"{event_type} was fired" else: message = f"{event_type} event was fired" if params := event_data.get("params"): message = f"{message} with parameters: {params}" return { LOGBOOK_ENTRY_NAME: device_name, LOGBOOK_ENTRY_MESSAGE: message, } async_describe_event(ZHA_DOMAIN, ZHA_EVENT, async_describe_zha_event)
Return a new backup with the flag to allow overwriting the EZSP EUI64.
def _allow_overwrite_ezsp_ieee( backup: zigpy.backups.NetworkBackup, ) -> zigpy.backups.NetworkBackup: """Return a new backup with the flag to allow overwriting the EZSP EUI64.""" new_stack_specific = copy.deepcopy(backup.network_info.stack_specific) new_stack_specific.setdefault("ezsp", {})[EZSP_OVERWRITE_EUI64] = True return backup.replace( network_info=backup.network_info.replace(stack_specific=new_stack_specific) )
Return a new backup without the flag to allow overwriting the EZSP EUI64.
def _prevent_overwrite_ezsp_ieee( backup: zigpy.backups.NetworkBackup, ) -> zigpy.backups.NetworkBackup: """Return a new backup without the flag to allow overwriting the EZSP EUI64.""" if "ezsp" not in backup.network_info.stack_specific: return backup new_stack_specific = copy.deepcopy(backup.network_info.stack_specific) new_stack_specific.setdefault("ezsp", {}).pop(EZSP_OVERWRITE_EUI64, None) return backup.replace( network_info=backup.network_info.replace(stack_specific=new_stack_specific) )
Return the ZHA radio path, or None if there's no ZHA config entry.
def _get_zha_url(hass: HomeAssistant) -> str | None: """Return the ZHA radio path, or None if there's no ZHA config entry.""" with contextlib.suppress(ValueError): return api.async_get_radio_path(hass) return None
Wrap value in list if it is provided and not one.
def _ensure_list_if_present(value: _T | None) -> list[_T] | list[Any] | None: """Wrap value in list if it is provided and not one.""" if value is None: return None return cast("list[_T]", value) if isinstance(value, list) else [value]
Transform a group member.
def _cv_group_member(value: dict[str, Any]) -> GroupMember: """Transform a group member.""" return GroupMember( ieee=value[ATTR_IEEE], endpoint_id=value[ATTR_ENDPOINT_ID], )
Transform a cluster binding.
def _cv_cluster_binding(value: dict[str, Any]) -> ClusterBinding: """Transform a cluster binding.""" return ClusterBinding( name=value[ATTR_NAME], type=value[ATTR_TYPE], id=value[ATTR_ID], endpoint_id=value[ATTR_ENDPOINT_ID], )
Transform a zigpy network backup.
def _cv_zigpy_network_backup(value: dict[str, Any]) -> zigpy.backups.NetworkBackup: """Transform a zigpy network backup.""" try: return zigpy.backups.NetworkBackup.from_dict(value) except ValueError as err: raise vol.Invalid(str(err)) from err
Set up the web socket API.
def async_load_api(hass: HomeAssistant) -> None: """Set up the web socket API.""" zha_gateway = get_zha_gateway(hass) application_controller = zha_gateway.application_controller async def permit(service: ServiceCall) -> None: """Allow devices to join this network.""" duration: int = service.data[ATTR_DURATION] ieee: EUI64 | None = service.data.get(ATTR_IEEE) src_ieee: EUI64 link_key: KeyData if ATTR_SOURCE_IEEE in service.data: src_ieee = service.data[ATTR_SOURCE_IEEE] link_key = service.data[ATTR_INSTALL_CODE] _LOGGER.info("Allowing join for %s device with link key", src_ieee) await application_controller.permit_with_link_key( time_s=duration, node=src_ieee, link_key=link_key ) return if ATTR_QR_CODE in service.data: src_ieee, link_key = service.data[ATTR_QR_CODE] _LOGGER.info("Allowing join for %s device with link key", src_ieee) await application_controller.permit_with_link_key( time_s=duration, node=src_ieee, link_key=link_key ) return if ieee: _LOGGER.info("Permitting joins for %ss on %s device", duration, ieee) else: _LOGGER.info("Permitting joins for %ss", duration) await application_controller.permit(time_s=duration, node=ieee) async_register_admin_service( hass, DOMAIN, SERVICE_PERMIT, permit, schema=SERVICE_SCHEMAS[SERVICE_PERMIT] ) async def remove(service: ServiceCall) -> None: """Remove a node from the network.""" zha_gateway = get_zha_gateway(hass) ieee: EUI64 = service.data[ATTR_IEEE] zha_device: ZHADevice | None = zha_gateway.get_device(ieee) if zha_device is not None and zha_device.is_active_coordinator: _LOGGER.info("Removing the coordinator (%s) is not allowed", ieee) return _LOGGER.info("Removing node %s", ieee) await application_controller.remove(ieee) async_register_admin_service( hass, DOMAIN, SERVICE_REMOVE, remove, schema=SERVICE_SCHEMAS[IEEE_SERVICE] ) async def set_zigbee_cluster_attributes(service: ServiceCall) -> None: """Set zigbee attribute for cluster on zha entity.""" ieee: EUI64 = service.data[ATTR_IEEE] endpoint_id: int = service.data[ATTR_ENDPOINT_ID] cluster_id: int = service.data[ATTR_CLUSTER_ID] cluster_type: str = service.data[ATTR_CLUSTER_TYPE] attribute: int | str = service.data[ATTR_ATTRIBUTE] value: int | bool | str = service.data[ATTR_VALUE] manufacturer: int | None = service.data.get(ATTR_MANUFACTURER) zha_device = zha_gateway.get_device(ieee) response = None if zha_device is not None: response = await zha_device.write_zigbee_attribute( endpoint_id, cluster_id, attribute, value, cluster_type=cluster_type, manufacturer=manufacturer, ) else: raise ValueError(f"Device with IEEE {str(ieee)} not found") _LOGGER.debug( ( "Set attribute for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s:" " [%s] %s: [%s]" ), ATTR_CLUSTER_ID, cluster_id, ATTR_CLUSTER_TYPE, cluster_type, ATTR_ENDPOINT_ID, endpoint_id, ATTR_ATTRIBUTE, attribute, ATTR_VALUE, value, ATTR_MANUFACTURER, manufacturer, RESPONSE, response, ) async_register_admin_service( hass, DOMAIN, SERVICE_SET_ZIGBEE_CLUSTER_ATTRIBUTE, set_zigbee_cluster_attributes, schema=SERVICE_SCHEMAS[SERVICE_SET_ZIGBEE_CLUSTER_ATTRIBUTE], ) async def issue_zigbee_cluster_command(service: ServiceCall) -> None: """Issue command on zigbee cluster on ZHA entity.""" ieee: EUI64 = service.data[ATTR_IEEE] endpoint_id: int = service.data[ATTR_ENDPOINT_ID] cluster_id: int = service.data[ATTR_CLUSTER_ID] cluster_type: str = service.data[ATTR_CLUSTER_TYPE] command: int = service.data[ATTR_COMMAND] command_type: str = service.data[ATTR_COMMAND_TYPE] args: list | None = service.data.get(ATTR_ARGS) params: dict | None = service.data.get(ATTR_PARAMS) manufacturer: int | None = service.data.get(ATTR_MANUFACTURER) zha_device = zha_gateway.get_device(ieee) if zha_device is not None: if cluster_id >= MFG_CLUSTER_ID_START and manufacturer is None: manufacturer = zha_device.manufacturer_code await zha_device.issue_cluster_command( endpoint_id, cluster_id, command, command_type, args, params, cluster_type=cluster_type, manufacturer=manufacturer, ) _LOGGER.debug( ( "Issued command for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s]" " %s: [%s] %s: [%s] %s: [%s]" ), ATTR_CLUSTER_ID, cluster_id, ATTR_CLUSTER_TYPE, cluster_type, ATTR_ENDPOINT_ID, endpoint_id, ATTR_COMMAND, command, ATTR_COMMAND_TYPE, command_type, ATTR_ARGS, args, ATTR_PARAMS, params, ATTR_MANUFACTURER, manufacturer, ) else: raise ValueError(f"Device with IEEE {str(ieee)} not found") async_register_admin_service( hass, DOMAIN, SERVICE_ISSUE_ZIGBEE_CLUSTER_COMMAND, issue_zigbee_cluster_command, schema=SERVICE_SCHEMAS[SERVICE_ISSUE_ZIGBEE_CLUSTER_COMMAND], ) async def issue_zigbee_group_command(service: ServiceCall) -> None: """Issue command on zigbee cluster on a zigbee group.""" group_id: int = service.data[ATTR_GROUP] cluster_id: int = service.data[ATTR_CLUSTER_ID] command: int = service.data[ATTR_COMMAND] args: list = service.data[ATTR_ARGS] manufacturer: int | None = service.data.get(ATTR_MANUFACTURER) group = zha_gateway.get_group(group_id) if cluster_id >= MFG_CLUSTER_ID_START and manufacturer is None: _LOGGER.error("Missing manufacturer attribute for cluster: %d", cluster_id) response = None if group is not None: cluster = group.endpoint[cluster_id] response = await cluster.command( command, *args, manufacturer=manufacturer, expect_reply=True ) _LOGGER.debug( "Issued group command for: %s: [%s] %s: [%s] %s: %s %s: [%s] %s: %s", ATTR_CLUSTER_ID, cluster_id, ATTR_COMMAND, command, ATTR_ARGS, args, ATTR_MANUFACTURER, manufacturer, RESPONSE, response, ) async_register_admin_service( hass, DOMAIN, SERVICE_ISSUE_ZIGBEE_GROUP_COMMAND, issue_zigbee_group_command, schema=SERVICE_SCHEMAS[SERVICE_ISSUE_ZIGBEE_GROUP_COMMAND], ) def _get_ias_wd_cluster_handler(zha_device): """Get the IASWD cluster handler for a device.""" cluster_handlers = { ch.name: ch for endpoint in zha_device.endpoints.values() for ch in endpoint.claimed_cluster_handlers.values() } return cluster_handlers.get(CLUSTER_HANDLER_IAS_WD) async def warning_device_squawk(service: ServiceCall) -> None: """Issue the squawk command for an IAS warning device.""" ieee: EUI64 = service.data[ATTR_IEEE] mode: int = service.data[ATTR_WARNING_DEVICE_MODE] strobe: int = service.data[ATTR_WARNING_DEVICE_STROBE] level: int = service.data[ATTR_LEVEL] if (zha_device := zha_gateway.get_device(ieee)) is not None: if cluster_handler := _get_ias_wd_cluster_handler(zha_device): await cluster_handler.issue_squawk(mode, strobe, level) else: _LOGGER.error( "Squawking IASWD: %s: [%s] is missing the required IASWD cluster handler!", ATTR_IEEE, str(ieee), ) else: _LOGGER.error( "Squawking IASWD: %s: [%s] could not be found!", ATTR_IEEE, str(ieee) ) _LOGGER.debug( "Squawking IASWD: %s: [%s] %s: [%s] %s: [%s] %s: [%s]", ATTR_IEEE, str(ieee), ATTR_WARNING_DEVICE_MODE, mode, ATTR_WARNING_DEVICE_STROBE, strobe, ATTR_LEVEL, level, ) async_register_admin_service( hass, DOMAIN, SERVICE_WARNING_DEVICE_SQUAWK, warning_device_squawk, schema=SERVICE_SCHEMAS[SERVICE_WARNING_DEVICE_SQUAWK], ) async def warning_device_warn(service: ServiceCall) -> None: """Issue the warning command for an IAS warning device.""" ieee: EUI64 = service.data[ATTR_IEEE] mode: int = service.data[ATTR_WARNING_DEVICE_MODE] strobe: int = service.data[ATTR_WARNING_DEVICE_STROBE] level: int = service.data[ATTR_LEVEL] duration: int = service.data[ATTR_WARNING_DEVICE_DURATION] duty_mode: int = service.data[ATTR_WARNING_DEVICE_STROBE_DUTY_CYCLE] intensity: int = service.data[ATTR_WARNING_DEVICE_STROBE_INTENSITY] if (zha_device := zha_gateway.get_device(ieee)) is not None: if cluster_handler := _get_ias_wd_cluster_handler(zha_device): await cluster_handler.issue_start_warning( mode, strobe, level, duration, duty_mode, intensity ) else: _LOGGER.error( "Warning IASWD: %s: [%s] is missing the required IASWD cluster handler!", ATTR_IEEE, str(ieee), ) else: _LOGGER.error( "Warning IASWD: %s: [%s] could not be found!", ATTR_IEEE, str(ieee) ) _LOGGER.debug( "Warning IASWD: %s: [%s] %s: [%s] %s: [%s] %s: [%s]", ATTR_IEEE, str(ieee), ATTR_WARNING_DEVICE_MODE, mode, ATTR_WARNING_DEVICE_STROBE, strobe, ATTR_LEVEL, level, ) async_register_admin_service( hass, DOMAIN, SERVICE_WARNING_DEVICE_WARN, warning_device_warn, schema=SERVICE_SCHEMAS[SERVICE_WARNING_DEVICE_WARN], ) websocket_api.async_register_command(hass, websocket_permit_devices) websocket_api.async_register_command(hass, websocket_get_devices) websocket_api.async_register_command(hass, websocket_get_groupable_devices) websocket_api.async_register_command(hass, websocket_get_groups) websocket_api.async_register_command(hass, websocket_get_device) websocket_api.async_register_command(hass, websocket_get_group) websocket_api.async_register_command(hass, websocket_add_group) websocket_api.async_register_command(hass, websocket_remove_groups) websocket_api.async_register_command(hass, websocket_add_group_members) websocket_api.async_register_command(hass, websocket_remove_group_members) websocket_api.async_register_command(hass, websocket_bind_group) websocket_api.async_register_command(hass, websocket_unbind_group) websocket_api.async_register_command(hass, websocket_reconfigure_node) websocket_api.async_register_command(hass, websocket_device_clusters) websocket_api.async_register_command(hass, websocket_device_cluster_attributes) websocket_api.async_register_command(hass, websocket_device_cluster_commands) websocket_api.async_register_command(hass, websocket_read_zigbee_cluster_attributes) websocket_api.async_register_command(hass, websocket_get_bindable_devices) websocket_api.async_register_command(hass, websocket_bind_devices) websocket_api.async_register_command(hass, websocket_unbind_devices) websocket_api.async_register_command(hass, websocket_update_topology) websocket_api.async_register_command(hass, websocket_get_configuration) websocket_api.async_register_command(hass, websocket_update_zha_configuration) websocket_api.async_register_command(hass, websocket_get_network_settings) websocket_api.async_register_command(hass, websocket_list_network_backups) websocket_api.async_register_command(hass, websocket_create_network_backup) websocket_api.async_register_command(hass, websocket_restore_network_backup) websocket_api.async_register_command(hass, websocket_change_channel)
Unload the ZHA API.
def async_unload_api(hass: HomeAssistant) -> None: """Unload the ZHA API.""" hass.services.async_remove(DOMAIN, SERVICE_PERMIT) hass.services.async_remove(DOMAIN, SERVICE_REMOVE) hass.services.async_remove(DOMAIN, SERVICE_SET_ZIGBEE_CLUSTER_ATTRIBUTE) hass.services.async_remove(DOMAIN, SERVICE_ISSUE_ZIGBEE_CLUSTER_COMMAND) hass.services.async_remove(DOMAIN, SERVICE_ISSUE_ZIGBEE_GROUP_COMMAND) hass.services.async_remove(DOMAIN, SERVICE_WARNING_DEVICE_SQUAWK) hass.services.async_remove(DOMAIN, SERVICE_WARNING_DEVICE_WARN)
Clean the serial port path, applying corrections where necessary.
def _clean_serial_port_path(path: str) -> str: """Clean the serial port path, applying corrections where necessary.""" if path.startswith("socket://"): path = path.strip() # Removes extraneous brackets from IP addresses (they don't parse in CPython 3.11.4) if re.match(r"^socket://\[\d+\.\d+\.\d+\.\d+\]:\d+$", path): path = path.replace("[", "").replace("]", "") return path
Get the supported device automation triggers for a zigpy device.
def get_device_automation_triggers( device: zigpy.device.Device, ) -> dict[tuple[str, str], dict[str, str]]: """Get the supported device automation triggers for a zigpy device.""" return { ("device_offline", "device_offline"): {"device_event_type": "device_offline"}, **getattr(device, "device_automation_triggers", {}), }
Capture current logger levels for ZHA.
def async_capture_log_levels() -> dict[str, int]: """Capture current logger levels for ZHA.""" return { DEBUG_COMP_BELLOWS: logging.getLogger(DEBUG_COMP_BELLOWS).getEffectiveLevel(), DEBUG_COMP_ZHA: logging.getLogger(DEBUG_COMP_ZHA).getEffectiveLevel(), DEBUG_COMP_ZIGPY: logging.getLogger(DEBUG_COMP_ZIGPY).getEffectiveLevel(), DEBUG_COMP_ZIGPY_ZNP: logging.getLogger( DEBUG_COMP_ZIGPY_ZNP ).getEffectiveLevel(), DEBUG_COMP_ZIGPY_DECONZ: logging.getLogger( DEBUG_COMP_ZIGPY_DECONZ ).getEffectiveLevel(), DEBUG_COMP_ZIGPY_XBEE: logging.getLogger( DEBUG_COMP_ZIGPY_XBEE ).getEffectiveLevel(), DEBUG_COMP_ZIGPY_ZIGATE: logging.getLogger( DEBUG_COMP_ZIGPY_ZIGATE ).getEffectiveLevel(), }
Set logger levels for ZHA.
def async_set_logger_levels(levels: dict[str, int]) -> None: """Set logger levels for ZHA.""" logging.getLogger(DEBUG_COMP_BELLOWS).setLevel(levels[DEBUG_COMP_BELLOWS]) logging.getLogger(DEBUG_COMP_ZHA).setLevel(levels[DEBUG_COMP_ZHA]) logging.getLogger(DEBUG_COMP_ZIGPY).setLevel(levels[DEBUG_COMP_ZIGPY]) logging.getLogger(DEBUG_COMP_ZIGPY_ZNP).setLevel(levels[DEBUG_COMP_ZIGPY_ZNP]) logging.getLogger(DEBUG_COMP_ZIGPY_DECONZ).setLevel(levels[DEBUG_COMP_ZIGPY_DECONZ]) logging.getLogger(DEBUG_COMP_ZIGPY_XBEE).setLevel(levels[DEBUG_COMP_ZIGPY_XBEE]) logging.getLogger(DEBUG_COMP_ZIGPY_ZIGATE).setLevel(levels[DEBUG_COMP_ZIGPY_ZIGATE])
Convert a cluster command schema to a voluptuous schema.
def cluster_command_schema_to_vol_schema(schema: CommandSchema) -> vol.Schema: """Convert a cluster command schema to a voluptuous schema.""" return vol.Schema( { vol.Optional(field.name) if field.optional else vol.Required(field.name): schema_type_to_vol(field.type) for field in schema.fields } )
Convert a schema type to a voluptuous type.
def schema_type_to_vol(field_type: Any) -> Any: """Convert a schema type to a voluptuous type.""" if issubclass(field_type, enum.Flag) and field_type.__members__: return cv.multi_select( [key.replace("_", " ") for key in field_type.__members__] ) if issubclass(field_type, enum.Enum) and field_type.__members__: return vol.In([key.replace("_", " ") for key in field_type.__members__]) if ( issubclass(field_type, zigpy.types.FixedIntType) or issubclass(field_type, enum.Flag) or issubclass(field_type, enum.Enum) ): return vol.All( vol.Coerce(int), vol.Range(field_type.min_value, field_type.max_value) ) return str
Convert user input to ZCL values.
def convert_to_zcl_values( fields: dict[str, Any], schema: CommandSchema ) -> dict[str, Any]: """Convert user input to ZCL values.""" converted_fields: dict[str, Any] = {} for field in schema.fields: if field.name not in fields: continue value = fields[field.name] if issubclass(field.type, enum.Flag) and isinstance(value, list): new_value = 0 for flag in value: if isinstance(flag, str): new_value |= field.type[flag.replace(" ", "_")] else: new_value |= flag value = field.type(new_value) elif issubclass(field.type, enum.Enum): value = ( field.type[value.replace(" ", "_")] if isinstance(value, str) else field.type(value) ) else: value = field.type(value) _LOGGER.debug( "Converted ZCL schema field(%s) value from: %s to: %s", field.name, fields[field.name], value, ) converted_fields[field.name] = value return converted_fields
Determine if target is bindable to source.
def async_is_bindable_target(source_zha_device, target_zha_device): """Determine if target is bindable to source.""" if target_zha_device.nwk == 0x0000: return True source_clusters = source_zha_device.async_get_std_clusters() target_clusters = target_zha_device.async_get_std_clusters() for endpoint_id in source_clusters: for t_endpoint_id in target_clusters: matches = set( source_clusters[endpoint_id][CLUSTER_TYPE_OUT].keys() ).intersection(target_clusters[t_endpoint_id][CLUSTER_TYPE_IN].keys()) if any(bindable in BINDABLE_CLUSTERS for bindable in matches): return True return False
Get the value for the specified configuration from the ZHA config entry.
def async_get_zha_config_value( config_entry: ConfigEntry, section: str, config_key: str, default: _T ) -> _T: """Get the value for the specified configuration from the ZHA config entry.""" return ( config_entry.options.get(CUSTOM_CONFIGURATION, {}) .get(section, {}) .get(config_key, default) )
Determine if a device containing the specified in cluster is paired.
def async_cluster_exists(hass: HomeAssistant, cluster_id, skip_coordinator=True): """Determine if a device containing the specified in cluster is paired.""" zha_gateway = get_zha_gateway(hass) zha_devices = zha_gateway.devices.values() for zha_device in zha_devices: if skip_coordinator and zha_device.is_coordinator: continue clusters_by_endpoint = zha_device.async_get_clusters() for clusters in clusters_by_endpoint.values(): if ( cluster_id in clusters[CLUSTER_TYPE_IN] or cluster_id in clusters[CLUSTER_TYPE_OUT] ): return True return False
Get a ZHA device for the given device registry id.
def async_get_zha_device(hass: HomeAssistant, device_id: str) -> ZHADevice: """Get a ZHA device for the given device registry id.""" device_registry = dr.async_get(hass) registry_device = device_registry.async_get(device_id) if not registry_device: _LOGGER.error("Device id `%s` not found in registry", device_id) raise KeyError(f"Device id `{device_id}` not found in registry.") zha_gateway = get_zha_gateway(hass) try: ieee_address = list(registry_device.identifiers)[0][1] ieee = zigpy.types.EUI64.convert(ieee_address) except (IndexError, ValueError) as ex: _LOGGER.error( "Unable to determine device IEEE for device with device id `%s`", device_id ) raise KeyError( f"Unable to determine device IEEE for device with device id `{device_id}`." ) from ex return zha_gateway.devices[ieee]
Find attributes with matching key from states.
def find_state_attributes(states: list[State], key: str) -> Iterator[Any]: """Find attributes with matching key from states.""" for state in states: if (value := state.attributes.get(key)) is not None: yield value
Return the mean of the supplied values.
def mean_int(*args): """Return the mean of the supplied values.""" return int(sum(args) / len(args))
Return the mean values along the columns of the supplied values.
def mean_tuple(*args): """Return the mean values along the columns of the supplied values.""" return tuple(sum(x) / len(x) for x in zip(*args, strict=False))
Find the first attribute matching key from states. If none are found, return default.
def reduce_attribute( states: list[State], key: str, default: Any | None = None, reduce: Callable[..., Any] = mean_int, ) -> Any: """Find the first attribute matching key from states. If none are found, return default. """ attrs = list(find_state_attributes(states, key)) if not attrs: return default if len(attrs) == 1: return attrs[0] return reduce(*attrs)
Convert string to install code bytes and validate length.
def convert_install_code(value: str) -> zigpy.types.KeyData: """Convert string to install code bytes and validate length.""" try: code = binascii.unhexlify(value.replace("-", "").lower()) except binascii.Error as exc: raise vol.Invalid(f"invalid hex string: {value}") from exc if len(code) != 18: # 16 byte code + 2 crc bytes raise vol.Invalid("invalid length of the install code") link_key = zigpy.util.convert_install_code(code) if link_key is None: raise vol.Invalid("invalid install code") return link_key
Try to parse the QR code. if successful, return a tuple of a EUI64 address and install code.
def qr_to_install_code(qr_code: str) -> tuple[zigpy.types.EUI64, zigpy.types.KeyData]: """Try to parse the QR code. if successful, return a tuple of a EUI64 address and install code. """ for code_pattern in QR_CODES: match = re.search(code_pattern, qr_code, re.VERBOSE) if match is None: continue ieee_hex = binascii.unhexlify(match[1]) ieee = zigpy.types.EUI64(ieee_hex[::-1]) # Bosch supplies (A) device specific link key (DSLK) or (A) install code + crc if "RB01SG" in code_pattern and len(match[2]) == 32: link_key_hex = binascii.unhexlify(match[2]) link_key = zigpy.types.KeyData(link_key_hex) return ieee, link_key install_code = match[2] # install_code sanity check link_key = convert_install_code(install_code) return ieee, link_key raise vol.Invalid(f"couldn't convert qr code: {qr_code}")
Get the global ZHA data object.
def get_zha_data(hass: HomeAssistant) -> ZHAData: """Get the global ZHA data object.""" if DATA_ZHA not in hass.data: hass.data[DATA_ZHA] = ZHAData() return hass.data[DATA_ZHA]
Get the ZHA gateway object.
def get_zha_gateway(hass: HomeAssistant) -> ZHAGateway: """Get the ZHA gateway object.""" if (zha_gateway := get_zha_data(hass).gateway) is None: raise ValueError("No gateway object exists") return zha_gateway
Validate and return a unit of measure.
def validate_unit(quirks_unit: enum.Enum) -> enum.Enum: """Validate and return a unit of measure.""" return UNITS_OF_MEASURE[type(quirks_unit).__name__](quirks_unit.value)
Validate and return a device class.
def validate_device_class( device_class_enum: type[ BinarySensorDeviceClass | SensorDeviceClass | NumberDeviceClass ], metadata_value: enum.Enum, platform: str, logger: logging.Logger, ) -> BinarySensorDeviceClass | SensorDeviceClass | NumberDeviceClass | None: """Validate and return a device class.""" try: return device_class_enum(metadata_value.value) except ValueError as ex: logger.warning( "Quirks provided an invalid device class: %s for platform %s: %s", metadata_value, platform, ex, ) return None
Convert single str or None to a set. Pass through callables and sets.
def set_or_callable(value) -> frozenset[str] | Callable: """Convert single str or None to a set. Pass through callables and sets.""" if value is None: return frozenset() if callable(value): return value if isinstance(value, (frozenset, set, list)): return frozenset(value) return frozenset([str(value)])
Return true if the manufacturer and model match known Hue motion sensor models.
def is_hue_motion_sensor(cluster_handler: ClusterHandler) -> bool: """Return true if the manufacturer and model match known Hue motion sensor models.""" return cluster_handler.cluster.endpoint.manufacturer in ( "Philips", "Signify Netherlands B.V.", ) and cluster_handler.cluster.endpoint.model in ( "SML001", "SML002", "SML003", "SML004", )
Return true if the manufacturer and model match known Sonoff sensor models.
def is_sonoff_presence_sensor(cluster_handler: ClusterHandler) -> bool: """Return true if the manufacturer and model match known Sonoff sensor models.""" return cluster_handler.cluster.endpoint.manufacturer in ( "SONOFF", ) and cluster_handler.cluster.endpoint.model in ("SNZB-06P",)
Wrap zigpy exceptions in `HomeAssistantError` exceptions.
def wrap_zigpy_exceptions() -> Iterator[None]: """Wrap zigpy exceptions in `HomeAssistantError` exceptions.""" try: yield except TimeoutError as exc: raise HomeAssistantError( "Failed to send request: device did not respond" ) from exc except zigpy.exceptions.ZigbeeException as exc: message = "Failed to send request" if str(exc): message = f"{message}: {exc}" raise HomeAssistantError(message) from exc
Send a request with retries and wrap expected zigpy exceptions.
def retry_request(func: _FuncType[_P]) -> _ReturnFuncType[_P]: """Send a request with retries and wrap expected zigpy exceptions.""" @functools.wraps(func) async def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> Any: with wrap_zigpy_exceptions(): return await RETRYABLE_REQUEST_DECORATOR(func)(*args, **kwargs) return wrapper
Parse and log a zigbee cluster command.
def parse_and_log_command(cluster_handler, tsn, command_id, args): """Parse and log a zigbee cluster command.""" try: name = cluster_handler.cluster.server_commands[command_id].name except KeyError: name = f"0x{command_id:02X}" cluster_handler.debug( "received '%s' command with %s args on cluster_id '%s' tsn '%s'", name, args, cluster_handler.cluster.cluster_id, tsn, ) return name
Format the difference between two network backups.
def _format_settings_diff(old_state: NetworkBackup, new_state: NetworkBackup) -> str: """Format the difference between two network backups.""" lines: list[str] = [] def _add_difference( lines: list[str], text: str, old: Any, new: Any, pre: bool = True ) -> None: """Add a line to the list if the values are different.""" wrap = "`" if pre else "" if old != new: lines.append(f"{text}: {wrap}{old}{wrap} \u2192 {wrap}{new}{wrap}") _add_difference( lines, "Channel", old=old_state.network_info.channel, new=new_state.network_info.channel, pre=False, ) _add_difference( lines, "Node IEEE", old=old_state.node_info.ieee, new=new_state.node_info.ieee, ) _add_difference( lines, "PAN ID", old=old_state.network_info.pan_id, new=new_state.network_info.pan_id, ) _add_difference( lines, "Extended PAN ID", old=old_state.network_info.extended_pan_id, new=new_state.network_info.extended_pan_id, ) _add_difference( lines, "NWK update ID", old=old_state.network_info.nwk_update_id, new=new_state.network_info.nwk_update_id, pre=False, ) _add_difference( lines, "TC Link Key", old=old_state.network_info.tc_link_key.key, new=new_state.network_info.tc_link_key.key, ) _add_difference( lines, "Network Key", old=old_state.network_info.network_key.key, new=new_state.network_info.network_key.key, ) return "\n".join([f"- {line}" for line in lines])
Identify the radio hardware with the given serial port.
def _detect_radio_hardware(hass: HomeAssistant, device: str) -> HardwareType: """Identify the radio hardware with the given serial port.""" try: yellow_hardware.async_info(hass) except HomeAssistantError: pass else: if device == YELLOW_RADIO_DEVICE: return HardwareType.YELLOW try: info = skyconnect_hardware.async_info(hass) except HomeAssistantError: pass else: for hardware_info in info: for entry_id in hardware_info.config_entries or []: entry = hass.config_entries.async_get_entry(entry_id) if entry is not None and entry.data["device"] == device: return HardwareType.SKYCONNECT return HardwareType.OTHER
Delete repair issues that should disappear on a successful startup.
def async_delete_blocking_issues(hass: HomeAssistant) -> None: """Delete repair issues that should disappear on a successful startup.""" ir.async_delete_issue(hass, DOMAIN, ISSUE_WRONG_SILABS_FIRMWARE_INSTALLED) ir.async_delete_issue(hass, DOMAIN, ISSUE_INCONSISTENT_NETWORK_SETTINGS)
Set up the ZhongHong HVAC platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the ZhongHong HVAC platform.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) gw_addr = config.get(CONF_GATEWAY_ADDRRESS) hub = ZhongHongGateway(host, port, gw_addr) devices = [ ZhongHongClimate(hub, addr_out, addr_in) for (addr_out, addr_in) in hub.discovery_ac() ] _LOGGER.debug("We got %s zhong_hong climate devices", len(devices)) hub_is_initialized = False def _start_hub(): """Start the hub socket and query status of all devices.""" hub.start_listen() hub.query_all_status() async def startup(): """Start hub socket after all climate entity is set up.""" nonlocal hub_is_initialized if not all(device.is_initialized for device in devices): return if hub_is_initialized: return _LOGGER.debug("zhong_hong hub start listen event") await hass.async_add_executor_job(_start_hub) hub_is_initialized = True async_dispatcher_connect(hass, SIGNAL_DEVICE_ADDED, startup) # add devices after SIGNAL_DEVICE_SETTED_UP event is listened add_entities(devices) def stop_listen(event): """Stop ZhongHongHub socket.""" hub.stop_listen() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_listen)
Set up the Ziggo Mediabox XL platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Ziggo Mediabox XL platform.""" hass.data[DATA_KNOWN_DEVICES] = known_devices = set() # Is this a manual configuration? if (host := config.get(CONF_HOST)) is not None: name = config.get(CONF_NAME) manual_config = True elif discovery_info is not None: host = discovery_info["host"] name = discovery_info.get("name") manual_config = False else: _LOGGER.error("Cannot determine device") return # Only add a device once, so discovered devices do not override manual # config. hosts = [] connection_successful = False ip_addr = socket.gethostbyname(host) if ip_addr not in known_devices: try: # Mediabox instance with a timeout of 3 seconds. mediabox = ZiggoMediaboxXL(ip_addr, 3) # Check if a connection can be established to the device. if mediabox.test_connection(): connection_successful = True elif manual_config: _LOGGER.info("Can't connect to %s", host) else: _LOGGER.error("Can't connect to %s", host) # When the device is in eco mode it's not connected to the network # so it needs to be added anyway if it's configured manually. if manual_config or connection_successful: hosts.append( ZiggoMediaboxXLDevice(mediabox, host, name, connection_successful) ) known_devices.add(ip_addr) except OSError as error: _LOGGER.error("Can't connect to %s: %s", host, error) else: _LOGGER.info("Ignoring duplicate Ziggo Mediabox XL %s", host) add_entities(hosts, True)
Test if the user has the default config value from adding "zone:".
def empty_value(value: Any) -> Any: """Test if the user has the default config value from adding "zone:".""" if isinstance(value, dict) and len(value) == 0: return [] raise vol.Invalid("Not a default value")
Find the active zone for given latitude, longitude. This method must be run in the event loop.
def async_active_zone( hass: HomeAssistant, latitude: float, longitude: float, radius: int = 0 ) -> State | None: """Find the active zone for given latitude, longitude. This method must be run in the event loop. """ # Sort entity IDs so that we are deterministic if equal distance to 2 zones min_dist: float = sys.maxsize closest: State | None = None # This can be called before async_setup by device tracker zone_entity_ids: Iterable[str] = hass.data.get(ZONE_ENTITY_IDS, ()) for entity_id in zone_entity_ids: if ( not (zone := hass.states.get(entity_id)) # Skip unavailable zones or zone.state == STATE_UNAVAILABLE # Skip passive zones or (zone_attrs := zone.attributes).get(ATTR_PASSIVE) # Skip zones where we cannot calculate distance or ( zone_dist := distance( latitude, longitude, zone_attrs[ATTR_LATITUDE], zone_attrs[ATTR_LONGITUDE], ) ) is None # Skip zone that are outside the radius aka the # lat/long is outside the zone or not (zone_dist - (zone_radius := zone_attrs[ATTR_RADIUS]) < radius) ): continue # If have a closest and its not closer than the closest skip it if closest and not ( zone_dist < min_dist or ( # If same distance, prefer smaller zone zone_dist == min_dist and zone_radius < closest.attributes[ATTR_RADIUS] ) ): continue # We got here which means it closer than the previous known closest # or equal distance but this one is smaller. min_dist = zone_dist closest = zone return closest
Set up track of entity IDs for zones.
def async_setup_track_zone_entity_ids(hass: HomeAssistant) -> None: """Set up track of entity IDs for zones.""" zone_entity_ids: list[str] = hass.states.async_entity_ids(DOMAIN) hass.data[ZONE_ENTITY_IDS] = zone_entity_ids @callback def _async_add_zone_entity_id( event_: Event[EventStateChangedData], ) -> None: """Add zone entity ID.""" zone_entity_ids.append(event_.data["entity_id"]) zone_entity_ids.sort() @callback def _async_remove_zone_entity_id( event_: Event[EventStateChangedData], ) -> None: """Remove zone entity ID.""" zone_entity_ids.remove(event_.data["entity_id"]) event.async_track_state_added_domain(hass, DOMAIN, _async_add_zone_entity_id) event.async_track_state_removed_domain(hass, DOMAIN, _async_remove_zone_entity_id)
Test if given latitude, longitude is in given zone. Async friendly.
def in_zone(zone: State, latitude: float, longitude: float, radius: float = 0) -> bool: """Test if given latitude, longitude is in given zone. Async friendly. """ if zone.state == STATE_UNAVAILABLE: return False zone_dist = distance( latitude, longitude, zone.attributes[ATTR_LATITUDE], zone.attributes[ATTR_LONGITUDE], ) if zone_dist is None or zone.attributes[ATTR_RADIUS] is None: return False return zone_dist - radius < cast(float, zone.attributes[ATTR_RADIUS])
Return the home zone config.
def _home_conf(hass: HomeAssistant) -> dict: """Return the home zone config.""" return { CONF_NAME: hass.config.location_name, CONF_LATITUDE: hass.config.latitude, CONF_LONGITUDE: hass.config.longitude, CONF_RADIUS: DEFAULT_RADIUS, CONF_ICON: ICON_HOME, CONF_PASSIVE: False, }
Set up the ZoneMinder cameras.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the ZoneMinder cameras.""" filter_urllib3_logging() cameras = [] zm_client: ZoneMinder for zm_client in hass.data[ZONEMINDER_DOMAIN].values(): if not (monitors := zm_client.get_monitors()): raise PlatformNotReady( "Camera could not fetch any monitors from ZoneMinder" ) for monitor in monitors: _LOGGER.info("Initializing camera %s", monitor.id) cameras.append(ZoneMinderCamera(monitor, zm_client.verify_ssl)) add_entities(cameras)
Set up the ZoneMinder sensor platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the ZoneMinder sensor platform.""" include_archived = config[CONF_INCLUDE_ARCHIVED] monitored_conditions = config[CONF_MONITORED_CONDITIONS] sensors: list[SensorEntity] = [] zm_client: ZoneMinder for zm_client in hass.data[ZONEMINDER_DOMAIN].values(): if not (monitors := zm_client.get_monitors()): raise PlatformNotReady( "Sensor could not fetch any monitors from ZoneMinder" ) for monitor in monitors: sensors.append(ZMSensorMonitors(monitor)) sensors.extend( [ ZMSensorEvents(monitor, include_archived, description) for description in SENSOR_TYPES if description.key in monitored_conditions ] ) sensors.append(ZMSensorRunState(zm_client)) add_entities(sensors)
Set up the ZoneMinder switch platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the ZoneMinder switch platform.""" on_state = MonitorState(config.get(CONF_COMMAND_ON)) off_state = MonitorState(config.get(CONF_COMMAND_OFF)) switches: list[ZMSwitchMonitors] = [] zm_client: ZoneMinder for zm_client in hass.data[ZONEMINDER_DOMAIN].values(): if not (monitors := zm_client.get_monitors()): raise PlatformNotReady( "Switch could not fetch any monitors from ZoneMinder" ) switches.extend( ZMSwitchMonitors(monitor, on_state, off_state) for monitor in monitors ) add_entities(switches)
Set up the ZoneMinder component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the ZoneMinder component.""" hass.data[DOMAIN] = {} success = True for conf in config[DOMAIN]: protocol = "https" if conf[CONF_SSL] else "http" host_name = conf[CONF_HOST] server_origin = f"{protocol}://{host_name}" zm_client = ZoneMinder( server_origin, conf.get(CONF_USERNAME), conf.get(CONF_PASSWORD), conf.get(CONF_PATH), conf.get(CONF_PATH_ZMS), conf.get(CONF_VERIFY_SSL), ) hass.data[DOMAIN][host_name] = zm_client try: success = zm_client.login() and success except RequestsConnectionError as ex: _LOGGER.error( "ZoneMinder connection failure to %s: %s", host_name, ex, ) def set_active_state(call: ServiceCall) -> None: """Set the ZoneMinder run state to the given state name.""" zm_id = call.data[ATTR_ID] state_name = call.data[ATTR_NAME] if zm_id not in hass.data[DOMAIN]: _LOGGER.error("Invalid ZoneMinder host provided: %s", zm_id) if not hass.data[DOMAIN][zm_id].set_active_state(state_name): _LOGGER.error( "Unable to change ZoneMinder state. Host: %s, state: %s", zm_id, state_name, ) hass.services.register( DOMAIN, SERVICE_SET_RUN_STATE, set_active_state, schema=SET_RUN_STATE_SCHEMA ) hass.async_create_task( async_load_platform(hass, Platform.BINARY_SENSOR, DOMAIN, {}, config) ) return success
Get the add-on manager.
def get_addon_manager(hass: HomeAssistant) -> AddonManager: """Get the add-on manager.""" return AddonManager(hass, LOGGER, "Z-Wave JS", ADDON_SLUG)
Handle provisioning entry dict to ProvisioningEntry.
def convert_planned_provisioning_entry(info: dict) -> ProvisioningEntry: """Handle provisioning entry dict to ProvisioningEntry.""" return ProvisioningEntry( dsk=info[DSK], security_classes=info[SECURITY_CLASSES], status=info[STATUS], requested_security_classes=info.get(REQUESTED_SECURITY_CLASSES), additional_properties={ k: v for k, v in info.items() if k not in (DSK, SECURITY_CLASSES, STATUS, REQUESTED_SECURITY_CLASSES) }, )
Convert QR provisioning information dict to QRProvisioningInformation.
def convert_qr_provisioning_information(info: dict) -> QRProvisioningInformation: """Convert QR provisioning information dict to QRProvisioningInformation.""" return QRProvisioningInformation( version=info[VERSION], security_classes=info[SECURITY_CLASSES], dsk=info[DSK], generic_device_class=info[GENERIC_DEVICE_CLASS], specific_device_class=info[SPECIFIC_DEVICE_CLASS], installer_icon_type=info[INSTALLER_ICON_TYPE], manufacturer_id=info[MANUFACTURER_ID], product_type=info[PRODUCT_TYPE], product_id=info[PRODUCT_ID], application_version=info[APPLICATION_VERSION], max_inclusion_request_interval=info.get(MAX_INCLUSION_REQUEST_INTERVAL), uuid=info.get(UUID), supported_protocols=info.get(SUPPORTED_PROTOCOLS), status=info[STATUS], requested_security_classes=info.get(REQUESTED_SECURITY_CLASSES), additional_properties=info.get(ADDITIONAL_PROPERTIES, {}), )
Decorate async function to get entry.
def async_get_entry( orig_func: Callable[ [HomeAssistant, ActiveConnection, dict[str, Any], ConfigEntry, Client, Driver], Coroutine[Any, Any, None], ], ) -> Callable[ [HomeAssistant, ActiveConnection, dict[str, Any]], Coroutine[Any, Any, None] ]: """Decorate async function to get entry.""" @wraps(orig_func) async def async_get_entry_func( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Provide user specific data and store to function.""" entry, client, driver = await _async_get_entry( hass, connection, msg, msg[ENTRY_ID] ) if not entry or not client or not driver: return await orig_func(hass, connection, msg, entry, client, driver) return async_get_entry_func
Decorate async function to get node.
def async_get_node( orig_func: Callable[ [HomeAssistant, ActiveConnection, dict[str, Any], Node], Coroutine[Any, Any, None], ], ) -> Callable[ [HomeAssistant, ActiveConnection, dict[str, Any]], Coroutine[Any, Any, None] ]: """Decorate async function to get node.""" @wraps(orig_func) async def async_get_node_func( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Provide user specific data and store to function.""" node = await _async_get_node(hass, connection, msg, msg[DEVICE_ID]) if not node: return await orig_func(hass, connection, msg, node) return async_get_node_func
Decorate async function to handle FailedCommand and send relevant error.
def async_handle_failed_command( orig_func: Callable[ Concatenate[HomeAssistant, ActiveConnection, dict[str, Any], _P], Coroutine[Any, Any, None], ], ) -> Callable[ Concatenate[HomeAssistant, ActiveConnection, dict[str, Any], _P], Coroutine[Any, Any, None], ]: """Decorate async function to handle FailedCommand and send relevant error.""" @wraps(orig_func) async def async_handle_failed_command_func( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any], *args: _P.args, **kwargs: _P.kwargs, ) -> None: """Handle FailedCommand within function and send relevant error.""" try: await orig_func(hass, connection, msg, *args, **kwargs) except FailedCommand as err: # Unsubscribe to callbacks if unsubs := msg.get(DATA_UNSUBSCRIBE): for unsub in unsubs: unsub() connection.send_error(msg[ID], err.error_code, err.args[0]) return async_handle_failed_command_func
Get node status.
def node_status(node: Node) -> dict[str, Any]: """Get node status.""" return { "node_id": node.node_id, "is_routing": node.is_routing, "status": node.status, "is_secure": node.is_secure, "ready": node.ready, "zwave_plus_version": node.zwave_plus_version, "highest_security_class": node.highest_security_class, "is_controller_node": node.is_controller_node, "has_firmware_update_cc": any( cc.id == CommandClass.FIRMWARE_UPDATE_MD.value for cc in node.command_classes ), }
Register all of our api endpoints.
def async_register_api(hass: HomeAssistant) -> None: """Register all of our api endpoints.""" websocket_api.async_register_command(hass, websocket_network_status) websocket_api.async_register_command(hass, websocket_subscribe_node_status) websocket_api.async_register_command(hass, websocket_node_status) websocket_api.async_register_command(hass, websocket_node_metadata) websocket_api.async_register_command(hass, websocket_node_alerts) websocket_api.async_register_command(hass, websocket_add_node) websocket_api.async_register_command(hass, websocket_grant_security_classes) websocket_api.async_register_command(hass, websocket_validate_dsk_and_enter_pin) websocket_api.async_register_command(hass, websocket_provision_smart_start_node) websocket_api.async_register_command(hass, websocket_unprovision_smart_start_node) websocket_api.async_register_command(hass, websocket_get_provisioning_entries) websocket_api.async_register_command(hass, websocket_parse_qr_code_string) websocket_api.async_register_command( hass, websocket_try_parse_dsk_from_qr_code_string ) websocket_api.async_register_command(hass, websocket_supports_feature) websocket_api.async_register_command(hass, websocket_stop_inclusion) websocket_api.async_register_command(hass, websocket_stop_exclusion) websocket_api.async_register_command(hass, websocket_remove_node) websocket_api.async_register_command(hass, websocket_remove_failed_node) websocket_api.async_register_command(hass, websocket_replace_failed_node) websocket_api.async_register_command(hass, websocket_begin_rebuilding_routes) websocket_api.async_register_command( hass, websocket_subscribe_rebuild_routes_progress ) websocket_api.async_register_command(hass, websocket_stop_rebuilding_routes) websocket_api.async_register_command(hass, websocket_refresh_node_info) websocket_api.async_register_command(hass, websocket_refresh_node_values) websocket_api.async_register_command(hass, websocket_refresh_node_cc_values) websocket_api.async_register_command(hass, websocket_rebuild_node_routes) websocket_api.async_register_command(hass, websocket_set_config_parameter) websocket_api.async_register_command(hass, websocket_get_config_parameters) websocket_api.async_register_command(hass, websocket_subscribe_log_updates) websocket_api.async_register_command(hass, websocket_update_log_config) websocket_api.async_register_command(hass, websocket_get_log_config) websocket_api.async_register_command( hass, websocket_update_data_collection_preference ) websocket_api.async_register_command(hass, websocket_data_collection_status) websocket_api.async_register_command(hass, websocket_abort_firmware_update) websocket_api.async_register_command( hass, websocket_is_node_firmware_update_in_progress ) websocket_api.async_register_command( hass, websocket_subscribe_firmware_update_status ) websocket_api.async_register_command( hass, websocket_get_node_firmware_update_capabilities ) websocket_api.async_register_command( hass, websocket_is_any_ota_firmware_update_in_progress ) websocket_api.async_register_command(hass, websocket_check_for_config_updates) websocket_api.async_register_command(hass, websocket_install_config_update) websocket_api.async_register_command( hass, websocket_subscribe_controller_statistics ) websocket_api.async_register_command(hass, websocket_subscribe_node_statistics) websocket_api.async_register_command(hass, websocket_hard_reset_controller) hass.http.register_view(FirmwareUploadView(dr.async_get(hass)))
Validate that filename is provided if log_to_file is True.
def filename_is_present_if_logging_to_file(obj: dict) -> dict: """Validate that filename is provided if log_to_file is True.""" if obj.get(LOG_TO_FILE, False) and FILENAME not in obj: raise vol.Invalid("`filename` must be provided if logging to file") return obj
Get a dictionary of a node's firmware update progress.
def _get_node_firmware_update_progress_dict( progress: NodeFirmwareUpdateProgress, ) -> dict[str, int | float]: """Get a dictionary of a node's firmware update progress.""" return { "current_file": progress.current_file, "total_files": progress.total_files, "sent_fragments": progress.sent_fragments, "total_fragments": progress.total_fragments, "progress": progress.progress, }
Get a dictionary of a controller's firmware update progress.
def _get_controller_firmware_update_progress_dict( progress: ControllerFirmwareUpdateProgress, ) -> dict[str, int | float]: """Get a dictionary of a controller's firmware update progress.""" return { "current_file": 1, "total_files": 1, "sent_fragments": progress.sent_fragments, "total_fragments": progress.total_fragments, "progress": progress.progress, }
Get dictionary of controller statistics.
def _get_controller_statistics_dict( statistics: ControllerStatistics, ) -> dict[str, int]: """Get dictionary of controller statistics.""" return { "messages_tx": statistics.messages_tx, "messages_rx": statistics.messages_rx, "messages_dropped_tx": statistics.messages_dropped_tx, "messages_dropped_rx": statistics.messages_dropped_rx, "nak": statistics.nak, "can": statistics.can, "timeout_ack": statistics.timeout_ack, "timout_response": statistics.timeout_response, "timeout_callback": statistics.timeout_callback, }
Get dictionary of node statistics.
def _get_node_statistics_dict( hass: HomeAssistant, statistics: NodeStatistics ) -> dict[str, Any]: """Get dictionary of node statistics.""" dev_reg = dr.async_get(hass) def _convert_node_to_device_id(node: Node) -> str: """Convert a node to a device id.""" driver = node.client.driver assert driver device = dev_reg.async_get_device(identifiers={get_device_id(driver, node)}) assert device return device.id data: dict = { "commands_tx": statistics.commands_tx, "commands_rx": statistics.commands_rx, "commands_dropped_tx": statistics.commands_dropped_tx, "commands_dropped_rx": statistics.commands_dropped_rx, "timeout_response": statistics.timeout_response, "rtt": statistics.rtt, "rssi": statistics.rssi, "lwr": statistics.lwr.as_dict() if statistics.lwr else None, "nlwr": statistics.nlwr.as_dict() if statistics.nlwr else None, } for key in ("lwr", "nlwr"): if not data[key]: continue for key_2 in ("repeaters", "route_failed_between"): if not data[key][key_2]: continue data[key][key_2] = [ _convert_node_to_device_id(node) for node in data[key][key_2] ] return data
Return a schema for the manual step.
def get_manual_schema(user_input: dict[str, Any]) -> vol.Schema: """Return a schema for the manual step.""" default_url = user_input.get(CONF_URL, DEFAULT_URL) return vol.Schema({vol.Required(CONF_URL, default=default_url): str})
Return a schema for the on Supervisor step.
def get_on_supervisor_schema(user_input: dict[str, Any]) -> vol.Schema: """Return a schema for the on Supervisor step.""" default_use_addon = user_input[CONF_USE_ADDON] return vol.Schema({vol.Optional(CONF_USE_ADDON, default=default_use_addon): bool})
Return a dict of USB ports and their friendly names.
def get_usb_ports() -> dict[str, str]: """Return a dict of USB ports and their friendly names.""" ports = list_ports.comports() port_descriptions = {} for port in ports: vid: str | None = None pid: str | None = None if port.vid is not None and port.pid is not None: usb_device = usb.usb_device_from_port(port) vid = usb_device.vid pid = usb_device.pid dev_path = usb.get_serial_by_id(port.device) human_name = usb.human_readable_device_name( dev_path, port.serial_number, port.manufacturer, port.description, vid, pid, ) port_descriptions[dev_path] = human_name return port_descriptions
Validate and coerce a boolean value.
def boolean(value: Any) -> bool: """Validate and coerce a boolean value.""" if isinstance(value, bool): return value if isinstance(value, str): value = value.lower().strip() if value in ("true", "yes", "on", "enable"): return True if value in ("false", "no", "off", "disable"): return False raise vol.Invalid(f"invalid boolean value {value}")
Generate the config parameter name used in a device automation subtype.
def generate_config_parameter_subtype(config_value: ConfigurationValue) -> str: """Generate the config parameter name used in a device automation subtype.""" parameter = str(config_value.property_) if config_value.property_key: # Property keys for config values are always an int assert isinstance(config_value.property_key, int) parameter = ( f"{parameter}[{hex(config_value.property_key)}] on endpoint " f"{config_value.endpoint}" ) return ( f"{parameter} ({config_value.property_name}) on endpoint " f"{config_value.endpoint}" )
Return whether device's config entries are not loaded.
def async_bypass_dynamic_config_validation(hass: HomeAssistant, device_id: str) -> bool: """Return whether device's config entries are not loaded.""" dev_reg = dr.async_get(hass) if (device := dev_reg.async_get(device_id)) is None: raise ValueError(f"Device {device_id} not found") entry = next( ( config_entry for config_entry in hass.config_entries.async_entries(DOMAIN) if config_entry.entry_id in device.config_entries and config_entry.state == ConfigEntryState.LOADED ), None, ) if not entry: return True # The driver may not be ready when the config entry is loaded. client: ZwaveClient = hass.data[DOMAIN][entry.entry_id][DATA_CLIENT] return client.driver is 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.""" condition_type = config[CONF_TYPE] device_id = config[CONF_DEVICE_ID] @callback def test_node_status(hass: HomeAssistant, variables: TemplateVarsType) -> bool: """Test if node status is a certain state.""" node = async_get_node_from_device_id(hass, device_id) return bool(node.status.name.lower() == config[CONF_STATUS]) if condition_type == NODE_STATUS_TYPE: return test_node_status @callback def test_config_parameter(hass: HomeAssistant, variables: TemplateVarsType) -> bool: """Test if config parameter is a certain state.""" node = async_get_node_from_device_id(hass, device_id) config_value = cast(ConfigurationValue, node.values[config[CONF_VALUE_ID]]) return bool(config_value.value == config[ATTR_VALUE]) if condition_type == CONFIG_PARAMETER_TYPE: return test_config_parameter @callback def test_value(hass: HomeAssistant, variables: TemplateVarsType) -> bool: """Test if value is a certain state.""" node = async_get_node_from_device_id(hass, device_id) value = get_zwave_value_from_config(node, config) return bool(value.value == config[ATTR_VALUE]) if condition_type == VALUE_TYPE: return test_value raise HomeAssistantError(f"Unhandled condition type {condition_type}")
Get trigger platform from Z-Wave JS trigger type.
def get_trigger_platform_from_type(trigger_type: str) -> str: """Get trigger platform from Z-Wave JS trigger type.""" trigger_split = trigger_type.split(".") # Our convention for trigger types is to have the trigger type at the beginning # delimited by a `.`. For zwave_js triggers, there is a `.` in the name if (trigger_platform := trigger_split[0]) == DOMAIN: return ".".join(trigger_split[:2]) return trigger_platform
Return redacted value of a Z-Wave value.
def _redacted_value(zwave_value: ValueDataType) -> ValueDataType: """Return redacted value of a Z-Wave value.""" redacted_value: ValueDataType = deepcopy(zwave_value) redacted_value["value"] = REDACTED return redacted_value
Redact value of a Z-Wave value if it matches criteria to redact.
def optionally_redact_value_of_zwave_value(zwave_value: ValueDataType) -> ValueDataType: """Redact value of a Z-Wave value if it matches criteria to redact.""" # If the value has no value, there is nothing to redact if zwave_value.get("value") in (None, ""): return zwave_value if zwave_value.get("metadata", {}).get("secret"): return _redacted_value(zwave_value) for value_to_redact in VALUES_TO_REDACT: if value_matches_matcher(value_to_redact, zwave_value): return _redacted_value(zwave_value) return zwave_value
Redact node state.
def redact_node_state(node_state: dict) -> dict: """Redact node state.""" redacted_state: dict = deepcopy(node_state) # dump_msgs returns values in a list but dump_node_state returns them in a dict if isinstance(node_state["values"], list): redacted_state["values"] = [ optionally_redact_value_of_zwave_value(zwave_value) for zwave_value in node_state["values"] ] else: redacted_state["values"] = { value_id: optionally_redact_value_of_zwave_value(zwave_value) for value_id, zwave_value in node_state["values"].items() } return redacted_state
Get entities for a device.
def get_device_entities( hass: HomeAssistant, node: Node, config_entry: ConfigEntry, device: dr.DeviceEntry ) -> list[dict[str, Any]]: """Get entities for a device.""" entity_entries = er.async_entries_for_device( er.async_get(hass), device.id, include_disabled_entities=True ) entities = [] for entry in entity_entries: # Skip entities that are not part of this integration if entry.config_entry_id != config_entry.entry_id: continue # If the value ID returns as None, we don't need to include this entity if (value_id := get_value_id_from_unique_id(entry.unique_id)) is None: continue primary_value_data = None if (zwave_value := node.values.get(value_id)) is not None: primary_value_data = { "command_class": zwave_value.command_class, "command_class_name": zwave_value.command_class_name, "endpoint": zwave_value.endpoint, "property": zwave_value.property_, "property_name": zwave_value.property_name, "property_key": zwave_value.property_key, "property_key_name": zwave_value.property_key_name, } state_key = get_state_key_from_unique_id(entry.unique_id) if state_key is not None: primary_value_data["state_key"] = state_key entity = { "domain": entry.domain, "entity_id": entry.entity_id, "original_name": entry.original_name, "original_device_class": entry.original_device_class, "disabled": entry.disabled, "disabled_by": entry.disabled_by, "hidden_by": entry.hidden_by, "original_icon": entry.original_icon, "entity_category": entry.entity_category, "supported_features": entry.supported_features, "unit_of_measurement": entry.unit_of_measurement, "value_id": value_id, "primary_value": primary_value_data, } entities.append(entity) return entities
Run discovery on ZWave node and return matching (primary) values.
def async_discover_node_values( node: ZwaveNode, device: DeviceEntry, discovered_value_ids: dict[str, set[str]] ) -> Generator[ZwaveDiscoveryInfo, None, None]: """Run discovery on ZWave node and return matching (primary) values.""" for value in node.values.values(): # We don't need to rediscover an already processed value_id if value.value_id not in discovered_value_ids[device.id]: yield from async_discover_single_value(value, device, discovered_value_ids)
Run discovery on a single ZWave value and return matching schema info.
def async_discover_single_value( value: ZwaveValue, device: DeviceEntry, discovered_value_ids: dict[str, set[str]] ) -> Generator[ZwaveDiscoveryInfo, None, None]: """Run discovery on a single ZWave value and return matching schema info.""" discovered_value_ids[device.id].add(value.value_id) for schema in DISCOVERY_SCHEMAS: # check manufacturer_id, product_id, product_type if ( ( schema.manufacturer_id is not None and value.node.manufacturer_id not in schema.manufacturer_id ) or ( schema.product_id is not None and value.node.product_id not in schema.product_id ) or ( schema.product_type is not None and value.node.product_type not in schema.product_type ) ): continue # check firmware_version_range if schema.firmware_version_range is not None and ( ( schema.firmware_version_range.min is not None and schema.firmware_version_range.min_ver > AwesomeVersion(value.node.firmware_version) ) or ( schema.firmware_version_range.max is not None and schema.firmware_version_range.max_ver < AwesomeVersion(value.node.firmware_version) ) ): continue # check device_class_generic if value.node.device_class and not check_device_class( value.node.device_class.generic, schema.device_class_generic ): continue # check device_class_specific if value.node.device_class and not check_device_class( value.node.device_class.specific, schema.device_class_specific ): continue # check primary value if not check_value(value, schema.primary_value): continue # check additional required values if schema.required_values is not None and not all( any(check_value(val, val_scheme) for val in value.node.values.values()) for val_scheme in schema.required_values ): continue # check for values that may not be present if schema.absent_values is not None and any( any(check_value(val, val_scheme) for val in value.node.values.values()) for val_scheme in schema.absent_values ): continue # resolve helper data from template resolved_data = None additional_value_ids_to_watch = set() if schema.data_template: try: resolved_data = schema.data_template.resolve_data(value) except UnknownValueData as err: LOGGER.error( "Discovery for value %s on device '%s' (%s) will be skipped: %s", value, device.name_by_user or device.name, value.node, err, ) continue additional_value_ids_to_watch = schema.data_template.value_ids_to_watch( resolved_data ) # all checks passed, this value belongs to an entity yield ZwaveDiscoveryInfo( node=value.node, primary_value=value, assumed_state=schema.assumed_state, platform=schema.platform, platform_hint=schema.hint, platform_data_template=schema.data_template, platform_data=resolved_data, additional_value_ids_to_watch=additional_value_ids_to_watch, entity_registry_enabled_default=schema.entity_registry_enabled_default, entity_category=schema.entity_category, ) if not schema.allow_multi: # return early since this value may not be discovered # by other schemas/platforms return if value.command_class == CommandClass.CONFIGURATION: yield from async_discover_single_configuration_value( cast(ConfigurationValue, value) )
Run discovery on single Z-Wave configuration value and return schema matches.
def async_discover_single_configuration_value( value: ConfigurationValue, ) -> Generator[ZwaveDiscoveryInfo, None, None]: """Run discovery on single Z-Wave configuration value and return schema matches.""" if value.metadata.writeable and value.metadata.readable: if value.configuration_value_type == ConfigurationValueType.ENUMERATED: yield ZwaveDiscoveryInfo( node=value.node, primary_value=value, assumed_state=False, platform=Platform.SELECT, platform_hint="config_parameter", platform_data=None, additional_value_ids_to_watch=set(), entity_registry_enabled_default=False, ) elif value.configuration_value_type in ( ConfigurationValueType.RANGE, ConfigurationValueType.MANUAL_ENTRY, ): yield ZwaveDiscoveryInfo( node=value.node, primary_value=value, assumed_state=False, platform=Platform.NUMBER, platform_hint="config_parameter", platform_data=None, additional_value_ids_to_watch=set(), entity_registry_enabled_default=False, ) elif value.configuration_value_type == ConfigurationValueType.BOOLEAN: yield ZwaveDiscoveryInfo( node=value.node, primary_value=value, assumed_state=False, platform=Platform.SWITCH, platform_hint="config_parameter", platform_data=None, additional_value_ids_to_watch=set(), entity_registry_enabled_default=False, ) elif not value.metadata.writeable and value.metadata.readable: if value.configuration_value_type == ConfigurationValueType.BOOLEAN: yield ZwaveDiscoveryInfo( node=value.node, primary_value=value, assumed_state=False, platform=Platform.BINARY_SENSOR, platform_hint="config_parameter", platform_data=None, additional_value_ids_to_watch=set(), entity_registry_enabled_default=False, ) else: yield ZwaveDiscoveryInfo( node=value.node, primary_value=value, assumed_state=False, platform=Platform.SENSOR, platform_hint="config_parameter", platform_data=None, additional_value_ids_to_watch=set(), entity_registry_enabled_default=False, )
Check if value matches scheme.
def check_value(value: ZwaveValue, schema: ZWaveValueDiscoverySchema) -> bool: """Check if value matches scheme.""" # check command_class if ( schema.command_class is not None and value.command_class not in schema.command_class ): return False # check endpoint if schema.endpoint is not None and value.endpoint not in schema.endpoint: return False # check property if schema.property is not None and value.property_ not in schema.property: return False # check property_name if ( schema.property_name is not None and value.property_name not in schema.property_name ): return False # check property_key if ( schema.property_key is not None and value.property_key not in schema.property_key ): return False # check property_key against not_property_key set if ( schema.not_property_key is not None and value.property_key in schema.not_property_key ): return False # check metadata_type if schema.type is not None and value.metadata.type not in schema.type: return False # check metadata_readable if schema.readable is not None and value.metadata.readable != schema.readable: return False # check metadata_writeable if schema.writeable is not None and value.metadata.writeable != schema.writeable: return False # check available states if ( schema.any_available_states is not None and value.metadata.states is not None and not any( str(key) in value.metadata.states and value.metadata.states[str(key)] == val for key, val in schema.any_available_states ) ): return False # check value if schema.value is not None and value.value not in schema.value: return False # check metadata_stateful if schema.stateful is not None and value.metadata.stateful != schema.stateful: return False return True
Check if device class id or label matches.
def check_device_class( device_class: DeviceClassItem, required_value: set[str] | None ) -> bool: """Check if device class id or label matches.""" if required_value is None: return True if any(device_class.label == val for val in required_value): return True return False
Return a string with the command class and label.
def _cc_and_label(value: Value) -> str: """Return a string with the command class and label.""" label = value.metadata.label if label: label = label.lower() return f"{value.command_class_name.capitalize()} {label}".strip()
Return whether value matches matcher.
def value_matches_matcher( matcher: ZwaveValueMatcher, value_data: ValueDataType ) -> bool: """Return whether value matches matcher.""" command_class = None if "commandClass" in value_data: command_class = CommandClass(value_data["commandClass"]) zwave_value_id = ZwaveValueMatcher( property_=value_data.get("property"), command_class=command_class, endpoint=value_data.get("endpoint"), property_key=value_data.get("propertyKey"), ) return all( redacted_field_val is None or redacted_field_val == zwave_value_field_val for redacted_field_val, zwave_value_field_val in zip( astuple(matcher), astuple(zwave_value_id), strict=False ) )
Get the value ID and optional state key from a unique ID. Raises ValueError
def get_value_id_from_unique_id(unique_id: str) -> str | None: """Get the value ID and optional state key from a unique ID. Raises ValueError """ split_unique_id = unique_id.split(".") # If the unique ID contains a `-` in its second part, the unique ID contains # a value ID and we can return it. if "-" in (value_id := split_unique_id[1]): return value_id return None
Get the state key from a unique ID.
def get_state_key_from_unique_id(unique_id: str) -> int | None: """Get the state key from a unique ID.""" # If the unique ID has more than two parts, it's a special unique ID. If the last # part of the unique ID is an int, then it's a state key and we return it. if len(split_unique_id := unique_id.split(".")) > 2: try: return int(split_unique_id[-1]) except ValueError: pass return None
Return the value of a ZwaveValue.
def get_value_of_zwave_value(value: ZwaveValue | None) -> Any | None: """Return the value of a ZwaveValue.""" return value.value if value else None