response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Crownstone 0..100 to hass 0..255.
def crownstone_state_to_hass(value: int) -> int: """Crownstone 0..100 to hass 0..255.""" return map_from_to(value, 0, 100, 0, 255)
Hass 0..255 to Crownstone 0..100.
def hass_to_crownstone_state(value: int) -> int: """Hass 0..255 to Crownstone 0..100.""" return map_from_to(value, 0, 255, 0, 100)
Update the state of a Crownstone when switched externally.
def async_update_crwn_state_sse( manager: CrownstoneEntryManager, switch_event: SwitchStateUpdateEvent ) -> None: """Update the state of a Crownstone when switched externally.""" try: updated_crownstone = manager.cloud.get_crownstone_by_id(switch_event.cloud_id) except CrownstoneNotFoundError: return # only update on change. if updated_crownstone.state != switch_event.switch_state: updated_crownstone.state = switch_event.switch_state async_dispatcher_send(manager.hass, SIG_CROWNSTONE_STATE_UPDATE)
Update the ability information of a Crownstone.
def async_update_crwn_ability( manager: CrownstoneEntryManager, ability_event: AbilityChangeEvent ) -> None: """Update the ability information of a Crownstone.""" try: updated_crownstone = manager.cloud.get_crownstone_by_id(ability_event.cloud_id) except CrownstoneNotFoundError: return ability_type = ability_event.ability_type ability_enabled = ability_event.ability_enabled # only update on a change in state if updated_crownstone.abilities[ability_type].is_enabled == ability_enabled: return # write the change to the crownstone entity. updated_crownstone.abilities[ability_type].is_enabled = ability_enabled if ability_event.sub_type == EVENT_ABILITY_CHANGE_DIMMING: # reload the config entry because dimming is part of supported features manager.hass.async_create_task( manager.hass.config_entries.async_reload(manager.config_entry.entry_id) ) else: async_dispatcher_send(manager.hass, SIG_CROWNSTONE_STATE_UPDATE)
Update the uart ready state for entities that use USB.
def update_uart_state(manager: CrownstoneEntryManager, _: bool | None) -> None: """Update the uart ready state for entities that use USB.""" # update availability of power usage entities. dispatcher_send(manager.hass, SIG_UART_STATE_CHANGE)
Update the state of a Crownstone when switched externally.
def update_crwn_state_uart( manager: CrownstoneEntryManager, data: AdvExternalCrownstoneState ) -> None: """Update the state of a Crownstone when switched externally.""" if data.type != AdvType.EXTERNAL_STATE: return try: updated_crownstone = manager.cloud.get_crownstone_by_uid( data.crownstoneId, manager.usb_sphere_id ) except CrownstoneNotFoundError: return if data.switchState is None: return # update on change updated_state = cast(SwitchState, data.switchState) if updated_crownstone.state != updated_state.intensity: updated_crownstone.state = updated_state.intensity dispatcher_send(manager.hass, SIG_CROWNSTONE_STATE_UPDATE)
Set up SSE listeners.
def setup_sse_listeners(manager: CrownstoneEntryManager) -> None: """Set up SSE listeners.""" # save unsub function for when entry removed manager.listeners[SSE_LISTENERS] = [ async_dispatcher_connect( manager.hass, f"{DOMAIN}_{EVENT_SWITCH_STATE_UPDATE}", partial(async_update_crwn_state_sse, manager), ), async_dispatcher_connect( manager.hass, f"{DOMAIN}_{EVENT_ABILITY_CHANGE}", partial(async_update_crwn_ability, manager), ), ]
Set up UART listeners.
def setup_uart_listeners(manager: CrownstoneEntryManager) -> None: """Set up UART listeners.""" # save subscription id to unsub manager.listeners[UART_LISTENERS] = [ UartEventBus.subscribe( SystemTopics.connectionEstablished, partial(update_uart_state, manager), ), UartEventBus.subscribe( SystemTopics.connectionClosed, partial(update_uart_state, manager), ), UartEventBus.subscribe( UartTopics.newDataAvailable, partial(update_crwn_state_uart, manager), ), ]
Set up the CUPS sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the CUPS sensor.""" host: str = config[CONF_HOST] port: int = config[CONF_PORT] printers: list[str] = config[CONF_PRINTERS] is_cups: bool = config[CONF_IS_CUPS_SERVER] if is_cups: data = CupsData(host, port, None) data.update() if data.available is False: _LOGGER.error("Unable to connect to CUPS server: %s:%s", host, port) raise PlatformNotReady assert data.printers is not None dev: list[SensorEntity] = [] for printer in printers: if printer not in data.printers: _LOGGER.error("Printer is not present: %s", printer) continue dev.append(CupsSensor(data, printer)) if "marker-names" in data.attributes[printer]: dev.extend( MarkerSensor(data, printer, marker, True) for marker in data.attributes[printer]["marker-names"] ) add_entities(dev, True) return data = CupsData(host, port, printers) data.update() if data.available is False: _LOGGER.error("Unable to connect to IPP printer: %s:%s", host, port) raise PlatformNotReady dev = [] for printer in printers: dev.append(IPPSensor(data, printer)) if "marker-names" in data.attributes[printer]: for marker in data.attributes[printer]["marker-names"]: dev.append(MarkerSensor(data, printer, marker, False)) add_entities(dev, True)
Set up the Currencylayer sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Currencylayer sensor.""" base = config[CONF_BASE] api_key = config[CONF_API_KEY] parameters = {"source": base, "access_key": api_key, "format": 1} rest = CurrencylayerData(_RESOURCE, parameters) response = requests.get(_RESOURCE, params=parameters, timeout=10) if "error" in response.json(): return add_entities( (CurrencylayerSensor(rest, base, variable) for variable in config[CONF_QUOTE]), True, )
Format target temperature to be sent to the Daikin unit, rounding to nearest half degree.
def format_target_temperature(target_temperature: float) -> str: """Format target temperature to be sent to the Daikin unit, rounding to nearest half degree.""" return str(round(float(target_temperature) * 2, 0) / 2).rstrip("0").rstrip(".")
Update unique ID of entity entry.
def update_unique_id( entity_entry: er.RegistryEntry, unique_id: str ) -> dict[str, str] | None: """Update unique ID of entity entry.""" if entity_entry.unique_id.startswith(unique_id): # Already correct, nothing to do return None unique_id_parts = entity_entry.unique_id.split("-") unique_id_parts[0] = unique_id entity_new_unique_id = "-".join(unique_id_parts) _LOGGER.debug( "Migrating entity %s from %s to new id %s", entity_entry.entity_id, entity_entry.unique_id, entity_new_unique_id, ) return {"new_unique_id": entity_new_unique_id}
Set up the available Danfoss Air sensors etc.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the available Danfoss Air sensors etc.""" data = hass.data[DANFOSS_AIR_DOMAIN] sensors = [ [ "Danfoss Air Bypass Active", ReadCommand.bypass, BinarySensorDeviceClass.OPENING, ], ["Danfoss Air Away Mode Active", ReadCommand.away_mode, None], ] add_entities( ( DanfossAirBinarySensor(data, sensor[0], sensor[1], sensor[2]) for sensor in sensors ), True, )
Set up the available Danfoss Air sensors etc.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the available Danfoss Air sensors etc.""" data = hass.data[DANFOSS_AIR_DOMAIN] sensors = [ [ "Danfoss Air Exhaust Temperature", UnitOfTemperature.CELSIUS, ReadCommand.exhaustTemperature, SensorDeviceClass.TEMPERATURE, SensorStateClass.MEASUREMENT, ], [ "Danfoss Air Outdoor Temperature", UnitOfTemperature.CELSIUS, ReadCommand.outdoorTemperature, SensorDeviceClass.TEMPERATURE, SensorStateClass.MEASUREMENT, ], [ "Danfoss Air Supply Temperature", UnitOfTemperature.CELSIUS, ReadCommand.supplyTemperature, SensorDeviceClass.TEMPERATURE, SensorStateClass.MEASUREMENT, ], [ "Danfoss Air Extract Temperature", UnitOfTemperature.CELSIUS, ReadCommand.extractTemperature, SensorDeviceClass.TEMPERATURE, SensorStateClass.MEASUREMENT, ], [ "Danfoss Air Remaining Filter", PERCENTAGE, ReadCommand.filterPercent, None, None, ], [ "Danfoss Air Humidity", PERCENTAGE, ReadCommand.humidity, SensorDeviceClass.HUMIDITY, SensorStateClass.MEASUREMENT, ], ["Danfoss Air Fan Step", PERCENTAGE, ReadCommand.fan_step, None, None], [ "Danfoss Air Exhaust Fan Speed", REVOLUTIONS_PER_MINUTE, ReadCommand.exhaust_fan_speed, None, None, ], [ "Danfoss Air Supply Fan Speed", REVOLUTIONS_PER_MINUTE, ReadCommand.supply_fan_speed, None, None, ], [ "Danfoss Air Dial Battery", PERCENTAGE, ReadCommand.battery_percent, SensorDeviceClass.BATTERY, None, ], ] add_entities( ( DanfossAir(data, sensor[0], sensor[1], sensor[2], sensor[3], sensor[4]) for sensor in sensors ), True, )
Set up the Danfoss Air HRV switch platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Danfoss Air HRV switch platform.""" data = hass.data[DANFOSS_AIR_DOMAIN] switches = [ [ "Danfoss Air Boost", ReadCommand.boost, UpdateCommand.boost_activate, UpdateCommand.boost_deactivate, ], [ "Danfoss Air Bypass", ReadCommand.bypass, UpdateCommand.bypass_activate, UpdateCommand.bypass_deactivate, ], [ "Danfoss Air Automatic Bypass", ReadCommand.automatic_bypass, UpdateCommand.bypass_activate, UpdateCommand.bypass_deactivate, ], ] add_entities( DanfossAir(data, switch[0], switch[1], switch[2], switch[3]) for switch in switches )
Set up the Danfoss Air component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Danfoss Air component.""" conf = config[DOMAIN] hass.data[DOMAIN] = DanfossAir(conf[CONF_HOST]) for platform in PLATFORMS: discovery.load_platform(hass, platform, DOMAIN, {}, config) return True
Set up the Datadog component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Datadog component.""" conf = config[DOMAIN] host = conf[CONF_HOST] port = conf[CONF_PORT] sample_rate = conf[CONF_RATE] prefix = conf[CONF_PREFIX] initialize(statsd_host=host, statsd_port=port) def logbook_entry_listener(event): """Listen for logbook entries and send them as events.""" name = event.data.get("name") message = event.data.get("message") statsd.event( title="Home Assistant", text=f"%%% \n **{name}** {message} \n %%%", tags=[ f"entity:{event.data.get('entity_id')}", f"domain:{event.data.get('domain')}", ], ) _LOGGER.debug("Sent event %s", event.data.get("entity_id")) def state_changed_listener(event): """Listen for new messages on the bus and sends them to Datadog.""" state = event.data.get("new_state") if state is None or state.state == STATE_UNKNOWN: return states = dict(state.attributes) metric = f"{prefix}.{state.domain}" tags = [f"entity:{state.entity_id}"] for key, value in states.items(): if isinstance(value, (float, int)): attribute = f"{metric}.{key.replace(' ', '_')}" value = int(value) if isinstance(value, bool) else value statsd.gauge(attribute, value, sample_rate=sample_rate, tags=tags) _LOGGER.debug("Sent metric %s: %s (tags: %s)", attribute, value, tags) try: value = state_helper.state_as_number(state) except ValueError: _LOGGER.debug("Error sending %s: %s (tags: %s)", metric, state.state, tags) return statsd.gauge(metric, value, sample_rate=sample_rate, tags=tags) _LOGGER.debug("Sent metric %s: %s (tags: %s)", metric, value, tags) hass.bus.listen(EVENT_LOGBOOK_ENTRY, logbook_entry_listener) hass.bus.listen(EVENT_STATE_CHANGED, state_changed_listener) return True
Validate the configuration and return a DD-WRT scanner.
def get_scanner(hass: HomeAssistant, config: ConfigType) -> DdWrtDeviceScanner | None: """Validate the configuration and return a DD-WRT scanner.""" try: return DdWrtDeviceScanner(config[DOMAIN]) except ConnectionError: return None
Parse the DD-WRT data format.
def _parse_ddwrt_response(data_str): """Parse the DD-WRT data format.""" return dict(_DDWRT_DATA_REGEX.findall(data_str))
Retrieve alarm system ID the unique ID is registered to.
def get_alarm_system_id_for_unique_id(hub: DeconzHub, unique_id: str) -> str | None: """Retrieve alarm system ID the unique ID is registered to.""" for alarm_system in hub.api.alarm_systems.values(): if unique_id in alarm_system.devices: return alarm_system.resource_id return None
Return the gateway which is marked as master.
def get_master_hub(hass: HomeAssistant) -> DeconzHub: """Return the gateway which is marked as master.""" for hub in hass.data[DOMAIN].values(): if hub.master: return cast(DeconzHub, hub) raise ValueError
Unload all deCONZ events.
def async_unload_events(hub: DeconzHub) -> None: """Unload all deCONZ events.""" for event in hub.events: event.async_will_remove_from_hass() hub.events.clear()
Resolve deconz event from device.
def _get_deconz_event_from_device( hass: HomeAssistant, device: dr.DeviceEntry, ) -> DeconzAlarmEvent | DeconzEvent | DeconzPresenceEvent | DeconzRelativeRotaryEvent: """Resolve deconz event from device.""" hubs: dict[str, DeconzHub] = hass.data.get(DOMAIN, {}) for hub in hubs.values(): for deconz_event in hub.events: if device.id == deconz_event.device_id: return deconz_event raise InvalidDeviceAutomationConfig( f'No deconz_event tied to device "{device.name}" found' )
Get device event description.
def _get_device_event_description( modelid: str, event: int ) -> tuple[str | None, str | None]: """Get device event description.""" device_event_descriptions = REMOTES[modelid] for event_type_tuple, event_dict in device_event_descriptions.items(): if event == event_dict.get(CONF_EVENT): return event_type_tuple if event == event_dict.get(CONF_GESTURE): return event_type_tuple return (None, None)
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_deconz_alarm_event(event: Event) -> dict[str, str]: """Describe deCONZ logbook alarm event.""" if device := device_registry.devices.get(event.data[ATTR_DEVICE_ID]): deconz_alarm_event = _get_deconz_event_from_device(hass, device) name = deconz_alarm_event.device.name else: name = event.data[CONF_ID] data = event.data[CONF_EVENT] return { LOGBOOK_ENTRY_NAME: name, LOGBOOK_ENTRY_MESSAGE: f"fired event '{data}'", } @callback def async_describe_deconz_event(event: Event) -> dict[str, str]: """Describe deCONZ logbook event.""" if device := device_registry.devices.get(event.data[ATTR_DEVICE_ID]): deconz_event = _get_deconz_event_from_device(hass, device) name = deconz_event.device.name else: deconz_event = None name = event.data[CONF_ID] action = None interface = None data = event.data.get(CONF_EVENT) or event.data.get(CONF_GESTURE, "") if data and deconz_event and deconz_event.device.model_id in REMOTES: action, interface = _get_device_event_description( deconz_event.device.model_id, data ) # Unknown event if not data: return { LOGBOOK_ENTRY_NAME: name, LOGBOOK_ENTRY_MESSAGE: "fired an unknown event", } # No device event match if not action: return { LOGBOOK_ENTRY_NAME: name, LOGBOOK_ENTRY_MESSAGE: f"fired event '{data}'", } # Gesture event if not interface: return { LOGBOOK_ENTRY_NAME: name, LOGBOOK_ENTRY_MESSAGE: f"fired event '{ACTIONS[action]}'", } return { LOGBOOK_ENTRY_NAME: name, LOGBOOK_ENTRY_MESSAGE: ( f"'{ACTIONS[action]}' event for '{INTERFACES[interface]}' was fired" ), } async_describe_event( DECONZ_DOMAIN, CONF_DECONZ_ALARM_EVENT, async_describe_deconz_alarm_event ) async_describe_event(DECONZ_DOMAIN, CONF_DECONZ_EVENT, async_describe_deconz_event)
Set up services for deCONZ integration.
def async_setup_services(hass: HomeAssistant) -> None: """Set up services for deCONZ integration.""" async def async_call_deconz_service(service_call: ServiceCall) -> None: """Call correct deCONZ service.""" service = service_call.service service_data = service_call.data if CONF_BRIDGE_ID in service_data: found_hub = False bridge_id = normalize_bridge_id(service_data[CONF_BRIDGE_ID]) for possible_hub in hass.data[DOMAIN].values(): if possible_hub.bridgeid == bridge_id: hub = possible_hub found_hub = True break if not found_hub: LOGGER.error("Could not find the gateway %s", bridge_id) return else: try: hub = get_master_hub(hass) except ValueError: LOGGER.error("No master gateway available") return if service == SERVICE_CONFIGURE_DEVICE: await async_configure_service(hub, service_data) elif service == SERVICE_DEVICE_REFRESH: await async_refresh_devices_service(hub) elif service == SERVICE_REMOVE_ORPHANED_ENTRIES: await async_remove_orphaned_entries_service(hub) for service in SUPPORTED_SERVICES: hass.services.async_register( DOMAIN, service, async_call_deconz_service, schema=SERVICE_TO_SCHEMA[service], )
Unload deCONZ services.
def async_unload_services(hass: HomeAssistant) -> None: """Unload deCONZ services.""" for service in SUPPORTED_SERVICES: hass.services.async_remove(DOMAIN, service)
Get a device serial number from a unique ID, if possible.
def serial_from_unique_id(unique_id: str | None) -> str | None: """Get a device serial number from a unique ID, if possible.""" if not unique_id or unique_id.count(":") != 7: return None return unique_id.partition("-")[0]
Validate the name.
def _name_validator(config): """Validate the name.""" config = copy.deepcopy(config) for address, device_config in config[CONF_DEVICES].items(): if CONF_NAME not in device_config: device_config[CONF_NAME] = util.slugify(address) return config
Retry bluetooth commands.
def retry( method: Callable[Concatenate[_DecoraLightT, _P], _R], ) -> Callable[Concatenate[_DecoraLightT, _P], _R | None]: """Retry bluetooth commands.""" @wraps(method) def wrapper_retry( device: _DecoraLightT, *args: _P.args, **kwargs: _P.kwargs ) -> _R | None: """Try send command and retry on error.""" initial = time.monotonic() while True: if time.monotonic() - initial >= 10: return None try: return method(device, *args, **kwargs) except (decora.decoraException, AttributeError, BTLEException): _LOGGER.warning( "Decora connect error for device %s. Reconnecting", device.name, ) # pylint: disable-next=protected-access device._switch.connect() return wrapper_retry
Set up an Decora switch.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up an Decora switch.""" lights = [] for address, device_config in config[CONF_DEVICES].items(): device = {} device["name"] = device_config[CONF_NAME] device["key"] = device_config[CONF_API_KEY] device["address"] = address light = DecoraLight(device) lights.append(light) add_entities(lights)
Set up the Decora WiFi platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Decora WiFi platform.""" email = config[CONF_USERNAME] password = config[CONF_PASSWORD] session = DecoraWiFiSession() try: success = session.login(email, password) # If login failed, notify user. if success is None: msg = "Failed to log into myLeviton Services. Check credentials." _LOGGER.error(msg) persistent_notification.create( hass, msg, title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID ) return # Gather all the available devices... perms = session.user.get_residential_permissions() all_switches: list = [] for permission in perms: if permission.residentialAccountId is not None: acct = ResidentialAccount(session, permission.residentialAccountId) all_switches.extend( switch for residence in acct.get_residences() for switch in residence.get_iot_switches() ) elif permission.residenceId is not None: residence = Residence(session, permission.residenceId) all_switches.extend(residence.get_iot_switches()) add_entities(DecoraWifiLight(sw) for sw in all_switches) except ValueError: _LOGGER.error("Failed to communicate with myLeviton Service") # Listen for the stop event and log out. def logout(event): """Log out...""" try: if session is not None: Person.logout(session) except ValueError: _LOGGER.error("Failed to log out of myLeviton Service") hass.bus.listen(EVENT_HOMEASSISTANT_STOP, logout)
Get current download/upload state.
def get_state(data: dict[str, float], key: str) -> str | float: """Get current download/upload state.""" upload = data[DATA_KEYS[0]] - data[DATA_KEYS[2]] download = data[DATA_KEYS[1]] - data[DATA_KEYS[3]] if key == CURRENT_STATUS: if upload > 0 and download > 0: return "seeding_and_downloading" if upload > 0 and download == 0: return "seeding" if upload == 0 and download > 0: return "downloading" return STATE_IDLE kb_spd = float(upload if key == UPLOAD_SPEED else download) / 1024 return round(kb_spd, 2 if kb_spd < 0.1 else 1)
Representation of a Demo Calendar for a future event.
def calendar_data_future() -> CalendarEvent: """Representation of a Demo Calendar for a future event.""" half_hour_from_now = dt_util.now() + datetime.timedelta(minutes=30) return CalendarEvent( start=half_hour_from_now, end=half_hour_from_now + datetime.timedelta(minutes=60), summary="Future Event", description="Future Description", location="Future Location", )
Representation of a Demo Calendar for a current event.
def calendar_data_current() -> CalendarEvent: """Representation of a Demo Calendar for a current event.""" middle_of_event = dt_util.now() - datetime.timedelta(minutes=30) return CalendarEvent( start=middle_of_event, end=middle_of_event + datetime.timedelta(minutes=60), summary="Current Event", )
Set up the demo tracker.
def setup_scanner( hass: HomeAssistant, config: ConfigType, see: SeeCallback, discovery_info: DiscoveryInfoType | None = None, ) -> bool: """Set up the demo tracker.""" def offset() -> float: """Return random offset.""" return (random.randrange(500, 2000)) / 2e5 * random.choice((-1, 1)) def random_see(dev_id: str, name: str) -> None: """Randomize a sighting.""" see( dev_id=dev_id, host_name=name, gps=(hass.config.latitude + offset(), hass.config.longitude + offset()), gps_accuracy=random.randrange(50, 150), battery=random.randrange(10, 90), ) def observe(call: ServiceCall | None = None) -> None: """Observe three entities.""" random_see("demo_paulus", "Paulus") random_see("demo_anne_therese", "Anne Therese") observe() see( dev_id="demo_home_boy", host_name="Home Boy", gps=(hass.config.latitude - 0.00002, hass.config.longitude + 0.00002), gps_accuracy=20, battery=53, ) hass.services.register(DOMAIN, SERVICE_RANDOMIZE_DEVICE_TRACKER_DATA, observe) return True
Set up the Demo geolocations.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Demo geolocations.""" DemoManager(hass, add_entities)
Set up Demo speech component.
def get_engine( hass: HomeAssistant, config: ConfigType, discovery_info: DiscoveryInfoType | None = None, ) -> Provider: """Set up Demo speech component.""" return DemoProvider(config.get(CONF_LANG, DEFAULT_LANG))
Set up the Denon platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Denon platform.""" denon = DenonDevice(config[CONF_NAME], config[CONF_HOST]) if denon.do_update(): add_entities([denon])
Log errors occurred when calling a Denon AVR receiver. Decorates methods of DenonDevice class. Declaration of staticmethod for this method is at the end of this class.
def async_log_errors( func: Callable[Concatenate[_DenonDeviceT, _P], Awaitable[_R]], ) -> Callable[Concatenate[_DenonDeviceT, _P], Coroutine[Any, Any, _R | None]]: """Log errors occurred when calling a Denon AVR receiver. Decorates methods of DenonDevice class. Declaration of staticmethod for this method is at the end of this class. """ @wraps(func) async def wrapper( self: _DenonDeviceT, *args: _P.args, **kwargs: _P.kwargs ) -> _R | None: # pylint: disable=protected-access available = True try: return await func(self, *args, **kwargs) except AvrTimoutError: available = False if self.available: _LOGGER.warning( ( "Timeout connecting to Denon AVR receiver at host %s. " "Device is unavailable" ), self._receiver.host, ) self._attr_available = False except AvrNetworkError: available = False if self.available: _LOGGER.warning( ( "Network error connecting to Denon AVR receiver at host %s. " "Device is unavailable" ), self._receiver.host, ) self._attr_available = False except AvrProcessingError: available = True if self.available: _LOGGER.warning( ( "Update of Denon AVR receiver at host %s not complete. " "Device is still available" ), self._receiver.host, ) except AvrForbiddenError: available = False if self.available: _LOGGER.warning( ( "Denon AVR receiver at host %s responded with HTTP 403 error. " "Device is unavailable. Please consider power cycling your " "receiver" ), self._receiver.host, ) self._attr_available = False except AvrCommandError as err: available = False _LOGGER.error( "Command %s failed with error: %s", func.__name__, err, ) except DenonAvrError: available = False _LOGGER.exception( "Error occurred in method %s for Denon AVR receiver", func.__name__ ) finally: if available and not self.available: _LOGGER.info( "Denon AVR receiver at host %s is available again", self._receiver.host, ) self._attr_available = True return None return wrapper
Evaluate state based on configuration.
def async_condition_from_config( hass: HomeAssistant, config: ConfigType ) -> condition.ConditionCheckerType: """Evaluate state based on configuration.""" if config[CONF_TYPE] == CONF_IS_ON: stat = "on" else: stat = "off" state_config = { CONF_CONDITION: "state", CONF_ENTITY_ID: config[CONF_ENTITY_ID], CONF_STATE: stat, } if CONF_FOR in config: state_config[CONF_FOR] = config[CONF_FOR] state_config = cv.STATE_CONDITION_SCHEMA(state_config) state_config = condition.state_validate_config(hass, state_config) return condition.state_from_config(state_config)
Set device automation metadata based on entity registry entry data.
def _async_set_entity_device_automation_metadata( hass: HomeAssistant, automation: dict[str, Any] ) -> None: """Set device automation metadata based on entity registry entry data.""" if "metadata" not in automation: automation["metadata"] = {} if ATTR_ENTITY_ID not in automation or "secondary" in automation["metadata"]: return entity_registry = er.async_get(hass) # Guard against the entry being removed before this is called if not (entry := entity_registry.async_get(automation[ATTR_ENTITY_ID])): return automation["metadata"]["secondary"] = bool(entry.entity_category or entry.hidden_by)
Get an entity registry entry from entry ID or raise.
def async_get_entity_registry_entry_or_raise( hass: HomeAssistant, entity_registry_id: str ) -> er.RegistryEntry: """Get an entity registry entry from entry ID or raise.""" entity_registry = er.async_get(hass) entry = entity_registry.async_get(entity_registry_id) if entry is None: raise EntityNotFound return entry
Validate schema and resolve entity registry entry id to entity_id.
def async_validate_entity_schema( hass: HomeAssistant, config: ConfigType, schema: vol.Schema ) -> ConfigType: """Validate schema and resolve entity registry entry id to entity_id.""" config = schema(config) registry = er.async_get(hass) if CONF_ENTITY_ID in config: config[CONF_ENTITY_ID] = er.async_resolve_entity_id( registry, config[CONF_ENTITY_ID] ) return config
Handle device automation errors.
def handle_device_errors( func: Callable[[HomeAssistant, ActiveConnection, dict[str, Any]], Awaitable[None]], ) -> Callable[ [HomeAssistant, ActiveConnection, dict[str, Any]], Coroutine[Any, Any, None] ]: """Handle device automation errors.""" @wraps(func) async def with_error_handling( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: try: await func(hass, connection, msg) except DeviceNotFound: connection.send_error( msg["id"], websocket_api.const.ERR_NOT_FOUND, "Device not found" ) return with_error_handling
Register a newly seen connected device. This is currently used by the dhcp integration to listen for newly registered connected devices for discovery.
def _async_connected_device_registered( hass: HomeAssistant, mac: str, ip_address: str | None, hostname: str | None ) -> None: """Register a newly seen connected device. This is currently used by the dhcp integration to listen for newly registered connected devices for discovery. """ async_dispatcher_send( hass, CONNECTED_DEVICE_REGISTERED, { ATTR_IP: ip_address, ATTR_MAC: mac, ATTR_HOST_NAME: hostname, }, )
Register a mac address with a unique ID.
def _async_register_mac( hass: HomeAssistant, domain: str, mac: str, unique_id: str, ) -> None: """Register a mac address with a unique ID.""" data_key = "device_tracker_mac" mac = dr.format_mac(mac) if data_key in hass.data: hass.data[data_key][mac] = (domain, unique_id) return # Setup listening. # dict mapping mac -> partial unique ID data = hass.data[data_key] = {mac: (domain, unique_id)} @callback def handle_device_event(ev: Event[EventDeviceRegistryUpdatedData]) -> None: """Enable the online status entity for the mac of a newly created device.""" # Only for new devices if ev.data["action"] != "create": return dev_reg = dr.async_get(hass) device_entry = dev_reg.async_get(ev.data["device_id"]) if device_entry is None: # This should not happen, since the device was just created. return # Check if device has a mac mac = None for conn in device_entry.connections: if conn[0] == dr.CONNECTION_NETWORK_MAC: mac = conn[1] break if mac is None: return # Check if we have an entity for this mac if (unique_id := data.get(mac)) is None: return ent_reg = er.async_get(hass) if (entity_id := ent_reg.async_get_entity_id(DOMAIN, *unique_id)) is None: return entity_entry = ent_reg.entities[entity_id] # Make sure entity has a config entry and was disabled by the # default disable logic in the integration and new entities # are allowed to be added. if ( entity_entry.config_entry_id is None or ( ( config_entry := hass.config_entries.async_get_entry( entity_entry.config_entry_id ) ) is not None and config_entry.pref_disable_new_entities ) or entity_entry.disabled_by != er.RegistryEntryDisabler.INTEGRATION ): return # Enable entity ent_reg.async_update_entity(entity_id, disabled_by=None) hass.bus.async_listen(dr.EVENT_DEVICE_REGISTRY_UPDATED, handle_device_event)
Create a function to test a device condition.
def async_condition_from_config( hass: HomeAssistant, config: ConfigType ) -> condition.ConditionCheckerType: """Create a function to test a device condition.""" registry = er.async_get(hass) entity_id = er.async_resolve_entity_id(registry, config[ATTR_ENTITY_ID]) reverse = config[CONF_TYPE] == "is_not_home" @callback def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool: """Test if an entity is a certain state.""" result = condition.state(hass, entity_id, STATE_HOME) if reverse: result = not result return result return test_is_state
Describe group on off states.
def async_describe_on_off_states( hass: HomeAssistant, registry: "GroupIntegrationRegistry" ) -> None: """Describe group on off states.""" registry.on_off_states(DOMAIN, {STATE_HOME}, STATE_HOME, STATE_NOT_HOME)
Call service to notify you see device.
def see( hass: HomeAssistant, mac: str | None = None, dev_id: str | None = None, host_name: str | None = None, location_name: str | None = None, gps: GPSType | None = None, gps_accuracy: int | None = None, battery: int | None = None, attributes: dict[str, Any] | None = None, ) -> None: """Call service to notify you see device.""" data: dict[str, Any] = { key: value for key, value in ( (ATTR_MAC, mac), (ATTR_DEV_ID, dev_id), (ATTR_HOST_NAME, host_name), (ATTR_LOCATION_NAME, location_name), (ATTR_GPS, gps), (ATTR_GPS_ACCURACY, gps_accuracy), (ATTR_BATTERY, battery), ) if value is not None } if attributes is not None: data[ATTR_ATTRIBUTES] = attributes hass.services.call(DOMAIN, SERVICE_SEE, data)
Set up the legacy integration.
def async_setup_integration(hass: HomeAssistant, config: ConfigType) -> None: """Set up the legacy integration.""" # The tracker is loaded in the _async_setup_integration task so # we create a future to avoid waiting on it here so that only # async_platform_discovered will have to wait in the rare event # a custom component still uses the legacy device tracker discovery. tracker_future: asyncio.Future[DeviceTracker] = hass.loop.create_future() async def async_platform_discovered( p_type: str, info: dict[str, Any] | None ) -> None: """Load a platform.""" platform = await async_create_platform_type(hass, config, p_type, {}) if platform is None or platform.type != PLATFORM_TYPE_LEGACY: return tracker = await tracker_future await platform.async_setup_legacy(hass, tracker, info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # # Legacy and platforms load in a non-awaited tracked task # to ensure device tracker setup can continue and config # entry integrations are not waiting for legacy device # tracker platforms to be set up. # hass.async_create_task( _async_setup_integration(hass, config, tracker_future), eager_start=True )
Load device names and attributes in a single executor job.
def _load_device_names_and_attributes( scanner: DeviceScanner, device_name_uses_executor: bool, extra_attributes_uses_executor: bool, seen: set[str], found_devices: list[str], ) -> tuple[dict[str, str | None], dict[str, dict[str, Any]]]: """Load device names and attributes in a single executor job.""" host_name_by_mac: dict[str, str | None] = {} extra_attributes_by_mac: dict[str, dict[str, Any]] = {} for mac in found_devices: if device_name_uses_executor and mac not in seen: host_name_by_mac[mac] = scanner.get_device_name(mac) if extra_attributes_uses_executor: try: extra_attributes_by_mac[mac] = scanner.get_extra_attributes(mac) except NotImplementedError: extra_attributes_by_mac[mac] = {} return host_name_by_mac, extra_attributes_by_mac
Set up the connect scanner-based platform to device tracker. This method must be run in the event loop.
def async_setup_scanner_platform( hass: HomeAssistant, config: ConfigType, scanner: DeviceScanner, async_see_device: Callable[..., Coroutine[None, None, None]], platform: str, ) -> None: """Set up the connect scanner-based platform to device tracker. This method must be run in the event loop. """ interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL) update_lock = asyncio.Lock() scanner.hass = hass # Initial scan of each mac we also tell about host name for config seen: set[str] = set() async def async_device_tracker_scan(now: datetime | None) -> None: """Handle interval matches.""" if update_lock.locked(): LOGGER.warning( ( "Updating device list from %s took longer than the scheduled " "scan interval %s" ), platform, interval, ) return async with update_lock: found_devices = await scanner.async_scan_devices() device_name_uses_executor = ( scanner.async_get_device_name.__func__ # type: ignore[attr-defined] is DeviceScanner.async_get_device_name ) extra_attributes_uses_executor = ( scanner.async_get_extra_attributes.__func__ # type: ignore[attr-defined] is DeviceScanner.async_get_extra_attributes ) host_name_by_mac: dict[str, str | None] = {} extra_attributes_by_mac: dict[str, dict[str, Any]] = {} if device_name_uses_executor or extra_attributes_uses_executor: ( host_name_by_mac, extra_attributes_by_mac, ) = await hass.async_add_executor_job( _load_device_names_and_attributes, scanner, device_name_uses_executor, extra_attributes_uses_executor, seen, found_devices, ) for mac in found_devices: if mac in seen: host_name = None else: host_name = host_name_by_mac.get( mac, await scanner.async_get_device_name(mac) ) seen.add(mac) try: extra_attributes = extra_attributes_by_mac.get( mac, await scanner.async_get_extra_attributes(mac) ) except NotImplementedError: extra_attributes = {} kwargs: dict[str, Any] = { "mac": mac, "host_name": host_name, "source_type": SourceType.ROUTER, "attributes": { "scanner": scanner.__class__.__name__, **extra_attributes, }, } zone_home = hass.states.get(ENTITY_ID_HOME) if zone_home is not None: kwargs["gps"] = [ zone_home.attributes[ATTR_LATITUDE], zone_home.attributes[ATTR_LONGITUDE], ] kwargs["gps_accuracy"] = 0 hass.async_create_task(async_see_device(**kwargs), eager_start=True) cancel_legacy_scan = async_track_time_interval( hass, async_device_tracker_scan, interval, name=f"device_tracker {platform} legacy scan", ) hass.async_create_task(async_device_tracker_scan(None), eager_start=True) @callback def _on_hass_stop(_: Event) -> None: """Cleanup when Home Assistant stops. Cancel the legacy scan. """ cancel_legacy_scan() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _on_hass_stop)
Add device to YAML configuration file.
def update_config(path: str, dev_id: str, device: Device) -> None: """Add device to YAML configuration file.""" with open(path, "a", encoding="utf8") as out: device_config = { device.dev_id: { ATTR_NAME: device.name, ATTR_MAC: device.mac, ATTR_ICON: device.icon, "picture": device.config_picture, "track": device.track, } } out.write("\n") out.write(dump(device_config))
Remove device from YAML configuration file.
def remove_device_from_config(hass: HomeAssistant, device_id: str) -> None: """Remove device from YAML configuration file.""" path = hass.config.path(YAML_DEVICES) devices = load_yaml_config_file(path) devices.pop(device_id) dumped = dump(devices) with open(path, "r+", encoding="utf8") as out: out.seek(0) out.truncate() out.write(dumped)
Return an 80px Gravatar for the given email address. Async friendly.
def get_gravatar_for_email(email: str) -> str: """Return an 80px Gravatar for the given email address. Async friendly. """ return ( "https://www.gravatar.com/avatar/" f"{hashlib.md5(email.encode('utf-8').lower()).hexdigest()}.jpg?s=80&d=wavatar" )
Return the state if any or a specified device is home.
def is_on(hass: HomeAssistant, entity_id: str) -> bool: """Return the state if any or a specified device is home.""" return hass.states.is_state(entity_id, STATE_HOME)
Configure mydevolo.
def configure_mydevolo(conf: dict[str, Any] | MappingProxyType[str, Any]) -> Mydevolo: """Configure mydevolo.""" mydevolo = Mydevolo() mydevolo.user = conf[CONF_USERNAME] mydevolo.password = conf[CONF_PASSWORD] mydevolo.url = conf.get(CONF_MYDEVOLO, DEFAULT_MYDEVOLO) return mydevolo
Check, if device is attached to the router.
def _is_connected_to_router(entity: DevoloBinarySensorEntity) -> bool: """Check, if device is attached to the router.""" return all( device.attached_to_router for device in entity.coordinator.data.devices if device.mac_address == entity.device.mac )
Assemble supported platforms.
def platforms(device: Device) -> set[Platform]: """Assemble supported platforms.""" supported_platforms = {Platform.BUTTON, Platform.SENSOR, Platform.SWITCH} if device.plcnet: supported_platforms.add(Platform.BINARY_SENSOR) if device.device and "wifi1" in device.device.features: supported_platforms.add(Platform.DEVICE_TRACKER) supported_platforms.add(Platform.IMAGE) if device.device and "update" in device.device.features: supported_platforms.add(Platform.UPDATE) return supported_platforms
Update device registry with new firmware version.
def update_sw_version(device_registry: dr.DeviceRegistry, device: Device) -> None: """Update device registry with new firmware version.""" if ( device_entry := device_registry.async_get_device( identifiers={(DOMAIN, str(device.serial_number))} ) ) and device_entry.sw_version != device.firmware_version: device_registry.async_update_device( device_id=device_entry.id, sw_version=device.firmware_version )
Index the integration matchers. We have three types of matchers: 1. Registered devices 2. Devices with no OUI - index by first char of lower() hostname 3. Devices with OUI - index by OUI
def async_index_integration_matchers( integration_matchers: list[DHCPMatcher], ) -> DhcpMatchers: """Index the integration matchers. We have three types of matchers: 1. Registered devices 2. Devices with no OUI - index by first char of lower() hostname 3. Devices with OUI - index by OUI """ registered_devices_domains: set[str] = set() no_oui_matchers: dict[str, list[DHCPMatcher]] = {} oui_matchers: dict[str, list[DHCPMatcher]] = {} for matcher in integration_matchers: domain = matcher["domain"] if REGISTERED_DEVICES in matcher: registered_devices_domains.add(domain) continue if mac_address := matcher.get(MAC_ADDRESS): oui_matchers.setdefault(mac_address[:6], []).append(matcher) continue if hostname := matcher.get(HOSTNAME): first_char = hostname[0].lower() no_oui_matchers.setdefault(first_char, []).append(matcher) return DhcpMatchers( registered_devices_domains=registered_devices_domains, no_oui_matchers=no_oui_matchers, oui_matchers=oui_matchers, )
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. DHCP 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. DHCP 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))
Redact sensitive data in a dict.
def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T: """Redact sensitive data in a dict.""" if not isinstance(data, (Mapping, list)): return data if isinstance(data, list): return cast(_T, [async_redact_data(val, to_redact) for val in data]) redacted = {**data} for key, value in redacted.items(): if value is None: continue if isinstance(value, str) and not value: continue if key in to_redact: redacted[key] = REDACTED elif isinstance(value, Mapping): redacted[key] = async_redact_data(value, to_redact) elif isinstance(value, list): redacted[key] = [async_redact_data(item, to_redact) for item in value] return cast(_T, redacted)
Register a diagnostics platform.
def _register_diagnostics_platform( hass: HomeAssistant, integration_domain: str, platform: DiagnosticsProtocol ) -> None: """Register a diagnostics platform.""" diagnostics_data: DiagnosticsData = hass.data[DOMAIN] diagnostics_data.platforms[integration_domain] = DiagnosticsPlatformData( getattr(platform, "async_get_config_entry_diagnostics", None), getattr(platform, "async_get_device_diagnostics", None), )
List all possible diagnostic handlers.
def handle_info( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """List all possible diagnostic handlers.""" diagnostics_data: DiagnosticsData = hass.data[DOMAIN] result = [ { "domain": domain, "handlers": { DiagnosticsType.CONFIG_ENTRY: info.config_entry_diagnostics is not None, DiagnosticsSubType.DEVICE: info.device_diagnostics is not None, }, } for domain, info in diagnostics_data.platforms.items() ] connection.send_result(msg["id"], result)
List all diagnostic handlers for a domain.
def handle_get( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """List all diagnostic handlers for a domain.""" domain = msg["domain"] diagnostics_data: DiagnosticsData = hass.data[DOMAIN] if (info := diagnostics_data.platforms.get(domain)) is None: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, "Domain not supported" ) return connection.send_result( msg["id"], { "domain": domain, "handlers": { DiagnosticsType.CONFIG_ENTRY: info.config_entry_diagnostics is not None, DiagnosticsSubType.DEVICE: info.device_diagnostics is not None, }, }, )
Return a response saying the error message.
def dialogflow_error_response(message, error): """Return a response saying the error message.""" api_version = get_api_version(message) if api_version is V1: parameters = message["result"]["parameters"] elif api_version is V2: parameters = message["queryResult"]["parameters"] dialogflow_response = DialogflowResponse(parameters, api_version) dialogflow_response.add_speech(error) return dialogflow_response.as_dict()
Get API version of Dialogflow message.
def get_api_version(message): """Get API version of Dialogflow message.""" if message.get("id") is not None: return V1 if message.get("responseId") is not None: return V2
Set up the Digital Ocean droplet sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Digital Ocean droplet sensor.""" if not (digital := hass.data.get(DATA_DIGITAL_OCEAN)): return droplets = config[CONF_DROPLETS] dev = [] for droplet in droplets: if (droplet_id := digital.get_droplet_id(droplet)) is None: _LOGGER.error("Droplet %s is not available", droplet) return dev.append(DigitalOceanBinarySensor(digital, droplet_id)) add_entities(dev, True)
Set up the Digital Ocean droplet switch.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Digital Ocean droplet switch.""" if not (digital := hass.data.get(DATA_DIGITAL_OCEAN)): return droplets = config[CONF_DROPLETS] dev = [] for droplet in droplets: if (droplet_id := digital.get_droplet_id(droplet)) is None: _LOGGER.error("Droplet %s is not available", droplet) return dev.append(DigitalOceanSwitch(digital, droplet_id)) add_entities(dev, True)
Set up the Digital Ocean component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Digital Ocean component.""" conf = config[DOMAIN] access_token = conf[CONF_ACCESS_TOKEN] digital = DigitalOcean(access_token) try: if not digital.manager.get_account(): _LOGGER.error("No account found for the given API token") return False except digitalocean.baseapi.DataReadError: _LOGGER.error("API token not valid for authentication") return False hass.data[DATA_DIGITAL_OCEAN] = digital return True
Set up the Discogs sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Discogs sensor.""" token = config[CONF_TOKEN] name = config[CONF_NAME] try: _discogs_client = discogs_client.Client(SERVER_SOFTWARE, user_token=token) discogs_data = { "user": _discogs_client.identity().name, "folders": _discogs_client.identity().collection_folders, "collection_count": _discogs_client.identity().num_collection, "wantlist_count": _discogs_client.identity().num_wantlist, } except discogs_client.exceptions.HTTPError: _LOGGER.error("API token is not valid") return monitored_conditions = config[CONF_MONITORED_CONDITIONS] entities = [ DiscogsSensor(discogs_data, name, description) for description in SENSOR_TYPES if description.key in monitored_conditions ] add_entities(entities, True)
Get a value from a Reading and divide with scale it.
def _get_and_scale(reading: Reading, key: str, scale: int) -> datetime | float | None: """Get a value from a Reading and divide with scale it.""" if (value := reading.values.get(key)) is not None: return value / scale return None
Register system health callbacks.
def async_register( hass: HomeAssistant, register: system_health.SystemHealthRegistration ) -> None: """Register system health callbacks.""" register.async_register_info(system_health_info)
Set up the Dlib Face detection platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Dlib Face detection platform.""" add_entities( DlibFaceDetectEntity(camera[CONF_ENTITY_ID], camera.get(CONF_NAME)) for camera in config[CONF_SOURCE] )
Set up the Dlib Face detection platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Dlib Face detection platform.""" add_entities( DlibFaceIdentifyEntity( camera[CONF_ENTITY_ID], config[CONF_FACES], camera.get(CONF_NAME), config[CONF_CONFIDENCE], ) for camera in config[CONF_SOURCE] )
Return True if this device should be ignored for discovery. These devices are supported better by other integrations, so don't bug the user about them. The user can add them if desired by via the user config flow, which will list all discovered but unconfigured devices.
def _is_ignored_device(discovery_info: ssdp.SsdpServiceInfo) -> bool: """Return True if this device should be ignored for discovery. These devices are supported better by other integrations, so don't bug the user about them. The user can add them if desired by via the user config flow, which will list all discovered but unconfigured devices. """ # Did the discovery trigger more than just this flow? if len(discovery_info.x_homeassistant_matching_domains) > 1: LOGGER.debug( "Ignoring device supported by multiple integrations: %s", discovery_info.x_homeassistant_matching_domains, ) return True # Is the root device not a DMR? if ( discovery_info.upnp.get(ssdp.ATTR_UPNP_DEVICE_TYPE) not in DmrDevice.DEVICE_TYPES ): return True # Special cases for devices with other discovery methods (e.g. mDNS), or # that advertise multiple unrelated (sent in separate discovery packets) # UPnP devices. manufacturer = (discovery_info.upnp.get(ssdp.ATTR_UPNP_MANUFACTURER) or "").lower() model = (discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME) or "").lower() if manufacturer.startswith("xbmc") or model == "kodi": # kodi return True if "philips" in manufacturer and "tv" in model: # philips_js # These TVs don't have a stable UDN, so also get discovered as a new # device every time they are turned on. return True if manufacturer.startswith("samsung") and "tv" in model: # samsungtv return True if manufacturer.startswith("lg") and "tv" in model: # webostv return True return False
Determine if discovery is a complete DLNA DMR device. Use the discovery_info instead of DmrDevice.is_profile_device to avoid contacting the device again.
def _is_dmr_device(discovery_info: ssdp.SsdpServiceInfo) -> bool: """Determine if discovery is a complete DLNA DMR device. Use the discovery_info instead of DmrDevice.is_profile_device to avoid contacting the device again. """ # Abort if the device doesn't support all services required for a DmrDevice. discovery_service_list = discovery_info.upnp.get(ssdp.ATTR_UPNP_SERVICE_LIST) if not discovery_service_list: return False services = discovery_service_list.get("service") if not services: discovery_service_ids: set[str] = set() elif isinstance(services, list): discovery_service_ids = {service.get("serviceId") for service in services} else: # Only one service defined (etree_to_dict failed to make a list) discovery_service_ids = {services.get("serviceId")} if not DmrDevice.SERVICE_IDS.issubset(discovery_service_ids): return False return True
Obtain this integration's domain data, creating it if needed.
def get_domain_data(hass: HomeAssistant) -> DlnaDmrData: """Obtain this integration's domain data, creating it if needed.""" if DOMAIN in hass.data: return cast(DlnaDmrData, hass.data[DOMAIN]) data = DlnaDmrData(hass) hass.data[DOMAIN] = data return data
Catch UpnpError errors.
def catch_request_errors( func: Callable[Concatenate[_DlnaDmrEntityT, _P], Awaitable[_R]], ) -> Callable[Concatenate[_DlnaDmrEntityT, _P], Coroutine[Any, Any, _R | None]]: """Catch UpnpError errors.""" @functools.wraps(func) async def wrapper( self: _DlnaDmrEntityT, *args: _P.args, **kwargs: _P.kwargs ) -> _R | None: """Catch UpnpError errors and check availability before and after request.""" if not self.available: _LOGGER.warning( "Device disappeared when trying to call service %s", func.__name__ ) return None try: return await func(self, *args, **kwargs) except UpnpError as err: self.check_available = True _LOGGER.error("Error during call %s: %r", func.__name__, err) return None return wrapper
Obtain this integration's domain data, creating it if needed.
def get_domain_data(hass: HomeAssistant) -> DlnaDmsData: """Obtain this integration's domain data, creating it if needed.""" if DOMAIN in hass.data: return cast(DlnaDmsData, hass.data[DOMAIN]) data = DlnaDmsData(hass) hass.data[DOMAIN] = data return data
Catch UpnpError errors.
def catch_request_errors( func: Callable[[_DlnaDmsDeviceMethod, str], Coroutine[Any, Any, _R]], ) -> Callable[[_DlnaDmsDeviceMethod, str], Coroutine[Any, Any, _R]]: """Catch UpnpError errors.""" @functools.wraps(func) async def wrapper(self: _DlnaDmsDeviceMethod, req_param: str) -> _R: """Catch UpnpError errors and check availability before and after request.""" if not self.available: LOGGER.warning("Device disappeared when trying to call %s", func.__name__) raise DeviceConnectionError("DMS is not connected") try: return await func(self, req_param) except UpnpActionError as err: LOGGER.debug("Server failure", exc_info=err) if err.error_code == ContentDirectoryErrorCode.NO_SUCH_OBJECT: LOGGER.debug("No such object: %s", req_param) raise ActionError(f"No such object: {req_param}") from err if err.error_code == ContentDirectoryErrorCode.INVALID_SEARCH_CRITERIA: LOGGER.debug("Invalid query: %s", req_param) raise ActionError(f"Invalid query: {req_param}") from err raise DeviceConnectionError(f"Server failure: {err!r}") from err except UpnpConnectionError as err: LOGGER.debug("Server disconnected", exc_info=err) await self.device_disconnect() raise DeviceConnectionError(f"Server disconnected: {err!r}") from err except UpnpError as err: LOGGER.debug("Server communication failure", exc_info=err) raise DeviceConnectionError( f"Server communication failure: {err!r}" ) from err return wrapper
Parse the media identifier component of a media-source URI.
def _parse_identifier(identifier: str | None) -> tuple[Action | None, str]: """Parse the media identifier component of a media-source URI.""" if not identifier: return None, "" if identifier.startswith(PATH_OBJECT_ID_FLAG): return Action.OBJECT, identifier[1:] if identifier.startswith(PATH_SEP): return Action.PATH, identifier[1:] if identifier.startswith(PATH_SEARCH_FLAG): return Action.SEARCH, identifier[1:] return Action.PATH, identifier
Determine if a resource can be streamed across a network.
def _resource_is_streaming(resource: didl_lite.Resource) -> bool: """Determine if a resource can be streamed across a network.""" # Err on the side of "True" if the protocol info is not available if not resource.protocol_info: return True protocol = resource.protocol_info.split(":")[0].lower() return protocol.lower() in STREAMABLE_PROTOCOLS
Return the MIME type of a resource, if specified.
def _resource_mime_type(resource: didl_lite.Resource) -> str | None: """Return the MIME type of a resource, if specified.""" # This is the contentFormat portion of the ProtocolInfo for an http-get stream if not resource.protocol_info: return None try: protocol, _, content_format, _ = resource.protocol_info.split(":", 3) except ValueError: return None if protocol.lower() in STREAMABLE_PROTOCOLS: return content_format return None
Escape string contents for DLNA search quoted values. See ContentDirectory:v4, section 4.1.2.
def _esc_quote(contents: str) -> str: """Escape string contents for DLNA search quoted values. See ContentDirectory:v4, section 4.1.2. """ return contents.replace("\\", "\\\\").replace('"', '\\"')
Parse the source_id and media identifier from a media source item.
def _parse_identifier(item: MediaSourceItem) -> tuple[str | None, str | None]: """Parse the source_id and media identifier from a media source item.""" if not item.identifier: return None, None source_id, _, media_id = item.identifier.partition(SOURCE_SEP) return source_id or None, media_id or None
Generate a unique source ID.
def generate_source_id(hass: HomeAssistant, name: str) -> str: """Generate a unique source ID.""" other_entries = hass.config_entries.async_entries(DOMAIN) other_source_ids: set[str] = { other_source_id for entry in other_entries if (other_source_id := entry.data.get(CONF_SOURCE_ID)) } source_id_base = slugify(name) if source_id_base not in other_source_ids: return source_id_base tries = 1 while (suggested_source_id := f"{source_id_base}_{tries}") in other_source_ids: tries += 1 return suggested_source_id
Set up is called when Home Assistant is loading our component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up is called when Home Assistant is loading our component.""" dominos = Dominos(hass, config) component = EntityComponent[DominosOrder](_LOGGER, DOMAIN, hass) hass.data[DOMAIN] = {} entities: list[DominosOrder] = [] conf = config[DOMAIN] hass.services.register( DOMAIN, "order", dominos.handle_order, vol.Schema( { vol.Required(ATTR_ORDER_ENTITY): cv.entity_ids, } ), ) if conf.get(ATTR_SHOW_MENU): hass.http.register_view(DominosProductListView(dominos)) for order_info in conf.get(ATTR_ORDERS): order = DominosOrder(order_info, dominos) entities.append(order) component.add_entities(entities) # Return boolean to indicate that initialization was successfully. return True
Set up the Doods client.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Doods client.""" url = config[CONF_URL] auth_key = config[CONF_AUTH_KEY] detector_name = config[CONF_DETECTOR] timeout = config[CONF_TIMEOUT] doods = PyDOODS(url, auth_key, timeout) response = doods.get_detectors() if not isinstance(response, dict): _LOGGER.warning("Could not connect to doods server: %s", url) return detector = {} for server_detector in response["detectors"]: if server_detector["name"] == detector_name: detector = server_detector break if not detector: _LOGGER.warning( "Detector %s is not supported by doods server %s", detector_name, url ) return add_entities( Doods( hass, camera[CONF_ENTITY_ID], camera.get(CONF_NAME), doods, detector, config, ) for camera in config[CONF_SOURCE] )
Verify we can connect to the device and return the status.
def _check_device(device: DoorBird) -> tuple[tuple[bool, int], dict[str, Any]]: """Verify we can connect to the device and return the status.""" return device.ready(), device.info()
Handle clearing favorites on device.
def _reset_device_favorites(door_station: ConfiguredDoorBird) -> None: """Handle clearing favorites on device.""" # Clear webhooks door_bird = door_station.device favorites: dict[str, list[str]] = door_bird.favorites() for favorite_type, favorite_ids in favorites.items(): for favorite_id in favorite_ids: door_bird.delete_favorite(favorite_type, favorite_id)
Describe logbook events.
def async_describe_events( hass: HomeAssistant, async_describe_event: Callable[ [str, str, Callable[[Event], dict[str, str | None]]], None ], ) -> None: """Describe logbook events.""" @callback def async_describe_logbook_event(event: Event) -> dict[str, str | None]: """Describe a logbook event.""" return { LOGBOOK_ENTRY_NAME: "Doorbird", LOGBOOK_ENTRY_MESSAGE: f"Event {event.event_type} was fired", # Database entries before Jun 25th 2020 will not have an entity ID LOGBOOK_ENTRY_ENTITY_ID: event.data.get(ATTR_ENTITY_ID), } domain_data: dict[str, DoorBirdData] = hass.data[DOMAIN] for data in domain_data.values(): for event in data.door_station.door_station_events: async_describe_event( DOMAIN, f"{DOMAIN}_{event}", async_describe_logbook_event )
Get the mac address depending on the device type.
def get_mac_address_from_door_station_info(door_station_info: dict[str, Any]) -> str: """Get the mac address depending on the device type.""" return door_station_info.get("PRIMARY_MAC_ADDR", door_station_info["WIFI_MAC_ADDR"])
Get door station by token.
def get_door_station_by_token( hass: HomeAssistant, token: str ) -> ConfiguredDoorBird | None: """Get door station by token.""" domain_data: dict[str, DoorBirdData] = hass.data[DOMAIN] for data in domain_data.values(): door_station = data.door_station if door_station.token == token: return door_station return None
Verify we can connect to the device and return the status.
def _init_door_bird_device(device: DoorBird) -> tuple[tuple[bool, int], dict[str, Any]]: """Verify we can connect to the device and return the status.""" return device.ready(), device.info()
Get the Dovado Router SMS notification service.
def get_service( hass: HomeAssistant, config: ConfigType, discovery_info: DiscoveryInfoType | None = None, ) -> DovadoSMSNotificationService: """Get the Dovado Router SMS notification service.""" return DovadoSMSNotificationService(hass.data[DOVADO_DOMAIN].client)
Set up the Dovado sensor platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Dovado sensor platform.""" dovado = hass.data[DOVADO_DOMAIN] sensors = config[CONF_SENSORS] entities = [ DovadoSensor(dovado, description) for description in SENSOR_TYPES if description.key in sensors ] add_entities(entities)