response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Return the thread device type as a string. The underlying value is a bitmask, but we want to turn that to a human readable string. Some devices will have multiple capabilities. For example, an NL55 is SLEEPY | MINIMAL. In that case we return the "best" capability. https://openthread.io/guides/thread-primer/node-roles-and-types
def thread_node_capability_to_str(char: Characteristic) -> str: """Return the thread device type as a string. The underlying value is a bitmask, but we want to turn that to a human readable string. Some devices will have multiple capabilities. For example, an NL55 is SLEEPY | MINIMAL. In that case we return the "best" capability. https://openthread.io/guides/thread-primer/node-roles-and-types """ val = ThreadNodeCapabilities(char.value) if val & ThreadNodeCapabilities.BORDER_ROUTER_CAPABLE: # can act as a bridge between thread network and e.g. WiFi return "border_router_capable" if val & ThreadNodeCapabilities.ROUTER_ELIGIBLE: # radio always on, can be a router return "router_eligible" if val & ThreadNodeCapabilities.FULL: # radio always on, but can't be a router return "full" if val & ThreadNodeCapabilities.MINIMAL: # transceiver always on, does not need to poll for messages from its parent return "minimal" if val & ThreadNodeCapabilities.SLEEPY: # normally disabled, wakes on occasion to poll for messages from its parent return "sleepy" # Device has no known thread capabilities return "none"
Return the thread status as a string. The underlying value is a bitmask, but we want to turn that to a human readable string. So we check the flags in order. E.g. BORDER_ROUTER implies ROUTER, so its more important to show that value.
def thread_status_to_str(char: Characteristic) -> str: """Return the thread status as a string. The underlying value is a bitmask, but we want to turn that to a human readable string. So we check the flags in order. E.g. BORDER_ROUTER implies ROUTER, so its more important to show that value. """ val = ThreadStatus(char.value) if val & ThreadStatus.BORDER_ROUTER: # Device has joined the Thread network and is participating # in routing between mesh nodes. # It's also the border router - bridging the thread network # to WiFI/Ethernet/etc return "border_router" if val & ThreadStatus.LEADER: # Device has joined the Thread network and is participating # in routing between mesh nodes. # It's also the leader. There's only one leader and it manages # which nodes are routers. return "leader" if val & ThreadStatus.ROUTER: # Device has joined the Thread network and is participating # in routing between mesh nodes. return "router" if val & ThreadStatus.CHILD: # Device has joined the Thread network as a child # It's not participating in routing between mesh nodes return "child" if val & ThreadStatus.JOINING: # Device is currently joining its Thread network return "joining" if val & ThreadStatus.DETACHED: # Device is currently unable to reach its Thread network return "detached" # Must be ThreadStatus.DISABLED # Device is not currently connected to Thread and will not try to. return "disabled"
Convert a unique_id to a tuple of accessory id, service iid and characteristic iid. Depending on the field in the accessory map that is referenced, some of these may be None. Returns None if this unique_id doesn't follow the homekit_controller scheme and is invalid.
def unique_id_to_iids(unique_id: str) -> IidTuple | None: """Convert a unique_id to a tuple of accessory id, service iid and characteristic iid. Depending on the field in the accessory map that is referenced, some of these may be None. Returns None if this unique_id doesn't follow the homekit_controller scheme and is invalid. """ try: match unique_id.split("_"): case (unique_id, aid, sid, cid): return (int(aid), int(sid), int(cid)) case (unique_id, aid, sid): return (int(aid), int(sid), None) case (unique_id, aid): return (int(aid), None, None) except ValueError: # One of the int conversions failed - this can't be a valid homekit_controller unique id # Fall through and return None pass return None
Return a name that is used for matching a similar string.
def folded_name(name: str) -> str: """Return a name that is used for matching a similar string.""" return name.casefold().replace(" ", "")
Set up the HomeMatic binary sensor platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the HomeMatic binary sensor platform.""" if discovery_info is None: return devices: list[BinarySensorEntity] = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: if discovery_info[ATTR_DISCOVERY_TYPE] == DISCOVER_BATTERY: devices.append(HMBatterySensor(conf)) else: devices.append(HMBinarySensor(conf)) add_entities(devices, True)
Set up the Homematic thermostat platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Homematic thermostat platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: new_device = HMThermostat(conf) devices.append(new_device) add_entities(devices, True)
Set up the platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the platform.""" if discovery_info is None: return devices: list[HMCover] = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: if conf[ATTR_DEVICE_TYPE] in HM_GARAGE: devices.append(HMGarage(conf)) else: devices.append(HMCover(conf)) add_entities(devices, True)
Set up the Homematic light platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Homematic light platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: new_device = HMLight(conf) devices.append(new_device) add_entities(devices, True)
Set up the Homematic lock platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Homematic lock platform.""" if discovery_info is None: return add_entities((HMLock(conf) for conf in discovery_info[ATTR_DISCOVER_DEVICES]), True)
Get the Homematic notification service.
def get_service( hass: HomeAssistant, config: ConfigType, discovery_info: DiscoveryInfoType | None = None, ) -> HomematicNotificationService: """Get the Homematic notification service.""" data = { ATTR_ADDRESS: config[ATTR_ADDRESS], ATTR_CHANNEL: config[ATTR_CHANNEL], ATTR_PARAM: config[ATTR_PARAM], ATTR_VALUE: config[ATTR_VALUE], } if ATTR_INTERFACE in config: data[ATTR_INTERFACE] = config[ATTR_INTERFACE] return HomematicNotificationService(hass, data)
Set up the HomeMatic sensor platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the HomeMatic sensor platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: state = conf.get(ATTR_PARAM) if (entity_desc := SENSOR_DESCRIPTIONS.get(state)) is None: name = conf.get(ATTR_NAME) _LOGGER.warning( ( "Sensor (%s) entity description is missing. Sensor state (%s) needs" " to be maintained" ), name, state, ) entity_desc = copy(DEFAULT_SENSOR_DESCRIPTION) new_device = HMSensor(conf, entity_desc) devices.append(new_device) add_entities(devices, True)
Set up the HomeMatic switch platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the HomeMatic switch platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: new_device = HMSwitch(conf) devices.append(new_device) add_entities(devices, True)
Set up the Homematic component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Homematic component.""" conf = config[DOMAIN] hass.data[DATA_CONF] = remotes = {} hass.data[DATA_STORE] = set() # Create hosts-dictionary for pyhomematic for rname, rconfig in conf[CONF_INTERFACES].items(): remotes[rname] = { "ip": rconfig.get(CONF_HOST), "port": rconfig.get(CONF_PORT), "path": rconfig.get(CONF_PATH), "resolvenames": rconfig.get(CONF_RESOLVENAMES), "jsonport": rconfig.get(CONF_JSONPORT), "username": rconfig.get(CONF_USERNAME), "password": rconfig.get(CONF_PASSWORD), "callbackip": rconfig.get(CONF_CALLBACK_IP), "callbackport": rconfig.get(CONF_CALLBACK_PORT), "ssl": rconfig[CONF_SSL], "verify_ssl": rconfig.get(CONF_VERIFY_SSL), "connect": True, } for sname, sconfig in conf[CONF_HOSTS].items(): remotes[sname] = { "ip": sconfig.get(CONF_HOST), "port": sconfig[CONF_PORT], "username": sconfig.get(CONF_USERNAME), "password": sconfig.get(CONF_PASSWORD), "connect": False, } # Create server thread bound_system_callback = partial(_system_callback_handler, hass, config) hass.data[DATA_HOMEMATIC] = homematic = HMConnection( local=config[DOMAIN].get(CONF_LOCAL_IP), localport=config[DOMAIN].get(CONF_LOCAL_PORT, DEFAULT_LOCAL_PORT), remotes=remotes, systemcallback=bound_system_callback, interface_id="homeassistant", ) # Start server thread, connect to hosts, initialize to receive events homematic.start() # Stops server when Home Assistant is shutting down hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, hass.data[DATA_HOMEMATIC].stop) # Init homematic hubs entity_hubs = [HMHub(hass, homematic, hub_name) for hub_name in conf[CONF_HOSTS]] def _hm_service_virtualkey(service: ServiceCall) -> None: """Service to handle virtualkey servicecalls.""" address = service.data.get(ATTR_ADDRESS) channel = service.data.get(ATTR_CHANNEL) param = service.data.get(ATTR_PARAM) # Device not found hmdevice = _device_from_servicecall(hass, service) if hmdevice is None: _LOGGER.error("%s not found for service virtualkey!", address) return # Parameter doesn't exist for device if param not in hmdevice.ACTIONNODE: _LOGGER.error("%s not datapoint in hm device %s", param, address) return # Channel doesn't exist for device if channel not in hmdevice.ACTIONNODE[param]: _LOGGER.error("%i is not a channel in hm device %s", channel, address) return # Call parameter hmdevice.actionNodeData(param, True, channel) hass.services.register( DOMAIN, SERVICE_VIRTUALKEY, _hm_service_virtualkey, schema=SCHEMA_SERVICE_VIRTUALKEY, ) def _service_handle_value(service: ServiceCall) -> None: """Service to call setValue method for HomeMatic system variable.""" entity_ids = service.data.get(ATTR_ENTITY_ID) name = service.data[ATTR_NAME] value = service.data[ATTR_VALUE] if entity_ids: entities = [ entity for entity in entity_hubs if entity.entity_id in entity_ids ] else: entities = entity_hubs if not entities: _LOGGER.error("No HomeMatic hubs available") return for hub in entities: hub.hm_set_variable(name, value) hass.services.register( DOMAIN, SERVICE_SET_VARIABLE_VALUE, _service_handle_value, schema=SCHEMA_SERVICE_SET_VARIABLE_VALUE, ) def _service_handle_reconnect(service: ServiceCall) -> None: """Service to reconnect all HomeMatic hubs.""" homematic.reconnect() hass.services.register( DOMAIN, SERVICE_RECONNECT, _service_handle_reconnect, schema=SCHEMA_SERVICE_RECONNECT, ) def _service_handle_device(service: ServiceCall) -> None: """Service to call setValue method for HomeMatic devices.""" address = service.data[ATTR_ADDRESS] channel = service.data[ATTR_CHANNEL] param = service.data[ATTR_PARAM] value = service.data[ATTR_VALUE] value_type = service.data.get(ATTR_VALUE_TYPE) # Convert value into correct XML-RPC Type. # https://docs.python.org/3/library/xmlrpc.client.html#xmlrpc.client.ServerProxy if value_type: if value_type == "int": value = int(value) elif value_type == "double": value = float(value) elif value_type == "boolean": value = bool(value) elif value_type == "dateTime.iso8601": value = datetime.strptime(value, "%Y%m%dT%H:%M:%S") else: # Default is 'string' value = str(value) # Device not found hmdevice = _device_from_servicecall(hass, service) if hmdevice is None: _LOGGER.error("%s not found!", address) return hmdevice.setValue(param, value, channel) hass.services.register( DOMAIN, SERVICE_SET_DEVICE_VALUE, _service_handle_device, schema=SCHEMA_SERVICE_SET_DEVICE_VALUE, ) def _service_handle_install_mode(service: ServiceCall) -> None: """Service to set interface into install mode.""" interface = service.data.get(ATTR_INTERFACE) mode = service.data.get(ATTR_MODE) time = service.data.get(ATTR_TIME) address = service.data.get(ATTR_ADDRESS) homematic.setInstallMode(interface, t=time, mode=mode, address=address) hass.services.register( DOMAIN, SERVICE_SET_INSTALL_MODE, _service_handle_install_mode, schema=SCHEMA_SERVICE_SET_INSTALL_MODE, ) def _service_put_paramset(service: ServiceCall) -> None: """Service to call the putParamset method on a HomeMatic connection.""" interface = service.data[ATTR_INTERFACE] address = service.data[ATTR_ADDRESS] paramset_key = service.data[ATTR_PARAMSET_KEY] # When passing in the paramset from a YAML file we get an OrderedDict # here instead of a dict, so add this explicit cast. # The service schema makes sure that this cast works. paramset = dict(service.data[ATTR_PARAMSET]) rx_mode = service.data.get(ATTR_RX_MODE) _LOGGER.debug( "Calling putParamset: %s, %s, %s, %s, %s", interface, address, paramset_key, paramset, rx_mode, ) homematic.putParamset(interface, address, paramset_key, paramset, rx_mode) hass.services.register( DOMAIN, SERVICE_PUT_PARAMSET, _service_put_paramset, schema=SCHEMA_SERVICE_PUT_PARAMSET, ) return True
System callback handler.
def _system_callback_handler(hass, config, src, *args): """System callback handler.""" # New devices available at hub if src == "newDevices": (interface_id, dev_descriptions) = args interface = interface_id.split("-")[-1] # Device support active? if not hass.data[DATA_CONF][interface]["connect"]: return addresses = [] for dev in dev_descriptions: address = dev["ADDRESS"].split(":")[0] if address not in hass.data[DATA_STORE]: hass.data[DATA_STORE].add(address) addresses.append(address) # Register EVENTS # Search all devices with an EVENTNODE that includes data bound_event_callback = partial(_hm_event_handler, hass, interface) for dev in addresses: hmdevice = hass.data[DATA_HOMEMATIC].devices[interface].get(dev) if hmdevice.EVENTNODE: hmdevice.setEventCallback(callback=bound_event_callback, bequeath=True) # Create Home Assistant entities if addresses: for component_name, discovery_type in ( ("switch", DISCOVER_SWITCHES), ("light", DISCOVER_LIGHTS), ("cover", DISCOVER_COVER), ("binary_sensor", DISCOVER_BINARY_SENSORS), ("sensor", DISCOVER_SENSORS), ("climate", DISCOVER_CLIMATE), ("lock", DISCOVER_LOCKS), ("binary_sensor", DISCOVER_BATTERY), ): # Get all devices of a specific type found_devices = _get_devices(hass, discovery_type, addresses, interface) # When devices of this type are found # they are setup in Home Assistant and a discovery event is fired if found_devices: discovery.load_platform( hass, component_name, DOMAIN, { ATTR_DISCOVER_DEVICES: found_devices, ATTR_DISCOVERY_TYPE: discovery_type, }, config, ) # Homegear error message elif src == "error": _LOGGER.error("Error: %s", args) (interface_id, errorcode, message) = args hass.bus.fire(EVENT_ERROR, {ATTR_ERRORCODE: errorcode, ATTR_MESSAGE: message})
Get the HomeMatic devices for given discovery_type.
def _get_devices(hass, discovery_type, keys, interface): """Get the HomeMatic devices for given discovery_type.""" device_arr = [] for key in keys: device = hass.data[DATA_HOMEMATIC].devices[interface][key] class_name = device.__class__.__name__ metadata = {} # Class not supported by discovery type if ( discovery_type != DISCOVER_BATTERY and class_name not in HM_DEVICE_TYPES[discovery_type] ): continue # Load metadata needed to generate a parameter list if discovery_type == DISCOVER_SENSORS: metadata.update(device.SENSORNODE) elif discovery_type == DISCOVER_BINARY_SENSORS: metadata.update(device.BINARYNODE) elif discovery_type == DISCOVER_BATTERY: if ATTR_LOWBAT in device.ATTRIBUTENODE: metadata.update({ATTR_LOWBAT: device.ATTRIBUTENODE[ATTR_LOWBAT]}) elif ATTR_LOW_BAT in device.ATTRIBUTENODE: metadata.update({ATTR_LOW_BAT: device.ATTRIBUTENODE[ATTR_LOW_BAT]}) else: continue else: metadata.update({None: device.ELEMENT}) # Generate options for 1...n elements with 1...n parameters for param, channels in metadata.items(): if ( param in HM_IGNORE_DISCOVERY_NODE and class_name not in HM_IGNORE_DISCOVERY_NODE_EXCEPTIONS.get(param, []) ): continue if discovery_type == DISCOVER_SWITCHES and class_name == "IPKeySwitchLevel": channels.remove(8) channels.remove(12) if discovery_type == DISCOVER_LIGHTS and class_name == "IPKeySwitchLevel": channels.remove(4) # Add devices _LOGGER.debug( "%s: Handling %s: %s: %s", discovery_type, key, param, channels ) for channel in channels: name = _create_ha_id( name=device.NAME, channel=channel, param=param, count=len(channels) ) unique_id = _create_ha_id( name=key, channel=channel, param=param, count=len(channels) ) device_dict = { CONF_PLATFORM: "homematic", ATTR_ADDRESS: key, ATTR_INTERFACE: interface, ATTR_NAME: name, ATTR_DEVICE_TYPE: class_name, ATTR_CHANNEL: channel, ATTR_UNIQUE_ID: unique_id, } if param is not None: device_dict[ATTR_PARAM] = param # Add new device try: DEVICE_SCHEMA(device_dict) device_arr.append(device_dict) except vol.MultipleInvalid as err: _LOGGER.error("Invalid device config: %s", str(err)) return device_arr
Generate a unique entity id.
def _create_ha_id(name, channel, param, count): """Generate a unique entity id.""" # HMDevice is a simple device if count == 1 and param is None: return name # Has multiple elements/channels if count > 1 and param is None: return f"{name} {channel}" # With multiple parameters on first channel if count == 1 and param is not None: return f"{name} {param}" # Multiple parameters with multiple channels if count > 1 and param is not None: return f"{name} {channel} {param}"
Handle all pyhomematic device events.
def _hm_event_handler(hass, interface, device, caller, attribute, value): """Handle all pyhomematic device events.""" try: channel = int(device.split(":")[1]) address = device.split(":")[0] hmdevice = hass.data[DATA_HOMEMATIC].devices[interface].get(address) except (TypeError, ValueError): _LOGGER.error("Event handling channel convert error!") return # Return if not an event supported by device if attribute not in hmdevice.EVENTNODE: return _LOGGER.debug("Event %s for %s channel %i", attribute, hmdevice.NAME, channel) # Keypress event if attribute in HM_PRESS_EVENTS: hass.bus.fire( EVENT_KEYPRESS, {ATTR_NAME: hmdevice.NAME, ATTR_PARAM: attribute, ATTR_CHANNEL: channel}, ) return # Impulse event if attribute in HM_IMPULSE_EVENTS: hass.bus.fire(EVENT_IMPULSE, {ATTR_NAME: hmdevice.NAME, ATTR_CHANNEL: channel}) return _LOGGER.warning("Event is unknown and not forwarded")
Extract HomeMatic device from service call.
def _device_from_servicecall(hass, service): """Extract HomeMatic device from service call.""" address = service.data.get(ATTR_ADDRESS) interface = service.data.get(ATTR_INTERFACE) if address == "BIDCOS-RF": address = "BidCoS-RF" if address == "HMIP-RCV-1": address = "HmIP-RCV-1" if interface: return hass.data[DATA_HOMEMATIC].devices[interface].get(address) for devices in hass.data[DATA_HOMEMATIC].devices.values(): if address in devices: return devices[address]
Response from async call contains errors or not.
def is_error_response(response: Any) -> TypeGuard[dict[str, Any]]: """Response from async call contains errors or not.""" if isinstance(response, dict): return response.get("errorCode") not in ("", None) return False
Handle async errors.
def handle_errors( func: Callable[ Concatenate[_HomematicipGenericEntityT, _P], Coroutine[Any, Any, Any] ], ) -> Callable[Concatenate[_HomematicipGenericEntityT, _P], Coroutine[Any, Any, Any]]: """Handle async errors.""" @wraps(func) async def inner( self: _HomematicipGenericEntityT, *args: _P.args, **kwargs: _P.kwargs ) -> None: """Handle errors from async call.""" result = await func(self, *args, **kwargs) if is_error_response(result): _LOGGER.error( "Error while execute function %s: %s", __name__, json.dumps(result), ) raise HomeAssistantError( f"Error while execute function {func.__name__}: {result.get('errorCode')}. See log for more information." ) return inner
Convert the given color to the reduced RGBColorState color. RGBColorStat contains only 8 colors including white and black, so a conversion is required.
def _convert_color(color: tuple) -> RGBColorState: """Convert the given color to the reduced RGBColorState color. RGBColorStat contains only 8 colors including white and black, so a conversion is required. """ if color is None: return RGBColorState.WHITE hue = int(color[0]) saturation = int(color[1]) if saturation < 5: return RGBColorState.WHITE if 30 < hue <= 90: return RGBColorState.YELLOW if 90 < hue <= 160: return RGBColorState.GREEN if 150 < hue <= 210: return RGBColorState.TURQUOISE if 210 < hue <= 270: return RGBColorState.BLUE if 270 < hue <= 330: return RGBColorState.PURPLE return RGBColorState.RED
Convert wind direction degree to named direction.
def _get_wind_direction(wind_direction_degree: float) -> str: """Convert wind direction degree to named direction.""" if 11.25 <= wind_direction_degree < 33.75: return "NNE" if 33.75 <= wind_direction_degree < 56.25: return "NE" if 56.25 <= wind_direction_degree < 78.75: return "ENE" if 78.75 <= wind_direction_degree < 101.25: return "E" if 101.25 <= wind_direction_degree < 123.75: return "ESE" if 123.75 <= wind_direction_degree < 146.25: return "SE" if 146.25 <= wind_direction_degree < 168.75: return "SSE" if 168.75 <= wind_direction_degree < 191.25: return "S" if 191.25 <= wind_direction_degree < 213.75: return "SSW" if 213.75 <= wind_direction_degree < 236.25: return "SW" if 236.25 <= wind_direction_degree < 258.75: return "WSW" if 258.75 <= wind_direction_degree < 281.25: return "W" if 281.25 <= wind_direction_degree < 303.75: return "WNW" if 303.75 <= wind_direction_degree < 326.25: return "NW" if 326.25 <= wind_direction_degree < 348.75: return "NNW" return "N"
Return a HmIP home.
def _get_home(hass: HomeAssistant, hapid: str) -> AsyncHome | None: """Return a HmIP home.""" if hap := hass.data[HMIPC_DOMAIN].get(hapid): return hap.home _LOGGER.info("No matching access point found for access point id %s", hapid) return None
Remove obsolete entities from entity registry.
def _async_remove_obsolete_entities( hass: HomeAssistant, entry: ConfigEntry, hap: HomematicipHAP ): """Remove obsolete entities from entity registry.""" if hap.home.currentAPVersion < "2.2.12": return entity_registry = er.async_get(hass) er_entries = async_entries_for_config_entry(entity_registry, entry.entry_id) for er_entry in er_entries: if er_entry.unique_id.startswith("HomematicipAccesspointStatus"): entity_registry.async_remove(er_entry.entity_id) continue for hapid in hap.home.accessPointUpdateStates: if er_entry.unique_id == f"HomematicipBatterySensor_{hapid}": entity_registry.async_remove(er_entry.entity_id)
Decorate HomeWizard Energy calls to handle HomeWizardEnergy exceptions. A decorator that wraps the passed in function, catches HomeWizardEnergy errors, and reloads the integration when the API was disabled so the reauth flow is triggered.
def homewizard_exception_handler( func: Callable[Concatenate[_HomeWizardEntityT, _P], Coroutine[Any, Any, Any]], ) -> Callable[Concatenate[_HomeWizardEntityT, _P], Coroutine[Any, Any, None]]: """Decorate HomeWizard Energy calls to handle HomeWizardEnergy exceptions. A decorator that wraps the passed in function, catches HomeWizardEnergy errors, and reloads the integration when the API was disabled so the reauth flow is triggered. """ async def handler( self: _HomeWizardEntityT, *args: _P.args, **kwargs: _P.kwargs ) -> None: try: await func(self, *args, **kwargs) except RequestError as ex: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", ) from ex except DisabledError as ex: await self.hass.config_entries.async_reload( self.coordinator.config_entry.entry_id ) raise HomeAssistantError( translation_domain=DOMAIN, translation_key="api_disabled", ) from ex return handler
Convert 0..1 value to percentage when value is not None.
def to_percentage(value: float | None) -> float | None: """Convert 0..1 value to percentage when value is not None.""" return value * 100 if value is not None else None
Create a repair issue asking the user to remove YAML.
def _create_import_issue(hass: HomeAssistant) -> None: """Create a repair issue asking the user to remove YAML.""" ir.async_create_issue( hass, HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}", breaks_in_ha_version="2024.6.0", is_fixable=False, issue_domain=DOMAIN, severity=ir.IssueSeverity.WARNING, translation_key="deprecated_yaml", translation_placeholders={ "domain": DOMAIN, "integration_title": "Lutron Homeworks", }, )
Validate address.
def _validate_address(handler: SchemaCommonFlowHandler, addr: str) -> None: """Validate address.""" try: validate_addr(addr) except vol.Invalid as err: raise SchemaFlowError("invalid_addr") from err for _key in (CONF_DIMMERS, CONF_KEYPADS): items: list[dict[str, Any]] = handler.options[_key] for item in items: if item[CONF_ADDR] == addr: raise SchemaFlowError("duplicated_addr")
Validate button number.
def _validate_button_number(handler: SchemaCommonFlowHandler, number: int) -> None: """Validate button number.""" keypad = handler.flow_state["_idx"] buttons: list[dict[str, Any]] = handler.options[CONF_KEYPADS][keypad][CONF_BUTTONS] for button in buttons: if button[CONF_NUMBER] == number: raise SchemaFlowError("duplicated_number")
Set up services for Lutron Homeworks Series 4 and 8 integration.
def async_setup_services(hass: HomeAssistant) -> None: """Set up services for Lutron Homeworks Series 4 and 8 integration.""" async def async_call_service(service_call: ServiceCall) -> None: """Call the service.""" await async_send_command(hass, service_call.data) hass.services.async_register( DOMAIN, "send_command", async_call_service, schema=SERVICE_SEND_COMMAND_SCHEMA, )
Calculate entity unique id.
def calculate_unique_id(controller_id: str, addr: str, idx: int) -> str: """Calculate entity unique id.""" return f"homeworks.{controller_id}.{addr}.{idx}"
Return a Home Connect appliance instance given an device_id.
def _get_appliance_by_device_id( hass: HomeAssistant, device_id: str ) -> api.HomeConnectDevice: """Return a Home Connect appliance instance given an device_id.""" for hc_api in hass.data[DOMAIN].values(): for dev_dict in hc_api.devices: device = dev_dict[CONF_DEVICE] if device.device_id == device_id: return device.appliance raise ValueError(f"Appliance for device id {device_id} not found")
Remove stale devices from device registry.
def remove_stale_devices( hass: HomeAssistant, config_entry: ConfigEntry, devices: dict[str, SomeComfortDevice], ) -> None: """Remove stale devices from device registry.""" device_registry = dr.async_get(hass) device_entries = dr.async_entries_for_config_entry( device_registry, config_entry.entry_id ) all_device_ids = {device.deviceid for device in devices.values()} for device_entry in device_entries: device_id: str | None = None for identifier in device_entry.identifiers: if identifier[0] == DOMAIN: device_id = identifier[1] break if device_id is None or device_id not in all_device_ids: # If device_id is None an invalid device entry was found for this config entry. # If the device_id is not in existing device ids it's a stale device entry. # Remove config entry from this device entry in either case. device_registry.async_update_device( device_entry.id, remove_config_entry_id=config_entry.entry_id )
Get the correct temperature unit for the device.
def _get_temperature_sensor_unit(device: Device) -> str: """Get the correct temperature unit for the device.""" if device.temperature_unit == "C": return UnitOfTemperature.CELSIUS return UnitOfTemperature.FAHRENHEIT
Set up the Horizon platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Horizon platform.""" host = config[CONF_HOST] name = config[CONF_NAME] port = config[CONF_PORT] try: client = Client(host, port=port) except AuthenticationError as msg: _LOGGER.error("Authentication to %s at %s failed: %s", name, host, msg) return except OSError as msg: # occurs if horizon box is offline _LOGGER.error("Connection to %s at %s failed: %s", name, host, msg) raise PlatformNotReady from msg _LOGGER.info("Connection to %s at %s established", name, host) add_entities([HorizonDevice(client, name, keys)], True)
Set up the HP iLO sensors.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the HP iLO sensors.""" hostname = config[CONF_HOST] port = config[CONF_PORT] login = config[CONF_USERNAME] password = config[CONF_PASSWORD] monitored_variables = config[CONF_MONITORED_VARIABLES] # Create a data fetcher to support all of the configured sensors. Then make # the first call to init the data and confirm we can connect. try: hp_ilo_data = HpIloData(hostname, port, login, password) except ValueError as error: _LOGGER.error(error) return # Initialize and add all of the sensors. devices = [] for monitored_variable in monitored_variables: new_device = HpIloSensor( hass=hass, hp_ilo_data=hp_ilo_data, sensor_name=f"{config[CONF_NAME]} {monitored_variable[CONF_NAME]}", sensor_type=monitored_variable[CONF_SENSOR_TYPE], sensor_value_template=monitored_variable.get(CONF_VALUE_TEMPLATE), unit_of_measurement=monitored_variable.get(CONF_UNIT_OF_MEASUREMENT), ) devices.append(new_device) add_entities(devices, True)
Warn user that GCM API config is deprecated.
def gcm_api_deprecated(value): """Warn user that GCM API config is deprecated.""" if value: _LOGGER.warning( "Configuring html5_push_notifications via the GCM api" " has been deprecated and stopped working since May 29," " 2019. Use the VAPID configuration instead. For instructions," " see https://www.home-assistant.io/integrations/html5/" ) return value
Load configuration.
def _load_config(filename: str) -> JsonObjectType: """Load configuration.""" with suppress(HomeAssistantError): return load_json_object(filename) return {}
Create JWT json to put into payload.
def add_jwt(timestamp, target, tag, jwt_secret): """Create JWT json to put into payload.""" jwt_exp = datetime.fromtimestamp(timestamp) + timedelta(days=JWT_VALID_DAYS) jwt_claims = { "exp": jwt_exp, "nbf": timestamp, "iat": timestamp, ATTR_TARGET: target, ATTR_TAG: tag, } return jwt.encode(jwt_claims, jwt_secret)
Sign a path for temporary access without auth header.
def async_sign_path( hass: HomeAssistant, path: str, expiration: timedelta, *, refresh_token_id: str | None = None, use_content_user: bool = False, ) -> str: """Sign a path for temporary access without auth header.""" if (secret := hass.data.get(DATA_SIGN_SECRET)) is None: secret = hass.data[DATA_SIGN_SECRET] = secrets.token_hex() if refresh_token_id is None: if use_content_user: refresh_token_id = hass.data[STORAGE_KEY] elif connection := websocket_api.current_connection.get(): refresh_token_id = connection.refresh_token_id elif ( request := current_request.get() ) and KEY_HASS_REFRESH_TOKEN_ID in request: refresh_token_id = request[KEY_HASS_REFRESH_TOKEN_ID] else: refresh_token_id = hass.data[STORAGE_KEY] url = URL(path) now_timestamp = int(time.time()) expiration_timestamp = now_timestamp + int(expiration.total_seconds()) params = [itm for itm in url.query.items() if itm[0] not in SAFE_QUERY_PARAMS] json_payload = json_bytes( { "iss": refresh_token_id, "path": url.path, "params": params, "iat": now_timestamp, "exp": expiration_timestamp, } ) encoded = api_jws.encode(json_payload, secret, "HS256") params.append((SIGN_QUERY_PARAM, encoded)) url = url.with_query(params) return f"{url.path}?{url.query_string}"
Validate that user is not allowed to do auth things.
def async_user_not_allowed_do_auth( hass: HomeAssistant, user: User, request: Request | None = None ) -> str | None: """Validate that user is not allowed to do auth things.""" if not user.is_active: return "User is not active" if not user.local_only: return None # User is marked as local only, check if they are allowed to do auth if request is None: request = current_request.get() if not request: return "No request available to validate local access" if is_cloud_connection(hass): return "User is local only" try: remote_address = ip_address(request.remote) # type: ignore[arg-type] except ValueError: return "Invalid remote IP" if is_local(remote_address): return None return "User cannot authenticate remotely"
Create IP Ban middleware for the app.
def setup_bans(hass: HomeAssistant, app: Application, login_threshold: int) -> None: """Create IP Ban middleware for the app.""" app.middlewares.append(ban_middleware) app[KEY_FAILED_LOGIN_ATTEMPTS] = defaultdict[IPv4Address | IPv6Address, int](int) app[KEY_LOGIN_THRESHOLD] = login_threshold app[KEY_BAN_MANAGER] = IpBanManager(hass) async def ban_startup(app: Application) -> None: """Initialize bans when app starts up.""" await app[KEY_BAN_MANAGER].async_load() app.on_startup.append(ban_startup)
Decorate function to handle invalid auth or failed login attempts.
def log_invalid_auth( func: Callable[Concatenate[_HassViewT, Request, _P], Awaitable[Response]], ) -> Callable[Concatenate[_HassViewT, Request, _P], Coroutine[Any, Any, Response]]: """Decorate function to handle invalid auth or failed login attempts.""" async def handle_req( view: _HassViewT, request: Request, *args: _P.args, **kwargs: _P.kwargs ) -> Response: """Try to log failed login attempts if response status >= BAD_REQUEST.""" resp = await func(view, request, *args, **kwargs) if resp.status >= HTTPStatus.BAD_REQUEST: await process_wrong_login(request) return resp return handle_req
Process a success login attempt. Reset failed login attempts counter for remote IP address. No release IP address from banned list function, it can only be done by manual modify ip bans config file.
def process_success_login(request: Request) -> None: """Process a success login attempt. Reset failed login attempts counter for remote IP address. No release IP address from banned list function, it can only be done by manual modify ip bans config file. """ app = request.app # Check if ban middleware is loaded if KEY_BAN_MANAGER not in app or app[KEY_LOGIN_THRESHOLD] < 1: return remote_addr = ip_address(request.remote) # type: ignore[arg-type] login_attempt_history = app[KEY_FAILED_LOGIN_ATTEMPTS] if remote_addr in login_attempt_history and login_attempt_history[remote_addr] > 0: _LOGGER.debug( "Login success, reset failed login attempts counter from %s", remote_addr ) login_attempt_history.pop(remote_addr)
Set up CORS.
def setup_cors(app: Application, origins: list[str]) -> None: """Set up CORS.""" cors = aiohttp_cors.setup( app, defaults={ host: aiohttp_cors.ResourceOptions( allow_headers=ALLOWED_CORS_HEADERS, allow_methods="*" ) for host in origins }, ) cors_added = set() def _allow_cors( route: AbstractRoute | AbstractResource, config: dict[str, aiohttp_cors.ResourceOptions] | None = None, ) -> None: """Allow CORS on a route.""" if isinstance(route, AbstractRoute): path = route.resource else: path = route if not isinstance(path, VALID_CORS_TYPES): return path_str = path.canonical if path_str.startswith("/api/hassio_ingress/"): return if path_str in cors_added: return cors.add(route, config) cors_added.add(path_str) app[KEY_ALLOW_ALL_CORS] = lambda route: _allow_cors( route, { "*": aiohttp_cors.ResourceOptions( allow_headers=ALLOWED_CORS_HEADERS, allow_methods="*" ) }, ) if origins: app[KEY_ALLOW_CONFIGRED_CORS] = cast(AllowCorsType, _allow_cors) else: app[KEY_ALLOW_CONFIGRED_CORS] = lambda _: None
Home Assistant API decorator to require user to be an admin.
def require_admin( _func: _FuncType[_HomeAssistantViewT, _P, _ResponseT] | None = None, *, error: Unauthorized | None = None, ) -> ( Callable[ [_FuncType[_HomeAssistantViewT, _P, _ResponseT]], _FuncType[_HomeAssistantViewT, _P, _ResponseT], ] | _FuncType[_HomeAssistantViewT, _P, _ResponseT] ): """Home Assistant API decorator to require user to be an admin.""" def decorator_require_admin( func: _FuncType[_HomeAssistantViewT, _P, _ResponseT], ) -> _FuncType[_HomeAssistantViewT, _P, _ResponseT]: """Wrap the provided with_admin function.""" @wraps(func) async def with_admin( self: _HomeAssistantViewT, request: Request, *args: _P.args, **kwargs: _P.kwargs, ) -> _ResponseT: """Check admin and call function.""" user: User = request["hass_user"] if not user.is_admin: raise error or Unauthorized() return await func(self, request, *args, **kwargs) return with_admin # See if we're being called as @require_admin or @require_admin(). if _func is None: # We're called with brackets. return decorator_require_admin # We're called as @require_admin without brackets. return decorator_require_admin(_func)
Create forwarded middleware for the app. Process IP addresses, proto and host information in the forwarded for headers. `X-Forwarded-For: <client>, <proxy1>, <proxy2>` e.g., `X-Forwarded-For: 203.0.113.195, 70.41.3.18, 150.172.238.178` We go through the list from the right side, and skip all entries that are in our trusted proxies list. The first non-trusted IP is used as the client IP. If all items in the X-Forwarded-For are trusted, including the most left item (client), the most left item is used. In the latter case, the client connection originated from an IP that is also listed as a trusted proxy IP or network. `X-Forwarded-Proto: <client>, <proxy1>, <proxy2>` e.g., `X-Forwarded-Proto: https, http, http` OR `X-Forwarded-Proto: https` (one entry, even with multiple proxies) The X-Forwarded-Proto is determined based on the corresponding entry of the X-Forwarded-For header that is used/chosen as the client IP. However, some proxies, for example, Kubernetes NGINX ingress, only retain one element in the X-Forwarded-Proto header. In that case, we'll just use what we have. `X-Forwarded-Host: <host>` e.g., `X-Forwarded-Host: example.com` If the previous headers are processed successfully, and the X-Forwarded-Host is present, it will be used. Additionally: - If no X-Forwarded-For header is found, the processing of all headers is skipped. - Throw HTTP 400 status when untrusted connected peer provides X-Forwarded-For headers. - If multiple instances of X-Forwarded-For, X-Forwarded-Proto or X-Forwarded-Host are found, an HTTP 400 status code is thrown. - If malformed or invalid (IP) data in X-Forwarded-For header is found, an HTTP 400 status code is thrown. - The connected client peer on the socket of the incoming connection, must be trusted for any processing to take place. - If the number of elements in X-Forwarded-Proto does not equal 1 or is equal to the number of elements in X-Forwarded-For, an HTTP 400 status code is thrown. - If an empty X-Forwarded-Host is provided, an HTTP 400 status code is thrown. - If an empty X-Forwarded-Proto is provided, or an empty element in the list, an HTTP 400 status code is thrown.
def async_setup_forwarded( app: Application, use_x_forwarded_for: bool | None, trusted_proxies: list[IPv4Network | IPv6Network], ) -> None: """Create forwarded middleware for the app. Process IP addresses, proto and host information in the forwarded for headers. `X-Forwarded-For: <client>, <proxy1>, <proxy2>` e.g., `X-Forwarded-For: 203.0.113.195, 70.41.3.18, 150.172.238.178` We go through the list from the right side, and skip all entries that are in our trusted proxies list. The first non-trusted IP is used as the client IP. If all items in the X-Forwarded-For are trusted, including the most left item (client), the most left item is used. In the latter case, the client connection originated from an IP that is also listed as a trusted proxy IP or network. `X-Forwarded-Proto: <client>, <proxy1>, <proxy2>` e.g., `X-Forwarded-Proto: https, http, http` OR `X-Forwarded-Proto: https` (one entry, even with multiple proxies) The X-Forwarded-Proto is determined based on the corresponding entry of the X-Forwarded-For header that is used/chosen as the client IP. However, some proxies, for example, Kubernetes NGINX ingress, only retain one element in the X-Forwarded-Proto header. In that case, we'll just use what we have. `X-Forwarded-Host: <host>` e.g., `X-Forwarded-Host: example.com` If the previous headers are processed successfully, and the X-Forwarded-Host is present, it will be used. Additionally: - If no X-Forwarded-For header is found, the processing of all headers is skipped. - Throw HTTP 400 status when untrusted connected peer provides X-Forwarded-For headers. - If multiple instances of X-Forwarded-For, X-Forwarded-Proto or X-Forwarded-Host are found, an HTTP 400 status code is thrown. - If malformed or invalid (IP) data in X-Forwarded-For header is found, an HTTP 400 status code is thrown. - The connected client peer on the socket of the incoming connection, must be trusted for any processing to take place. - If the number of elements in X-Forwarded-Proto does not equal 1 or is equal to the number of elements in X-Forwarded-For, an HTTP 400 status code is thrown. - If an empty X-Forwarded-Host is provided, an HTTP 400 status code is thrown. - If an empty X-Forwarded-Proto is provided, or an empty element in the list, an HTTP 400 status code is thrown. """ @middleware async def forwarded_middleware( request: Request, handler: Callable[[Request], Awaitable[StreamResponse]] ) -> StreamResponse: """Process forwarded data by a reverse proxy.""" # Skip requests from Remote UI if remote.is_cloud_request.get(): return await handler(request) # Handle X-Forwarded-For forwarded_for_headers: list[str] = request.headers.getall(X_FORWARDED_FOR, []) if not forwarded_for_headers: # No forwarding headers, continue as normal return await handler(request) # Get connected IP if ( request.transport is None or request.transport.get_extra_info("peername") is None ): # Connected IP isn't retrieveable from the request transport, continue return await handler(request) connected_ip = ip_address(request.transport.get_extra_info("peername")[0]) # We have X-Forwarded-For, but config does not agree if not use_x_forwarded_for: _LOGGER.error( ( "A request from a reverse proxy was received from %s, but your " "HTTP integration is not set-up for reverse proxies" ), connected_ip, ) raise HTTPBadRequest # Ensure the IP of the connected peer is trusted if not any(connected_ip in trusted_proxy for trusted_proxy in trusted_proxies): _LOGGER.error( "Received X-Forwarded-For header from an untrusted proxy %s", connected_ip, ) raise HTTPBadRequest # Multiple X-Forwarded-For headers if len(forwarded_for_headers) > 1: _LOGGER.error( "Too many headers for X-Forwarded-For: %s", forwarded_for_headers ) raise HTTPBadRequest # Process X-Forwarded-For from the right side (by reversing the list) forwarded_for_split = list(reversed(forwarded_for_headers[0].split(","))) try: forwarded_for = [ip_address(addr.strip()) for addr in forwarded_for_split] except ValueError as err: _LOGGER.error( "Invalid IP address in X-Forwarded-For: %s", forwarded_for_headers[0] ) raise HTTPBadRequest from err overrides: dict[str, str] = {} # Find the last trusted index in the X-Forwarded-For list forwarded_for_index = 0 for forwarded_ip in forwarded_for: if any(forwarded_ip in trusted_proxy for trusted_proxy in trusted_proxies): forwarded_for_index += 1 continue overrides["remote"] = str(forwarded_ip) break else: # If all the IP addresses are from trusted networks, take the left-most. forwarded_for_index = -1 overrides["remote"] = str(forwarded_for[-1]) # Handle X-Forwarded-Proto forwarded_proto_headers: list[str] = request.headers.getall( X_FORWARDED_PROTO, [] ) if forwarded_proto_headers: if len(forwarded_proto_headers) > 1: _LOGGER.error( "Too many headers for X-Forward-Proto: %s", forwarded_proto_headers ) raise HTTPBadRequest forwarded_proto_split = list( reversed(forwarded_proto_headers[0].split(",")) ) forwarded_proto = [proto.strip() for proto in forwarded_proto_split] # Catch empty values if "" in forwarded_proto: _LOGGER.error( "Empty item received in X-Forward-Proto header: %s", forwarded_proto_headers[0], ) raise HTTPBadRequest # The X-Forwarded-Proto contains either one element, or the equals number # of elements as X-Forwarded-For if len(forwarded_proto) not in (1, len(forwarded_for)): _LOGGER.error( ( "Incorrect number of elements in X-Forward-Proto. Expected 1 or" " %d, got %d: %s" ), len(forwarded_for), len(forwarded_proto), forwarded_proto_headers[0], ) raise HTTPBadRequest # Ideally this should take the scheme corresponding to the entry # in X-Forwarded-For that was chosen, but some proxies only retain # one element. In that case, use what we have. overrides["scheme"] = forwarded_proto[-1] if len(forwarded_proto) != 1: overrides["scheme"] = forwarded_proto[forwarded_for_index] # Handle X-Forwarded-Host forwarded_host_headers: list[str] = request.headers.getall(X_FORWARDED_HOST, []) if forwarded_host_headers: # Multiple X-Forwarded-Host headers if len(forwarded_host_headers) > 1: _LOGGER.error( "Too many headers for X-Forwarded-Host: %s", forwarded_host_headers ) raise HTTPBadRequest forwarded_host = forwarded_host_headers[0].strip() if not forwarded_host: _LOGGER.error("Empty value received in X-Forward-Host header") raise HTTPBadRequest overrides["host"] = forwarded_host # Done, create a new request based on gathered data. request = request.clone(**overrides) # type: ignore[arg-type] return await handler(request) app.middlewares.append(forwarded_middleware)
Create headers middleware for the app.
def setup_headers(app: Application, use_x_frame_options: bool) -> None: """Create headers middleware for the app.""" added_headers = { "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff", "Server": "", # Empty server header, to prevent aiohttp of setting one. } if use_x_frame_options: added_headers["X-Frame-Options"] = "SAMEORIGIN" @middleware async def headers_middleware( request: Request, handler: Callable[[Request], Awaitable[StreamResponse]] ) -> StreamResponse: """Process request and add headers to the responses.""" try: response = await handler(request) except HTTPException as err: for key, value in added_headers.items(): err.headers[key] = value raise for key, value in added_headers.items(): response.headers[key] = value return response app.middlewares.append(headers_middleware)
Create request context middleware for the app.
def setup_request_context( app: Application, context: ContextVar[Request | None] ) -> None: """Create request context middleware for the app.""" @middleware async def request_context_middleware( request: Request, handler: Callable[[Request], Awaitable[StreamResponse]] ) -> StreamResponse: """Request context middleware.""" context.set(request) return await handler(request) app.middlewares.append(request_context_middleware)
Create security filter middleware for the app.
def setup_security_filter(app: Application) -> None: """Create security filter middleware for the app.""" @lru_cache def _recursive_unquote(value: str) -> str: """Handle values that are encoded multiple times.""" if (unquoted := unquote(value)) != value: unquoted = _recursive_unquote(unquoted) return unquoted @middleware async def security_filter_middleware( request: Request, handler: Callable[[Request], Awaitable[StreamResponse]] ) -> StreamResponse: """Process request and block commonly known exploit attempts.""" path_with_query_string = f"{request.path}?{request.query_string}" for unsafe_byte in UNSAFE_URL_BYTES: if unsafe_byte in path_with_query_string: if unsafe_byte in request.query_string: _LOGGER.warning( "Filtered a request with unsafe byte query string: %s", request.raw_path, ) raise HTTPBadRequest _LOGGER.warning( "Filtered a request with an unsafe byte in path: %s", request.raw_path, ) raise HTTPBadRequest if FILTERS.search(_recursive_unquote(path_with_query_string)): # Check the full path with query string first, if its # a hit, than check just the query string to give a more # specific warning. if FILTERS.search(_recursive_unquote(request.query_string)): _LOGGER.warning( "Filtered a request with a potential harmful query string: %s", request.raw_path, ) raise HTTPBadRequest _LOGGER.warning( "Filtered a potential harmful request to: %s", request.raw_path ) raise HTTPBadRequest return await handler(request) app.middlewares.append(security_filter_middleware)
Return the cookie name.
def _get_cookie_name(is_secure: bool) -> str: """Return the cookie name.""" return PREFIXED_COOKIE_NAME if is_secure else COOKIE_NAME
Return the path to file on disk or None.
def _get_file_path(rel_url: str, directory: Path) -> Path | None: """Return the path to file on disk or None.""" filename = Path(rel_url) if filename.anchor: # rel_url is an absolute name like # /static/\\machine_name\c$ or /static/D:\path # where the static dir is totally different raise HTTPForbidden filepath: Path = directory.joinpath(filename).resolve() filepath.relative_to(directory) # on opening a dir, load its contents if allowed if filepath.is_dir(): return None if filepath.is_file(): return filepath raise FileNotFoundError
Set up services for HTTP component.
def _setup_services(hass: HomeAssistant, conf: ConfData) -> None: """Set up services for HTTP component.""" async def create_temporary_strict_connection_url( call: ServiceCall, ) -> ServiceResponse: """Create a strict connection url and return it.""" # Copied form homeassistant/helpers/service.py#_async_admin_handler # as the helper supports no responses yet if call.context.user_id: user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser(context=call.context) if not user.is_admin: raise Unauthorized(context=call.context) if conf[CONF_STRICT_CONNECTION] is StrictConnectionMode.DISABLED: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="strict_connection_not_enabled_non_cloud", ) try: url = get_url( hass, prefer_external=True, allow_internal=False, allow_cloud=False ) except NoURLAvailableError as ex: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="no_external_url_available", ) from ex # to avoid circular import # pylint: disable-next=import-outside-toplevel from homeassistant.components.auth import STRICT_CONNECTION_URL path = async_sign_path( hass, STRICT_CONNECTION_URL, datetime.timedelta(hours=1), use_content_user=True, ) url = urljoin(url, path) return { "url": f"https://login.home-assistant.io?u={quote_plus(url)}", "direct_url": url, } hass.services.async_register( DOMAIN, "create_temporary_strict_connection_url", create_temporary_strict_connection_url, supports_response=SupportsResponse.ONLY, )
Try to determine if the host entry is us, the HA instance.
def _is_us(host: _HostType) -> bool: """Try to determine if the host entry is us, the HA instance.""" # LAN host info entries have an "isLocalDevice" property, "1" / "0"; WLAN host list ones don't. return cast(str, host.get("isLocalDevice", "0")) == "1"
Add new entities that are not already being tracked.
def async_add_new_entities( router: Router, async_add_entities: AddEntitiesCallback, tracked: set[str], ) -> None: """Add new entities that are not already being tracked.""" if not (hosts := _get_hosts(router)): return track_wired_clients = router.config_entry.options.get( CONF_TRACK_WIRED_CLIENTS, DEFAULT_TRACK_WIRED_CLIENTS ) new_entities: list[Entity] = [] for host in ( x for x in hosts if not _is_us(x) and _is_connected(x) and x.get("MacAddress") and (track_wired_clients or _is_wireless(x)) ): entity = HuaweiLteScannerEntity(router, host["MacAddress"]) if entity.unique_id in tracked: continue tracked.add(entity.unique_id) new_entities.append(entity) async_add_entities(new_entities, True)
Format value.
def format_default(value: StateType) -> tuple[StateType, str | None]: """Format value.""" unit = None if value is not None: # Clean up value and infer unit, e.g. -71dBm, 15 dB if match := re.match( r"([>=<]*)(?P<value>.+?)\s*(?P<unit>[a-zA-Z]+)\s*$", str(value) ): try: value = float(match.group("value")) unit = match.group("unit") except ValueError: pass return value, unit
Format a frequency value for which source is in tenths of MHz.
def format_freq_mhz(value: StateType) -> tuple[StateType, UnitOfFrequency]: """Format a frequency value for which source is in tenths of MHz.""" return ( float(value) / 10 if value is not None else None, UnitOfFrequency.MEGAHERTZ, )
Convert elapsed seconds to last reset datetime.
def format_last_reset_elapsed_seconds(value: str | None) -> datetime | None: """Convert elapsed seconds to last reset datetime.""" if value is None: return None try: last_reset = datetime.now() - timedelta(seconds=int(value)) last_reset.replace(microsecond=0) except ValueError: return None return last_reset
Get signal icon.
def signal_icon(limits: Sequence[int], value: StateType) -> str: """Get signal icon.""" return ( "mdi:signal-cellular-outline", "mdi:signal-cellular-1", "mdi:signal-cellular-2", "mdi:signal-cellular-3", )[bisect(limits, value if value is not None else -1000)]
Get bandwidth icon.
def bandwidth_icon(limits: Sequence[int], value: StateType) -> str: """Get bandwidth icon.""" return ( "mdi:speedometer-slow", "mdi:speedometer-medium", "mdi:speedometer", )[bisect(limits, value if value is not None else -1000)]
Get list of device MAC addresses. :param device_info: the device.information structure for the device :param wlan_settings: the wlan.multi_basic_settings structure for the device
def get_device_macs( device_info: GetResponseType, wlan_settings: GetResponseType ) -> list[str]: """Get list of device MAC addresses. :param device_info: the device.information structure for the device :param wlan_settings: the wlan.multi_basic_settings structure for the device """ macs = [ device_info.get(x) for x in ("MacAddress1", "MacAddress2", "WifiMacAddrWl0", "WifiMacAddrWl1") ] # Assume not supported when exception is thrown with suppress(Exception): macs.extend(x.get("WifiMac") for x in wlan_settings["Ssids"]["Ssid"]) return sorted({format_mac(str(x)) for x in macs if x})
Get requests.Session that does not verify HTTPS, filter warnings about it.
def non_verifying_requests_session(url: str) -> requests.Session: """Get requests.Session that does not verify HTTPS, filter warnings about it.""" parsed_url = urlparse(url) assert parsed_url.hostname requests_session = requests.Session() requests_session.verify = False warnings.filterwarnings( "ignore", message=rf"^.*\b{re.escape(parsed_url.hostname)}\b", category=InsecureRequestWarning, module=r"^urllib3\.connectionpool$", ) return requests_session
Start a config flow.
def create_config_flow(hass: core.HomeAssistant, host: str) -> None: """Start a config flow.""" hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={"host": host}, ) )
Register services for Hue integration.
def async_register_services(hass: HomeAssistant) -> None: """Register services for Hue integration.""" async def hue_activate_scene(call: ServiceCall, skip_reload=True) -> None: """Handle activation of Hue scene.""" # Get parameters group_name = call.data[ATTR_GROUP_NAME] scene_name = call.data[ATTR_SCENE_NAME] transition = call.data.get(ATTR_TRANSITION) dynamic = call.data.get(ATTR_DYNAMIC, False) # Call the set scene function on each bridge tasks = [ hue_activate_scene_v1(bridge, group_name, scene_name, transition) if bridge.api_version == 1 else hue_activate_scene_v2( bridge, group_name, scene_name, transition, dynamic ) for bridge in hass.data[DOMAIN].values() if isinstance(bridge, HueBridge) ] results = await asyncio.gather(*tasks) # Did *any* bridge succeed? # Note that we'll get a "True" value for a successful call if True not in results: LOGGER.warning( "No bridge was able to activate scene %s in group %s", scene_name, group_name, ) if not hass.services.has_service(DOMAIN, SERVICE_HUE_ACTIVATE_SCENE): # Register a local handler for scene activation hass.services.async_register( DOMAIN, SERVICE_HUE_ACTIVATE_SCENE, verify_domain_control(hass, DOMAIN)(hue_activate_scene), schema=vol.Schema( { vol.Required(ATTR_GROUP_NAME): cv.string, vol.Required(ATTR_SCENE_NAME): cv.string, vol.Optional(ATTR_TRANSITION): cv.positive_int, vol.Optional(ATTR_DYNAMIC): cv.boolean, } ), )
Resolve hue event from device id.
def _get_hue_event_from_device_id(hass, device_id): """Resolve hue event from device id.""" for bridge in hass.data.get(DOMAIN, {}).values(): for hue_event in bridge.sensor_manager.current_events.values(): if device_id == hue_event.device_registry_id: return hue_event return None
Return device triggers for device on `v1` bridge. Make sure device is a supported remote model. Retrieve the hue event object matching device entry. Generate device trigger list.
def async_get_triggers(bridge: HueBridge, device: DeviceEntry) -> list[dict[str, str]]: """Return device triggers for device on `v1` bridge. Make sure device is a supported remote model. Retrieve the hue event object matching device entry. Generate device trigger list. """ if device.model not in REMOTES: return [] triggers = [] for trigger, subtype in REMOTES[device.model]: triggers.append( { CONF_DEVICE_ID: device.id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: "device", CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers
Create the light.
def create_light(item_class, coordinator, bridge, is_group, rooms, api, item_id): """Create the light.""" api_item = api[item_id] if is_group: supported_color_modes = set() supported_features = LightEntityFeature(0) for light_id in api_item.lights: if light_id not in bridge.api.lights: continue light = bridge.api.lights[light_id] supported_features |= SUPPORT_HUE.get(light.type, SUPPORT_HUE_EXTENDED) supported_color_modes.update( COLOR_MODES_HUE.get(light.type, COLOR_MODES_HUE_EXTENDED) ) supported_features = supported_features or SUPPORT_HUE_EXTENDED supported_color_modes = supported_color_modes or COLOR_MODES_HUE_EXTENDED supported_color_modes = filter_supported_color_modes(supported_color_modes) else: supported_color_modes = COLOR_MODES_HUE.get( api_item.type, COLOR_MODES_HUE_EXTENDED ) supported_features = SUPPORT_HUE.get(api_item.type, SUPPORT_HUE_EXTENDED) return item_class( coordinator, bridge, is_group, api_item, supported_color_modes, supported_features, rooms, )
Update items.
def async_update_items( bridge, api, current, async_add_entities, create_item, new_items_callback ): """Update items.""" new_items = [] for item_id in api: if item_id in current: continue current[item_id] = create_item(api, item_id) new_items.append(current[item_id]) bridge.hass.async_create_task(remove_devices(bridge, api, current)) if new_items: # This is currently used to setup the listener to update rooms if new_items_callback: new_items_callback() async_add_entities(new_items)
Convert hue brightness 1..254 to hass format 0..255.
def hue_brightness_to_hass(value): """Convert hue brightness 1..254 to hass format 0..255.""" return min(255, round((value / 254) * 255))
Convert hass brightness 0..255 to hue 1..254 scale.
def hass_to_hue_brightness(value): """Convert hass brightness 0..255 to hue 1..254 scale.""" return max(1, round((value / 255) * 254))
Return device triggers for device on `v2` bridge.
def async_get_triggers( bridge: HueBridge, device_entry: DeviceEntry ) -> list[dict[str, Any]]: """Return device triggers for device on `v2` bridge.""" api: HueBridgeV2 = bridge.api # Get Hue device id from device identifier hue_dev_id = get_hue_device_id(device_entry) # extract triggers from all button resources of this Hue device triggers: list[dict[str, Any]] = [] model_id = api.devices[hue_dev_id].product_data.product_name for resource in api.devices.get_sensors(hue_dev_id): # button triggers if resource.type == ResourceTypes.BUTTON: triggers.extend( { CONF_DEVICE_ID: device_entry.id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: "device", CONF_TYPE: event_type.value, CONF_SUBTYPE: resource.metadata.control_id, CONF_UNIQUE_ID: resource.id, } for event_type in DEVICE_SPECIFIC_EVENT_TYPES.get( model_id, DEFAULT_BUTTON_EVENT_TYPES ) ) # relative_rotary triggers elif resource.type == ResourceTypes.RELATIVE_ROTARY: triggers.extend( { CONF_DEVICE_ID: device_entry.id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: "device", CONF_TYPE: event_type.value, CONF_SUBTYPE: sub_type.value, CONF_UNIQUE_ID: resource.id, } for event_type in DEFAULT_ROTARY_EVENT_TYPES for sub_type in DEFAULT_ROTARY_EVENT_SUBTYPES ) return triggers
Get Hue device id from device entry.
def get_hue_device_id(device_entry: DeviceEntry) -> str | None: """Get Hue device id from device entry.""" return next( ( identifier[1] for identifier in device_entry.identifiers if identifier[0] == DOMAIN and ":" not in identifier[1] # filter out v1 mac id ), None, )
Return calculated brightness values.
def normalize_hue_brightness(brightness: float | None) -> float | None: """Return calculated brightness values.""" if brightness is not None: # Hue uses a range of [0, 100] to control brightness. brightness = float((brightness / 255) * 100) return brightness
Return rounded transition values.
def normalize_hue_transition(transition: float | None) -> float | None: """Return rounded transition values.""" if transition is not None: # hue transition duration is in milliseconds and round them to 100ms transition = int(round(transition, 1) * 1000) return transition
Return color temperature within Hue's ranges.
def normalize_hue_colortemp(colortemp: int | None) -> int | None: """Return color temperature within Hue's ranges.""" if colortemp is not None: # Hue only accepts a range between 153..500 colortemp = min(colortemp, 500) colortemp = max(colortemp, 153) return colortemp
Get the cumulative energy consumption for a certain period. :param current_measurements: The result from the Huisbaasje client :param source_type: The source of energy (electricity or gas) :param period_type: The period for which cumulative value should be given.
def _get_cumulative_value( current_measurements: dict, source_type: str, period_type: str, ): """Get the cumulative energy consumption for a certain period. :param current_measurements: The result from the Huisbaasje client :param source_type: The source of energy (electricity or gas) :param period_type: The period for which cumulative value should be given. """ if source_type in current_measurements: if ( period_type in current_measurements[source_type] and current_measurements[source_type][period_type] is not None ): return current_measurements[source_type][period_type]["value"] else: _LOGGER.error( "Source type %s not present in %s", source_type, current_measurements ) return None
Create a function to test a device condition.
def async_condition_from_config( hass: HomeAssistant, config: ConfigType ) -> condition.ConditionCheckerType: """Create a function to test a device condition.""" if config[CONF_TYPE] == "is_mode": attribute = ATTR_MODE else: return toggle_entity.async_condition_from_config(hass, config) registry = er.async_get(hass) entity_id = er.async_resolve_entity_id(registry, config[ATTR_ENTITY_ID]) def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool: """Test if an entity is a certain state.""" return ( entity_id is not None and (state := hass.states.get(entity_id)) is not None and state.attributes.get(attribute) == config[attribute] ) return test_is_state
Test if state significantly changed.
def async_check_significant_change( hass: HomeAssistant, old_state: str, old_attrs: dict, new_state: str, new_attrs: dict, **kwargs: Any, ) -> bool | None: """Test if state significantly changed.""" if old_state != new_state: return True old_attrs_s = set( {k: v for k, v in old_attrs.items() if k in SIGNIFICANT_ATTRIBUTES}.items() ) new_attrs_s = set( {k: v for k, v in new_attrs.items() if k in SIGNIFICANT_ATTRIBUTES}.items() ) changed_attrs: set[str] = {item[0] for item in old_attrs_s ^ new_attrs_s} for attr_name in changed_attrs: if attr_name in [ATTR_ACTION, ATTR_MODE]: return True old_attr_value = old_attrs.get(attr_name) new_attr_value = new_attrs.get(attr_name) if new_attr_value is None or not check_valid_float(new_attr_value): # New attribute value is invalid, ignore it continue if old_attr_value is None or not check_valid_float(old_attr_value): # Old attribute value was invalid, we should report again return True if check_absolute_change(old_attr_value, new_attr_value, 1.0): return True # no significant attribute change detected return False
Return if the humidifier is on based on the statemachine. Async friendly.
def is_on(hass: HomeAssistant, entity_id: str) -> bool: """Return if the humidifier is on based on the statemachine. Async friendly. """ return hass.states.is_state(entity_id, STATE_ON)
Create a PowerViewShade entity.
def create_powerview_shade_entity( coordinator: PowerviewShadeUpdateCoordinator, device_info: PowerviewDeviceInfo, room_name: str, shade: BaseShade, name_before_refresh: str, ) -> Iterable[ShadeEntity]: """Create a PowerViewShade entity.""" classes: Iterable[BaseShade] = TYPE_TO_CLASSES.get( shade.capability.type, (PowerViewShade,) ) _LOGGER.debug( "%s %s (%s) detected as %a %s", room_name, shade.name, shade.capability.type, classes, shade.raw_data, ) return [ cls(coordinator, device_info, room_name, shade, name_before_refresh) for cls in classes ]
Return diagnostics for a config entry.
def _async_get_diagnostics( hass: HomeAssistant, entry: ConfigEntry, ) -> dict[str, Any]: """Return diagnostics for a config entry.""" pv_entry: PowerviewEntryData = hass.data[DOMAIN][entry.entry_id] shade_data = pv_entry.coordinator.data.get_all_raw_data() hub_info = async_redact_data(asdict(pv_entry.device_info), REDACT_CONFIG) return {"hub_info": hub_info, "shade_data": shade_data}
Represent a Powerview device as a dictionary.
def _async_device_as_dict(hass: HomeAssistant, device: DeviceEntry) -> dict[str, Any]: """Represent a Powerview device as a dictionary.""" # Gather information how this device is represented in Home Assistant entity_registry = er.async_get(hass) data = async_redact_data(attr.asdict(device), REDACT_CONFIG) data["entities"] = [] entities: list[dict[str, Any]] = data["entities"] entries = er.async_entries_for_device( entity_registry, device_id=device.id, include_disabled_entities=True, ) for entity_entry in entries: state = hass.states.get(entity_entry.entity_id) state_dict = None if state: state_dict = dict(state.as_dict()) state_dict.pop("context", None) entity = attr.asdict(entity_entry) entity["state"] = state_dict entities.append(entity) return data
Store the desired shade velocity in the coordinator.
def store_velocity( coordinator: PowerviewShadeUpdateCoordinator, shade_id: int, value: float | None, ) -> None: """Store the desired shade velocity in the coordinator.""" coordinator.data.update_shade_velocity(shade_id, ShadePosition(velocity=value))
Get the signal value based on version of API.
def get_signal_device_class(shade: BaseShade) -> SensorDeviceClass | None: """Get the signal value based on version of API.""" return SensorDeviceClass.SIGNAL_STRENGTH if shade.api_version >= 3 else None
Get the unit of measurement for signal based on version of API.
def get_signal_native_unit(shade: BaseShade) -> str: """Get the unit of measurement for signal based on version of API.""" return SIGNAL_STRENGTH_DECIBELS if shade.api_version >= 3 else PERCENTAGE
Copy position data from source to target for None values only.
def copy_position_data(source: ShadePosition, target: ShadePosition) -> ShadePosition: """Copy position data from source to target for None values only.""" for field in POSITION_FIELDS: if (value := getattr(source, field.name)) is not None: setattr(target, field.name, value)
Return a dict with the key being the id for a list of entries.
def async_map_data_by_id(data: Iterable[dict[str | int, Any]]): """Return a dict with the key being the id for a list of entries.""" return {entry[ATTR_ID]: entry for entry in data}
Return the cutting height.
def _async_get_cutting_height(data: MowerAttributes) -> int: """Return the cutting height.""" if TYPE_CHECKING: # Sensor does not get created if it is None assert data.cutting_height is not None return data.cutting_height
Calculate a sensor's unique_id.
def _sensor_unique_id(server_id: str, instance_num: int, suffix: str) -> str: """Calculate a sensor's unique_id.""" return get_hyperion_unique_id( server_id, instance_num, f"{TYPE_HYPERION_SENSOR_BASE}_{suffix}", )
Convert a component to a unique_id.
def _component_to_unique_id(server_id: str, component: str, instance_num: int) -> str: """Convert a component to a unique_id.""" return get_hyperion_unique_id( server_id, instance_num, slugify( f"{TYPE_HYPERION_COMPONENT_SWITCH_BASE} {KEY_COMPONENTID_TO_NAME[component]}" ), )
Get a unique_id for a Hyperion instance.
def get_hyperion_unique_id(server_id: str, instance: int, name: str) -> str: """Get a unique_id for a Hyperion instance.""" return f"{server_id}_{instance}_{name}"
Get an id for a Hyperion device/instance.
def get_hyperion_device_id(server_id: str, instance: int) -> str: """Get an id for a Hyperion device/instance.""" return f"{server_id}_{instance}"
Split a unique_id into a (server_id, instance, type) tuple.
def split_hyperion_unique_id(unique_id: str) -> tuple[str, int, str] | None: """Split a unique_id into a (server_id, instance, type) tuple.""" data = tuple(unique_id.split("_", 2)) if len(data) != 3: return None try: return (data[0], int(data[1]), data[2]) except ValueError: return None
Create a Hyperion Client.
def create_hyperion_client( *args: Any, **kwargs: Any, ) -> client.HyperionClient: """Create a Hyperion Client.""" return client.HyperionClient(*args, **kwargs)
Listen for instance additions/removals.
def listen_for_instance_updates( hass: HomeAssistant, config_entry: ConfigEntry, add_func: Callable, remove_func: Callable, ) -> None: """Listen for instance additions/removals.""" hass.data[DOMAIN][config_entry.entry_id][CONF_ON_UNLOAD].extend( [ async_dispatcher_connect( hass, SIGNAL_INSTANCE_ADD.format(config_entry.entry_id), add_func, ), async_dispatcher_connect( hass, SIGNAL_INSTANCE_REMOVE.format(config_entry.entry_id), remove_func, ), ] )
Migrate old unique ids to new unique ids.
def _migrate_to_new_unique_id( hass: HomeAssistant, model: str, serial_number: str ) -> None: """Migrate old unique ids to new unique ids.""" ent_reg = er.async_get(hass) name_list = [ "Voltage", "Current", "Power", "ImportEnergy", "ExportGrid", "Frequency", "PF", ] phase_list = ["A", "B", "C", "NET"] id_phase_range = 1 if model == DEVICE_3080 else 4 id_name_range = 5 if model == DEVICE_3080 else 7 for row in range(id_phase_range): for idx in range(id_name_range): old_unique_id = f"{serial_number}-{row}-{idx}" new_unique_id = ( f"{serial_number}_{name_list[idx]}" if model == DEVICE_3080 else f"{serial_number}_{name_list[idx]}_{phase_list[row]}" ) entity_id = ent_reg.async_get_entity_id( Platform.SENSOR, DOMAIN, old_unique_id ) if entity_id is not None: try: ent_reg.async_update_entity(entity_id, new_unique_id=new_unique_id) except ValueError: _LOGGER.warning( "Skip migration of id [%s] to [%s] because it already exists", old_unique_id, new_unique_id, ) else: _LOGGER.debug( "Migrating unique_id from [%s] to [%s]", old_unique_id, new_unique_id, )
Force update all entities after state change.
def refresh_system( func: Callable[Concatenate[_AqualinkEntityT, _P], Awaitable[Any]], ) -> Callable[Concatenate[_AqualinkEntityT, _P], Coroutine[Any, Any, None]]: """Force update all entities after state change.""" @wraps(func) async def wrapper( self: _AqualinkEntityT, *args: _P.args, **kwargs: _P.kwargs ) -> None: """Call decorated function and send update signal to all entities.""" await func(self, *args, **kwargs) async_dispatcher_send(self.hass, DOMAIN) return wrapper
Signal for the unique_id going unavailable.
def signal_unavailable(unique_id: str) -> str: """Signal for the unique_id going unavailable.""" return f"{SIGNAL_IBEACON_DEVICE_UNAVAILABLE}_{unique_id}"
Signal for the unique_id being seen.
def signal_seen(unique_id: str) -> str: """Signal for the unique_id being seen.""" return f"{SIGNAL_IBEACON_DEVICE_SEEN}_{unique_id}"
Convert a Bluetooth address to a short address.
def make_short_address(address: str) -> str: """Convert a Bluetooth address to a short address.""" results = address.replace("-", ":").split(":") return f"{results[-2].upper()}{results[-1].upper()}"[-4:]