response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Set up the vlc platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the vlc platform.""" add_entities( [VlcDevice(config.get(CONF_NAME, DEFAULT_NAME), config.get(CONF_ARGUMENTS))] )
Return user form schema.
def user_form_schema(user_input: dict[str, Any] | None) -> vol.Schema: """Return user form schema.""" user_input = user_input or {} return vol.Schema( { vol.Required(CONF_PASSWORD): str, vol.Optional( CONF_HOST, default=user_input.get(CONF_HOST, "localhost") ): str, vol.Optional( CONF_PORT, default=user_input.get(CONF_PORT, DEFAULT_PORT) ): int, } )
Catch VLC errors.
def catch_vlc_errors( func: Callable[Concatenate[_VlcDeviceT, _P], Awaitable[None]], ) -> Callable[Concatenate[_VlcDeviceT, _P], Coroutine[Any, Any, None]]: """Catch VLC errors.""" @wraps(func) async def wrapper(self: _VlcDeviceT, *args: _P.args, **kwargs: _P.kwargs) -> None: """Catch VLC errors and modify availability.""" try: await func(self, *args, **kwargs) except CommandError as err: LOGGER.error("Command error: %s", err) except ConnectError as err: # pylint: disable=protected-access if self._attr_available: LOGGER.error("Connection error: %s", err) self._attr_available = False return wrapper
Return user form schema.
def user_form_schema(user_input: dict[str, Any] | None) -> vol.Schema: """Return user form schema.""" user_input = user_input or {} return vol.Schema( { vol.Optional(CONF_HOST, default=DEFAULT_HOST): str, vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): str, vol.Required(CONF_PASSWORD): str, } )
Add new tracker entities from the router.
def async_add_new_tracked_entities( coordinator: VodafoneStationRouter, async_add_entities: AddEntitiesCallback, tracked: set[str], ) -> None: """Add new tracker entities from the router.""" new_tracked = [] _LOGGER.debug("Adding device trackers entities") for mac, device_info in coordinator.data.devices.items(): if mac in tracked: continue _LOGGER.debug("New device tracker: %s", device_info.device.name) new_tracked.append(VodafoneStationTracker(coordinator, device_info)) tracked.add(mac) async_add_entities(new_tracked)
Calculate device uptime.
def _calculate_uptime(coordinator: VodafoneStationRouter, key: str) -> datetime: """Calculate device uptime.""" return coordinator.api.convert_uptime(coordinator.data.sensors[key])
Identify line type.
def _line_connection(coordinator: VodafoneStationRouter, key: str) -> str | None: """Identify line type.""" value = coordinator.data.sensors internet_ip = value[key] dsl_ip = value.get("dsl_ipaddr") fiber_ip = value.get("fiber_ipaddr") internet_key_ip = value.get("vf_internet_key_ip_addr") if internet_ip == dsl_ip: return LINE_TYPES[0] if internet_ip == fiber_ip: return LINE_TYPES[1] if internet_ip == internet_key_ip: return LINE_TYPES[2] return None
Plays a pre-recorded message if pipeline is misconfigured.
def make_protocol( hass: HomeAssistant, devices: VoIPDevices, call_info: CallInfo, rtcp_state: RtcpState | None = None, ) -> VoipDatagramProtocol: """Plays a pre-recorded message if pipeline is misconfigured.""" voip_device = devices.async_get_or_create(call_info) pipeline_id = pipeline_select.get_chosen_pipeline( hass, DOMAIN, voip_device.voip_id, ) try: pipeline: Pipeline | None = async_get_pipeline(hass, pipeline_id) except PipelineNotFound: pipeline = None if ( (pipeline is None) or (pipeline.stt_engine is None) or (pipeline.tts_engine is None) ): # Play pre-recorded message instead of failing return PreRecordMessageProtocol( hass, "problem.pcm", opus_payload_type=call_info.opus_payload_type, rtcp_state=rtcp_state, ) vad_sensitivity = pipeline_select.get_vad_sensitivity( hass, DOMAIN, voip_device.voip_id, ) # Pipeline is properly configured return PipelineRtpDatagramProtocol( hass, hass.config.language, voip_device, Context(user_id=devices.config_entry.data["user"]), opus_payload_type=call_info.opus_payload_type, silence_seconds=VadSensitivity.to_seconds(vad_sensitivity), rtcp_state=rtcp_state, )
Set up the Vultr subscription (server) binary sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Vultr subscription (server) binary sensor.""" vultr = hass.data[DATA_VULTR] subscription = config.get(CONF_SUBSCRIPTION) name = config.get(CONF_NAME) if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) return add_entities([VultrBinarySensor(vultr, subscription, name)], True)
Set up the Vultr subscription (server) sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Vultr subscription (server) sensor.""" vultr = hass.data[DATA_VULTR] subscription = config[CONF_SUBSCRIPTION] name = config[CONF_NAME] monitored_conditions = config[CONF_MONITORED_CONDITIONS] if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) return entities = [ VultrSensor(vultr, subscription, name, description) for description in SENSOR_TYPES if description.key in monitored_conditions ] add_entities(entities, True)
Set up the Vultr subscription switch.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Vultr subscription switch.""" vultr = hass.data[DATA_VULTR] subscription = config.get(CONF_SUBSCRIPTION) name = config.get(CONF_NAME) if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) return add_entities([VultrSwitch(vultr, subscription, name)], True)
Set up the Vultr component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Vultr component.""" api_key = config[DOMAIN].get(CONF_API_KEY) vultr = Vultr(api_key) try: vultr.update() except RuntimeError as ex: _LOGGER.error("Failed to make update API request because: %s", ex) persistent_notification.create( hass, f"Error: {ex}", title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID, ) return False hass.data[DATA_VULTR] = vultr return True
Set up the w800rf32 component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the w800rf32 component.""" # Declare the Handle event def handle_receive(event): """Handle received messages from w800rf32 gateway.""" # Log event if not event.device: return _LOGGER.debug("Receive W800rf32 event in handle_receive") # Get device_type from device_id in hass.data device_id = event.device.lower() signal = W800RF32_DEVICE.format(device_id) dispatcher_send(hass, signal, event) # device --> /dev/ttyUSB0 device = config[DOMAIN][CONF_DEVICE] w800_object = w800.Connect(device, None) def _start_w800rf32(event): w800_object.event_callback = handle_receive hass.bus.listen_once(EVENT_HOMEASSISTANT_START, _start_w800rf32) def _shutdown_w800rf32(event): """Close connection with w800rf32.""" w800_object.close_connection() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _shutdown_w800rf32) hass.data[DATA_W800RF32] = w800_object return True
Set up a wake on lan switch.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up a wake on lan switch.""" broadcast_address: str | None = config.get(CONF_BROADCAST_ADDRESS) broadcast_port: int | None = config.get(CONF_BROADCAST_PORT) host: str | None = config.get(CONF_HOST) mac_address: str = config[CONF_MAC] name: str = config[CONF_NAME] off_action: list[Any] | None = config.get(CONF_OFF_ACTION) add_entities( [ WolSwitch( hass, name, host, mac_address, off_action, broadcast_address, broadcast_port, ) ], host is not None, )
Return the entity id of the default engine.
def async_default_entity(hass: HomeAssistant) -> str | None: """Return the entity id of the default engine.""" return next(iter(hass.states.async_entity_ids(DOMAIN)), None)
Return wake word entity.
def async_get_wake_word_detection_entity( hass: HomeAssistant, entity_id: str ) -> WakeWordDetectionEntity | None: """Return wake word entity.""" component: EntityComponent[WakeWordDetectionEntity] = hass.data[DOMAIN] return component.get_entity(entity_id)
Authenticate with decorator using Wallbox API.
def _require_authentication( func: Callable[Concatenate[_WallboxCoordinatorT, _P], Any], ) -> Callable[Concatenate[_WallboxCoordinatorT, _P], Any]: """Authenticate with decorator using Wallbox API.""" def require_authentication( self: _WallboxCoordinatorT, *args: _P.args, **kwargs: _P.kwargs ) -> Any: """Authenticate using Wallbox API.""" try: self.authenticate() return func(self, *args, **kwargs) except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == HTTPStatus.FORBIDDEN: raise ConfigEntryAuthFailed from wallbox_connection_error raise ConnectionError from wallbox_connection_error return require_authentication
Return the minimum available value for charging current.
def min_charging_current_value(coordinator: WallboxCoordinator) -> float: """Return the minimum available value for charging current.""" if ( coordinator.data[CHARGER_DATA_KEY][CHARGER_PART_NUMBER_KEY][0:2] in BIDIRECTIONAL_MODEL_PREFIXES ): return cast(float, (coordinator.data[CHARGER_MAX_AVAILABLE_POWER_KEY] * -1)) return 6
Set up the Waterfurnace sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Waterfurnace sensor.""" if discovery_info is None: return client = hass.data[WF_DOMAIN] add_entities(WaterFurnaceSensor(client, description) for description in SENSORS)
Set up waterfurnace platform.
def setup(hass: HomeAssistant, base_config: ConfigType) -> bool: """Set up waterfurnace platform.""" config = base_config[DOMAIN] username = config[CONF_USERNAME] password = config[CONF_PASSWORD] wfconn = WaterFurnace(username, password) # NOTE(sdague): login will throw an exception if this doesn't # work, which will abort the setup. try: wfconn.login() except WFCredentialError: _LOGGER.error("Invalid credentials for waterfurnace login") return False hass.data[DOMAIN] = WaterFurnaceData(hass, wfconn) hass.data[DOMAIN].start() discovery.load_platform(hass, Platform.SENSOR, DOMAIN, {}, config) return True
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_ON, STATE_ECO, STATE_ELECTRIC, STATE_PERFORMANCE, STATE_HIGH_DEMAND, STATE_HEAT_PUMP, STATE_GAS, }, STATE_ON, STATE_OFF, )
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} ha_unit = hass.config.units.temperature_unit for attr_name in changed_attrs: if attr_name in [ATTR_OPERATION_MODE, ATTR_AWAY_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 ha_unit == UnitOfTemperature.FAHRENHEIT: absolute_change = 1.0 else: absolute_change = 0.5 if check_absolute_change(old_attr_value, new_attr_value, absolute_change): return True # no significant attribute change detected return False
Set up the Watson IoT Platform component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Watson IoT Platform component.""" conf = config[DOMAIN] include = conf[CONF_INCLUDE] exclude = conf[CONF_EXCLUDE] include_e = set(include[CONF_ENTITIES]) include_d = set(include[CONF_DOMAINS]) exclude_e = set(exclude[CONF_ENTITIES]) exclude_d = set(exclude[CONF_DOMAINS]) client_args = { "org": conf[CONF_ORG], "type": conf[CONF_TYPE], "id": conf[CONF_ID], "auth-method": "token", "auth-token": conf[CONF_TOKEN], } watson_gateway = Client(client_args) def event_to_json(event): """Add an event to the outgoing list.""" state = event.data.get("new_state") if ( state is None or state.state in (STATE_UNKNOWN, "", STATE_UNAVAILABLE) or state.entity_id in exclude_e or state.domain in exclude_d ): return if (include_e and state.entity_id not in include_e) or ( include_d and state.domain not in include_d ): return try: _state_as_value = float(state.state) except ValueError: _state_as_value = None if _state_as_value is None: try: _state_as_value = float(state_helper.state_as_number(state)) except ValueError: _state_as_value = None out_event = { "tags": {"domain": state.domain, "entity_id": state.object_id}, "time": event.time_fired.isoformat(), "fields": {"state": state.state}, } if _state_as_value is not None: out_event["fields"]["state_value"] = _state_as_value for key, value in state.attributes.items(): if key != "unit_of_measurement": # If the key is already in fields if key in out_event["fields"]: key = f"{key}_" # For each value we try to cast it as float # But if we cannot do it we store the value # as string try: out_event["fields"][key] = float(value) except (ValueError, TypeError): out_event["fields"][key] = str(value) return out_event instance = hass.data[DOMAIN] = WatsonIOTThread(hass, watson_gateway, event_to_json) instance.start() def shutdown(event): """Shut down the thread.""" instance.queue.put(None) instance.join() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, shutdown) return True
Set up IBM Watson TTS component.
def get_engine(hass, config, discovery_info=None): """Set up IBM Watson TTS component.""" authenticator = IAMAuthenticator(config[CONF_APIKEY]) service = TextToSpeechV1(authenticator) service.set_service_url(config[CONF_URL]) supported_languages = list({s[:5] for s in SUPPORTED_VOICES}) default_voice = config[CONF_VOICE] output_format = config[CONF_OUTPUT_FORMAT] service.set_default_headers({"x-watson-learning-opt-out": "true"}) if default_voice in DEPRECATED_VOICES: _LOGGER.warning( "Watson TTS voice %s is deprecated, it may be removed in the future", default_voice, ) return WatsonTTSProvider(service, supported_languages, default_voice, output_format)
Get a unique ID from a data payload.
def get_unique_id(data: dict[str, Any]) -> str: """Get a unique ID from a data payload.""" return f"{data[CONF_LATITUDE]}, {data[CONF_LONGITUDE]}"
Get the default options.
def default_options(hass: HomeAssistant) -> dict[str, str | bool]: """Get the default options.""" defaults = DEFAULT_OPTIONS.copy() if hass.config.units is US_CUSTOMARY_SYSTEM: defaults[CONF_UNITS] = IMPERIAL_UNITS return defaults
Describe group on off states.
def async_describe_on_off_states( hass: HomeAssistant, registry: "GroupIntegrationRegistry" ) -> None: """Describe group on off states.""" registry.exclude_domain(DOMAIN)
Translate a cardinal direction into azimuth angle (degrees).
def _cardinal_to_degrees(value: str | float | None) -> int | float | None: """Translate a cardinal direction into azimuth angle (degrees).""" if not isinstance(value, str): return value try: return float(360 / 16 * VALID_CARDINAL_DIRECTIONS.index(value.lower())) except ValueError: return None
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.""" # state changes are always significant if old_state != new_state: return True old_attrs_s = set( {k: v for k, v in old_attrs.items() if k in SIGNIFICANT_ATTRIBUTES}.items() ) new_attrs_s = set( {k: v for k, v in new_attrs.items() if k in SIGNIFICANT_ATTRIBUTES}.items() ) changed_attrs: set[str] = {item[0] for item in old_attrs_s ^ new_attrs_s} for attr_name in changed_attrs: old_attr_value = old_attrs.get(attr_name) new_attr_value = new_attrs.get(attr_name) absolute_change: float | None = None if attr_name == ATTR_WEATHER_WIND_BEARING: old_attr_value = _cardinal_to_degrees(old_attr_value) new_attr_value = _cardinal_to_degrees(new_attr_value) 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 attr_name in ( ATTR_WEATHER_APPARENT_TEMPERATURE, ATTR_WEATHER_DEW_POINT, ATTR_WEATHER_TEMPERATURE, ): if ( unit := new_attrs.get(ATTR_WEATHER_TEMPERATURE_UNIT) ) is not None and unit == UnitOfTemperature.FAHRENHEIT: absolute_change = 1.0 else: absolute_change = 0.5 if attr_name in ( ATTR_WEATHER_WIND_GUST_SPEED, ATTR_WEATHER_WIND_SPEED, ): if ( unit := new_attrs.get(ATTR_WEATHER_WIND_SPEED_UNIT) ) is None or unit in ( UnitOfSpeed.KILOMETERS_PER_HOUR, UnitOfSpeed.MILES_PER_HOUR, # 1km/h = 0.62mi/s UnitOfSpeed.FEET_PER_SECOND, # 1km/h = 0.91ft/s ): absolute_change = 1.0 elif unit == UnitOfSpeed.METERS_PER_SECOND: # 1km/h = 0.277m/s absolute_change = 0.5 if attr_name in ( ATTR_WEATHER_CLOUD_COVERAGE, # range 0-100% ATTR_WEATHER_HUMIDITY, # range 0-100% ATTR_WEATHER_OZONE, # range ~20-100ppm ATTR_WEATHER_VISIBILITY, # range 0-240km (150mi) ATTR_WEATHER_WIND_BEARING, # range 0-359° ): absolute_change = 1.0 if attr_name == ATTR_WEATHER_UV_INDEX: # range 1-11 absolute_change = 0.1 if attr_name == ATTR_WEATHER_PRESSURE: # local variation of around 100 hpa if (unit := new_attrs.get(ATTR_WEATHER_PRESSURE_UNIT)) is None or unit in ( UnitOfPressure.HPA, UnitOfPressure.MBAR, # 1hPa = 1mbar UnitOfPressure.MMHG, # 1hPa = 0.75mmHg ): absolute_change = 1.0 elif unit == UnitOfPressure.INHG: # 1hPa = 0.03inHg absolute_change = 0.05 # check for significant attribute value change if absolute_change is not None: if check_absolute_change(old_attr_value, new_attr_value, absolute_change): return True # no significant attribute change detected return False
Set up the weather websocket API.
def async_setup(hass: HomeAssistant) -> None: """Set up the weather websocket API.""" websocket_api.async_register_command(hass, ws_convertible_units) websocket_api.async_register_command(hass, ws_subscribe_forecast)
Return supported units for a device class.
def ws_convertible_units( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] ) -> None: """Return supported units for a device class.""" sorted_units = { key: sorted(units, key=str.casefold) for key, units in VALID_UNITS.items() } connection.send_result(msg["id"], {"units": sorted_units})
Convert temperature into preferred precision for display.
def round_temperature(temperature: float | None, precision: float) -> float | None: """Convert temperature into preferred precision for display.""" if temperature is None: return None # Round in the units appropriate if precision == PRECISION_HALVES: temperature = round(temperature * 2) / 2.0 elif precision == PRECISION_TENTHS: temperature = round(temperature, 1) # Integer as a fall back (PRECISION_WHOLE) else: temperature = round(temperature) return temperature
Raise error on attempt to get an unsupported forecast.
def raise_unsupported_forecast(entity_id: str, forecast_type: str) -> None: """Raise error on attempt to get an unsupported forecast.""" raise HomeAssistantError( f"Weather entity '{entity_id}' does not support '{forecast_type}' forecast" )
Construct a dispatch call from a ConfigEntry.
def format_dispatch_call(config_entry: ConfigEntry) -> str: """Construct a dispatch call from a ConfigEntry.""" return f"{config_entry.domain}_{config_entry.entry_id}_add"
Parse parse precipitation type.
def precipitation_raw_conversion_fn(raw_data: Enum): """Parse parse precipitation type.""" if raw_data.name.lower() == "unknown": return None return raw_data.name.lower()
Register a webhook.
def async_register( hass: HomeAssistant, domain: str, name: str, webhook_id: str, handler: Callable[[HomeAssistant, str, Request], Awaitable[Response | None]], *, local_only: bool | None = False, allowed_methods: Iterable[str] | None = None, ) -> None: """Register a webhook.""" handlers = hass.data.setdefault(DOMAIN, {}) if webhook_id in handlers: raise ValueError("Handler is already defined!") if allowed_methods is None: allowed_methods = DEFAULT_METHODS allowed_methods = frozenset(allowed_methods) if not allowed_methods.issubset(SUPPORTED_METHODS): raise ValueError( f"Unexpected method: {allowed_methods.difference(SUPPORTED_METHODS)}" ) handlers[webhook_id] = { "domain": domain, "name": name, "handler": handler, "local_only": local_only, "allowed_methods": allowed_methods, }
Remove a webhook.
def async_unregister(hass: HomeAssistant, webhook_id: str) -> None: """Remove a webhook.""" handlers = hass.data.setdefault(DOMAIN, {}) handlers.pop(webhook_id, None)
Generate a webhook_id.
def async_generate_id() -> str: """Generate a webhook_id.""" return secrets.token_hex(32)
Generate the full URL for a webhook_id.
def async_generate_url(hass: HomeAssistant, webhook_id: str) -> str: """Generate the full URL for a webhook_id.""" return ( f"{get_url(hass, prefer_external=True, allow_cloud=False)}" f"{async_generate_path(webhook_id)}" )
Generate the path component for a webhook_id.
def async_generate_path(webhook_id: str) -> str: """Generate the path component for a webhook_id.""" return URL_WEBHOOK_PATH.format(webhook_id=webhook_id)
Return a list of webhooks.
def websocket_list( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Return a list of webhooks.""" handlers = hass.data.setdefault(DOMAIN, {}) result = [ { "webhook_id": webhook_id, "domain": info["domain"], "name": info["name"], "local_only": info["local_only"], "allowed_methods": sorted(info["allowed_methods"]), } for webhook_id, info in handlers.items() ] connection.send_message(websocket_api.result_message(msg["id"], result))
Retrieve a Webmin instance and the base URL from config options.
def get_instance_from_options( hass: HomeAssistant, options: Mapping[str, Any] ) -> tuple[WebminInstance, URL]: """Retrieve a Webmin instance and the base URL from config options.""" base_url = URL.build( scheme="https" if options[CONF_SSL] else "http", user=options[CONF_USERNAME], password=options[CONF_PASSWORD], host=options[CONF_HOST], port=int(options[CONF_PORT]), ) return WebminInstance( session=async_create_clientsession( hass, verify_ssl=options[CONF_VERIFY_SSL], base_url=base_url, ) ), base_url
Return a sorted list of mac addresses.
def get_sorted_mac_addresses(data: dict[str, Any]) -> list[str]: """Return a sorted list of mac addresses.""" return sorted( [iface["ether"] for iface in data["active_interfaces"] if "ether" in iface] )
Get Device Entry from Device Registry by device ID. Raises ValueError if device ID is invalid.
def async_get_device_entry_by_device_id( hass: HomeAssistant, device_id: str ) -> DeviceEntry: """Get Device Entry from Device Registry by device ID. Raises ValueError if device ID is invalid. """ device_reg = dr.async_get(hass) if (device := device_reg.async_get(device_id)) is None: raise ValueError(f"Device {device_id} is not a valid {DOMAIN} device.") return device
Get device ID from an entity ID. Raises ValueError if entity or device ID is invalid.
def async_get_device_id_from_entity_id(hass: HomeAssistant, entity_id: str) -> str: """Get device ID from an entity ID. Raises ValueError if entity or device ID is invalid. """ ent_reg = er.async_get(hass) entity_entry = ent_reg.async_get(entity_id) if ( entity_entry is None or entity_entry.device_id is None or entity_entry.platform != DOMAIN ): raise ValueError(f"Entity {entity_id} is not a valid {DOMAIN} entity.") return entity_entry.device_id
Get WebOsClient from Device Registry by device entry. Raises ValueError if client is not found.
def async_get_client_by_device_entry( hass: HomeAssistant, device: DeviceEntry ) -> WebOsClient: """Get WebOsClient from Device Registry by device entry. Raises ValueError if client is not found. """ for config_entry_id in device.config_entries: if client := hass.data[DOMAIN][DATA_CONFIG_ENTRY].get(config_entry_id): break if not client: raise ValueError( f"Device {device.id} is not from an existing {DOMAIN} config entry" ) return client
Catch command exceptions.
def cmd( func: Callable[Concatenate[_T, _P], Awaitable[None]], ) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, None]]: """Catch command exceptions.""" @wraps(func) async def cmd_wrapper(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> None: """Wrap all command methods.""" try: await func(self, *args, **kwargs) except WEBOSTV_EXCEPTIONS as exc: if self.state != MediaPlayerState.OFF: raise HomeAssistantError( f"Error calling {func.__name__} on entity {self.entity_id}," f" state:{self.state}" ) from exc _LOGGER.warning( "Error calling %s on entity %s, state:%s, error: %r", func.__name__, self.entity_id, self.state, exc, ) return cmd_wrapper
Return trigger platform.
def _get_trigger_platform(config: ConfigType) -> TriggerProtocol: """Return trigger platform.""" platform_split = config[CONF_PLATFORM].split(".", maxsplit=1) if len(platform_split) < 2 or platform_split[1] not in TRIGGERS: raise ValueError( f"Unknown webOS Smart TV trigger platform {config[CONF_PLATFORM]}" ) return cast(TriggerProtocol, TRIGGERS[platform_split[1]])
Check and update stored client key if key has changed.
def update_client_key( hass: HomeAssistant, entry: ConfigEntry, client: WebOsClient ) -> None: """Check and update stored client key if key has changed.""" host = entry.data[CONF_HOST] key = entry.data[CONF_CLIENT_SECRET] if client.client_key != key: _LOGGER.debug("Updating client key for host %s", host) data = {CONF_HOST: host, CONF_CLIENT_SECRET: client.client_key} hass.config_entries.async_update_entry(entry, data=data)
Return data for a turn on trigger.
def async_get_turn_on_trigger(device_id: str) -> dict[str, str]: """Return data for a turn on trigger.""" return { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_TYPE: PLATFORM_TYPE, }
Return an auth_invalid message.
def auth_invalid_message(message: str) -> bytes: """Return an auth_invalid message.""" return json_bytes({"type": TYPE_AUTH_INVALID, "message": message})
Register commands.
def async_register_commands( hass: HomeAssistant, async_reg: Callable[[HomeAssistant, const.WebSocketCommandHandler], None], ) -> None: """Register commands.""" async_reg(hass, handle_call_service) async_reg(hass, handle_entity_source) async_reg(hass, handle_execute_script) async_reg(hass, handle_fire_event) async_reg(hass, handle_get_config) async_reg(hass, handle_get_services) async_reg(hass, handle_get_states) async_reg(hass, handle_manifest_get) async_reg(hass, handle_integration_setup_info) async_reg(hass, handle_manifest_list) async_reg(hass, handle_ping) async_reg(hass, handle_render_template) async_reg(hass, handle_subscribe_bootstrap_integrations) async_reg(hass, handle_subscribe_events) async_reg(hass, handle_subscribe_trigger) async_reg(hass, handle_test_condition) async_reg(hass, handle_unsubscribe_events) async_reg(hass, handle_validate_config) async_reg(hass, handle_subscribe_entities) async_reg(hass, handle_supported_features) async_reg(hass, handle_integration_descriptions)
Return a pong message.
def pong_message(iden: int) -> dict[str, Any]: """Return a pong message.""" return {"id": iden, "type": "pong"}
Forward state changed events to websocket.
def _forward_events_check_permissions( send_message: Callable[[bytes | str | dict[str, Any] | Callable[[], str]], None], user: User, msg_id: int, event: Event, ) -> None: """Forward state changed events to websocket.""" # We have to lookup the permissions again because the user might have # changed since the subscription was created. permissions = user.permissions if ( not user.is_admin and not permissions.access_all_entities(POLICY_READ) and not permissions.check_entity(event.data["entity_id"], POLICY_READ) ): return send_message(messages.cached_event_message(msg_id, event))
Forward events to websocket.
def _forward_events_unconditional( send_message: Callable[[bytes | str | dict[str, Any] | Callable[[], str]], None], msg_id: int, event: Event, ) -> None: """Forward events to websocket.""" send_message(messages.cached_event_message(msg_id, event))
Handle subscribe events command.
def handle_subscribe_events( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle subscribe events command.""" event_type = msg["event_type"] if event_type not in SUBSCRIBE_ALLOWLIST and not connection.user.is_admin: _LOGGER.error( "Refusing to allow %s to subscribe to event %s", connection.user.name, event_type, ) raise Unauthorized(user_id=connection.user.id) if event_type == EVENT_STATE_CHANGED: forward_events = partial( _forward_events_check_permissions, connection.send_message, connection.user, msg["id"], ) else: forward_events = partial( _forward_events_unconditional, connection.send_message, msg["id"] ) connection.subscriptions[msg["id"]] = hass.bus.async_listen( event_type, forward_events ) connection.send_result(msg["id"])
Handle subscribe bootstrap integrations command.
def handle_subscribe_bootstrap_integrations( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle subscribe bootstrap integrations command.""" @callback def forward_bootstrap_integrations(message: dict[str, Any]) -> None: """Forward bootstrap integrations to websocket.""" connection.send_message(messages.event_message(msg["id"], message)) connection.subscriptions[msg["id"]] = async_dispatcher_connect( hass, SIGNAL_BOOTSTRAP_INTEGRATIONS, forward_bootstrap_integrations ) connection.send_result(msg["id"])
Handle unsubscribe events command.
def handle_unsubscribe_events( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle unsubscribe events command.""" subscription = msg["subscription"] if subscription in connection.subscriptions: connection.subscriptions.pop(subscription)() connection.send_result(msg["id"]) else: connection.send_error(msg["id"], const.ERR_NOT_FOUND, "Subscription not found.")
Handle get states command.
def handle_get_states( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle get states command.""" states = _async_get_allowed_states(hass, connection) try: serialized_states = [state.as_dict_json for state in states] except (ValueError, TypeError): pass else: _send_handle_get_states_response(connection, msg["id"], serialized_states) return # If we can't serialize, we'll filter out unserializable states serialized_states = [] for state in states: try: serialized_states.append(state.as_dict_json) except (ValueError, TypeError): connection.logger.error( "Unable to serialize to JSON. Bad data found at %s", format_unserializable_data( find_paths_unserializable_data(state, dump=JSON_DUMP) ), ) _send_handle_get_states_response(connection, msg["id"], serialized_states)
Send handle get states response.
def _send_handle_get_states_response( connection: ActiveConnection, msg_id: int, serialized_states: list[bytes] ) -> None: """Send handle get states response.""" connection.send_message( construct_result_message( msg_id, b"".join((b"[", b",".join(serialized_states), b"]")) ) )
Forward entity state changed events to websocket.
def _forward_entity_changes( send_message: Callable[[str | bytes | dict[str, Any] | Callable[[], str]], None], entity_ids: set[str], user: User, msg_id: int, event: Event[EventStateChangedData], ) -> None: """Forward entity state changed events to websocket.""" entity_id = event.data["entity_id"] if entity_ids and entity_id not in entity_ids: return # We have to lookup the permissions again because the user might have # changed since the subscription was created. permissions = user.permissions if ( not user.is_admin and not permissions.access_all_entities(POLICY_READ) and not permissions.check_entity(event.data["entity_id"], POLICY_READ) ): return send_message(messages.cached_state_diff_message(msg_id, event))
Handle subscribe entities command.
def handle_subscribe_entities( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle subscribe entities command.""" entity_ids = set(msg.get("entity_ids", [])) # We must never await between sending the states and listening for # state changed events or we will introduce a race condition # where some states are missed states = _async_get_allowed_states(hass, connection) connection.subscriptions[msg["id"]] = hass.bus.async_listen( EVENT_STATE_CHANGED, partial( _forward_entity_changes, connection.send_message, entity_ids, connection.user, msg["id"], ), ) connection.send_result(msg["id"]) # JSON serialize here so we can recover if it blows up due to the # state machine containing unserializable data. This command is required # to succeed for the UI to show. try: serialized_states = [ state.as_compressed_state_json for state in states if not entity_ids or state.entity_id in entity_ids ] except (ValueError, TypeError): pass else: _send_handle_entities_init_response(connection, msg["id"], serialized_states) return serialized_states = [] for state in states: try: serialized_states.append(state.as_compressed_state_json) except (ValueError, TypeError): connection.logger.error( "Unable to serialize to JSON. Bad data found at %s", format_unserializable_data( find_paths_unserializable_data(state, dump=JSON_DUMP) ), ) _send_handle_entities_init_response(connection, msg["id"], serialized_states)
Send handle entities init response.
def _send_handle_entities_init_response( connection: ActiveConnection, msg_id: int, serialized_states: list[bytes] ) -> None: """Send handle entities init response.""" connection.send_message( b"".join( ( b'{"id":', str(msg_id).encode(), b',"type":"event","event":{"a":{', b",".join(serialized_states), b"}}}", ) ) )
Handle get config command.
def handle_get_config( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle get config command.""" connection.send_result(msg["id"], hass.config.as_dict())
Handle integrations command.
def handle_integration_setup_info( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle integrations command.""" connection.send_result( msg["id"], [ {"domain": integration, "seconds": seconds} for integration, seconds in async_get_setup_timings(hass).items() ], )
Handle ping command.
def handle_ping( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle ping command.""" connection.send_message(pong_message(msg["id"]))
Return a cached template.
def _cached_template(template_str: str, hass: HomeAssistant) -> template.Template: """Return a cached template.""" return template.Template(template_str, hass)
Prepare a websocket response from a dict of entity sources.
def _serialize_entity_sources( entity_infos: dict[str, entity.EntityInfo], ) -> dict[str, Any]: """Prepare a websocket response from a dict of entity sources.""" return { entity_id: {"domain": entity_info["domain"]} for entity_id, entity_info in entity_infos.items() }
Handle entity source command.
def handle_entity_source( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle entity source command.""" all_entity_sources = entity.entity_sources(hass) entity_perm = connection.user.permissions.check_entity if connection.user.permissions.access_all_entities(POLICY_READ): entity_sources = all_entity_sources else: entity_sources = { entity_id: source for entity_id, source in all_entity_sources.items() if entity_perm(entity_id, POLICY_READ) } connection.send_result(msg["id"], _serialize_entity_sources(entity_sources))
Handle fire event command.
def handle_fire_event( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle fire event command.""" context = connection.context(msg) hass.bus.async_fire(msg["event_type"], msg.get("event_data"), context=context) connection.send_result(msg["id"], {"context": context})
Handle setting supported features.
def handle_supported_features( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Handle setting supported features.""" connection.set_supported_features(msg["features"]) connection.send_result(msg["id"])
Decorate an async function to handle WebSocket API messages.
def async_response( func: const.AsyncWebSocketCommandHandler, ) -> const.WebSocketCommandHandler: """Decorate an async function to handle WebSocket API messages.""" task_name = f"websocket_api.async:{func.__name__}" @callback @wraps(func) def schedule_handler( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Schedule the handler.""" # As the webserver is now started before the start # event we do not want to block for websocket responders hass.async_create_background_task( _handle_async_response(func, hass, connection, msg), task_name, eager_start=True, ) return schedule_handler
Websocket decorator to require user to be an admin.
def require_admin(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler: """Websocket decorator to require user to be an admin.""" @wraps(func) def with_admin( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Check admin and call function.""" user = connection.user if user is None or not user.is_admin: raise Unauthorized func(hass, connection, msg) return with_admin
Decorate function validating login user exist in current WS connection. Will write out error message if not authenticated.
def ws_require_user( only_owner: bool = False, only_system_user: bool = False, allow_system_user: bool = True, only_active_user: bool = True, only_inactive_user: bool = False, only_supervisor: bool = False, ) -> Callable[[const.WebSocketCommandHandler], const.WebSocketCommandHandler]: """Decorate function validating login user exist in current WS connection. Will write out error message if not authenticated. """ def validator(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler: """Decorate func.""" @wraps(func) def check_current_user( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Check current user.""" def output_error(message_id: str, message: str) -> None: """Output error message.""" connection.send_message( messages.error_message(msg["id"], message_id, message) ) if only_owner and not connection.user.is_owner: output_error("only_owner", "Only allowed as owner") return if only_system_user and not connection.user.system_generated: output_error("only_system_user", "Only allowed as system user") return if not allow_system_user and connection.user.system_generated: output_error("not_system_user", "Not allowed as system user") return if only_active_user and not connection.user.is_active: output_error("only_active_user", "Only allowed as active user") return if only_inactive_user and connection.user.is_active: output_error("only_inactive_user", "Not allowed as active user") return if only_supervisor and connection.user.name != HASSIO_USER_NAME: output_error("only_supervisor", "Only allowed as Supervisor") return return func(hass, connection, msg) return check_current_user return validator
Tag a function as a websocket command. The schema must be either a dictionary where the keys are voluptuous markers, or a voluptuous.All schema where the first item is a voluptuous Mapping schema.
def websocket_command( schema: dict[vol.Marker, Any] | vol.All, ) -> Callable[[const.WebSocketCommandHandler], const.WebSocketCommandHandler]: """Tag a function as a websocket command. The schema must be either a dictionary where the keys are voluptuous markers, or a voluptuous.All schema where the first item is a voluptuous Mapping schema. """ if is_dict := isinstance(schema, dict): command = schema["type"] else: command = schema.validators[0].schema["type"] def decorate(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler: """Decorate ws command function.""" # pylint: disable=protected-access if is_dict and len(schema) == 1: # type only empty schema func._ws_schema = False # type: ignore[attr-defined] elif is_dict: func._ws_schema = messages.BASE_COMMAND_MESSAGE_SCHEMA.extend(schema) # type: ignore[attr-defined] else: if TYPE_CHECKING: assert not isinstance(schema, dict) extended_schema = vol.All( schema.validators[0].extend( messages.BASE_COMMAND_MESSAGE_SCHEMA.schema ), *schema.validators[1:], ) func._ws_schema = extended_schema # type: ignore[attr-defined] func._ws_command = command # type: ignore[attr-defined] return func return decorate
Return a success result message.
def result_message(iden: int, result: Any = None) -> dict[str, Any]: """Return a success result message.""" return {"id": iden, "type": const.TYPE_RESULT, "success": True, "result": result}
Construct a success result message JSON.
def construct_result_message(iden: int, payload: bytes) -> bytes: """Construct a success result message JSON.""" return b"".join( ( b'{"id":', str(iden).encode(), b',"type":"result","success":true,"result":', payload, b"}", ) )
Return an error result message.
def error_message( iden: int | None, code: str, message: str, translation_key: str | None = None, translation_domain: str | None = None, translation_placeholders: dict[str, Any] | None = None, ) -> dict[str, Any]: """Return an error result message.""" error_payload: dict[str, Any] = { "code": code, "message": message, } # In case `translation_key` is `None` we do not set it, nor the # `translation`_placeholders` and `translation_domain`. if translation_key is not None: error_payload["translation_key"] = translation_key error_payload["translation_placeholders"] = translation_placeholders error_payload["translation_domain"] = translation_domain return { "id": iden, **BASE_ERROR_MESSAGE, "error": error_payload, }
Return an event message.
def event_message(iden: int, event: Any) -> dict[str, Any]: """Return an event message.""" return {"id": iden, "type": "event", "event": event}
Return an event message. Serialize to json once per message. Since we can have many clients connected that are all getting many of the same events (mostly state changed) we can avoid serializing the same data for each connection.
def cached_event_message(iden: int, event: Event) -> bytes: """Return an event message. Serialize to json once per message. Since we can have many clients connected that are all getting many of the same events (mostly state changed) we can avoid serializing the same data for each connection. """ return b"".join( ( _partial_cached_event_message(event)[:-1], b',"id":', str(iden).encode(), b"}", ) )
Cache and serialize the event to json. The message is constructed without the id which appended in cached_event_message.
def _partial_cached_event_message(event: Event) -> bytes: """Cache and serialize the event to json. The message is constructed without the id which appended in cached_event_message. """ return ( _message_to_json_bytes_or_none({"type": "event", "event": event.json_fragment}) or INVALID_JSON_PARTIAL_MESSAGE )
Return an event message. Serialize to json once per message. Since we can have many clients connected that are all getting many of the same events (mostly state changed) we can avoid serializing the same data for each connection.
def cached_state_diff_message(iden: int, event: Event[EventStateChangedData]) -> bytes: """Return an event message. Serialize to json once per message. Since we can have many clients connected that are all getting many of the same events (mostly state changed) we can avoid serializing the same data for each connection. """ return b"".join( ( _partial_cached_state_diff_message(event)[:-1], b',"id":', str(iden).encode(), b"}", ) )
Cache and serialize the event to json. The message is constructed without the id which will be appended in cached_state_diff_message
def _partial_cached_state_diff_message(event: Event[EventStateChangedData]) -> bytes: """Cache and serialize the event to json. The message is constructed without the id which will be appended in cached_state_diff_message """ return ( _message_to_json_bytes_or_none( {"type": "event", "event": _state_diff_event(event)} ) or INVALID_JSON_PARTIAL_MESSAGE )
Convert a state_changed event to the minimal version. State update example { "a": {entity_id: compressed_state,…} "c": {entity_id: diff,…} "r": [entity_id,…] }
def _state_diff_event(event: Event[EventStateChangedData]) -> dict: """Convert a state_changed event to the minimal version. State update example { "a": {entity_id: compressed_state,…} "c": {entity_id: diff,…} "r": [entity_id,…] } """ if (event_new_state := event.data["new_state"]) is None: return {ENTITY_EVENT_REMOVE: [event.data["entity_id"]]} if (event_old_state := event.data["old_state"]) is None: return { ENTITY_EVENT_ADD: { event_new_state.entity_id: event_new_state.as_compressed_state } } return _state_diff(event_old_state, event_new_state)
Create a diff dict that can be used to overlay changes.
def _state_diff( old_state: State, new_state: State ) -> dict[str, dict[str, dict[str, dict[str, str | list[str]]]]]: """Create a diff dict that can be used to overlay changes.""" additions: dict[str, Any] = {} diff: dict[str, dict[str, Any]] = {STATE_DIFF_ADDITIONS: additions} new_state_context = new_state.context old_state_context = old_state.context if old_state.state != new_state.state: additions[COMPRESSED_STATE_STATE] = new_state.state if old_state.last_changed != new_state.last_changed: additions[COMPRESSED_STATE_LAST_CHANGED] = new_state.last_changed_timestamp elif old_state.last_updated != new_state.last_updated: additions[COMPRESSED_STATE_LAST_UPDATED] = new_state.last_updated_timestamp if old_state_context.parent_id != new_state_context.parent_id: additions[COMPRESSED_STATE_CONTEXT] = {"parent_id": new_state_context.parent_id} if old_state_context.user_id != new_state_context.user_id: if COMPRESSED_STATE_CONTEXT in additions: additions[COMPRESSED_STATE_CONTEXT]["user_id"] = new_state_context.user_id else: additions[COMPRESSED_STATE_CONTEXT] = {"user_id": new_state_context.user_id} if old_state_context.id != new_state_context.id: if COMPRESSED_STATE_CONTEXT in additions: additions[COMPRESSED_STATE_CONTEXT]["id"] = new_state_context.id else: additions[COMPRESSED_STATE_CONTEXT] = new_state_context.id if (old_attributes := old_state.attributes) != ( new_attributes := new_state.attributes ): for key, value in new_attributes.items(): if old_attributes.get(key) != value: additions.setdefault(COMPRESSED_STATE_ATTRIBUTES, {})[key] = value if removed := old_attributes.keys() - new_attributes: # sets are not JSON serializable by default so we convert to list # here if there are any values to avoid jumping into the json_encoder_default # for every state diff with a removed attribute diff[STATE_DIFF_REMOVALS] = {COMPRESSED_STATE_ATTRIBUTES: list(removed)} return {ENTITY_EVENT_CHANGE: {new_state.entity_id: diff}}
Serialize a websocket message to json or return None.
def _message_to_json_bytes_or_none(message: dict[str, Any]) -> bytes | None: """Serialize a websocket message to json or return None.""" try: return json_bytes(message) except (ValueError, TypeError): _LOGGER.error( "Unable to serialize to JSON. Bad data found at %s", format_unserializable_data( find_paths_unserializable_data(message, dump=JSON_DUMP) ), ) return None
Serialize a websocket message to json or return an error.
def message_to_json_bytes(message: dict[str, Any]) -> bytes: """Serialize a websocket message to json or return an error.""" return _message_to_json_bytes_or_none(message) or json_bytes( error_message( message["id"], const.ERR_UNKNOWN_ERROR, "Invalid JSON in response" ) )
Describe a request.
def describe_request(request: web.Request) -> str: """Describe a request.""" description = f"from {request.remote}" if user_agent := request.headers.get("user-agent"): description += f" ({user_agent})" return description
Register a websocket command.
def async_register_command( hass: HomeAssistant, command_or_handler: str | const.WebSocketCommandHandler, handler: const.WebSocketCommandHandler | None = None, schema: vol.Schema | None = None, ) -> None: """Register a websocket command.""" # pylint: disable=protected-access if handler is None: handler = cast(const.WebSocketCommandHandler, command_or_handler) command = handler._ws_command # type: ignore[attr-defined] schema = handler._ws_schema # type: ignore[attr-defined] else: command = command_or_handler if (handlers := hass.data.get(DOMAIN)) is None: handlers = hass.data[DOMAIN] = {} handlers[command] = (handler, schema)
Return the Voluptuous schema for the Options instance. All values are optional. The default value is set to the current value and the type hint is set to the value of the field type annotation.
def _schema_for_options(options: Options) -> vol.Schema: """Return the Voluptuous schema for the Options instance. All values are optional. The default value is set to the current value and the type hint is set to the value of the field type annotation. """ return vol.Schema( { vol.Optional( field.name, default=getattr(options, field.name) ): get_type_hints(options)[field.name] for field in fields(options) } )
Set up a WeMo link.
def async_setup_bridge( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, coordinator: DeviceCoordinator, ) -> None: """Set up a WeMo link.""" known_light_ids = set() @callback def async_update_lights() -> None: """Check to see if the bridge has any new lights.""" new_lights = [] bridge = cast(Bridge, coordinator.wemo) for light_id, light in bridge.Lights.items(): if light_id not in known_light_ids: known_light_ids.add(light_id) new_lights.append(WemoLight(coordinator, light)) async_add_entities(new_lights) async_update_lights() config_entry.async_on_unload(coordinator.async_add_listener(async_update_lights))
Fetch WemoData with proper typing.
def async_wemo_data(hass: HomeAssistant) -> WemoData: """Fetch WemoData with proper typing.""" return cast(WemoData, hass.data[DOMAIN])
Create device information. Modify if special device.
def _create_device_info(wemo: WeMoDevice) -> DeviceInfo: """Create device information. Modify if special device.""" _dev_info = _device_info(wemo) if wemo.model_name.lower() == "dli emulated belkin socket": _dev_info[ATTR_CONFIGURATION_URL] = f"http://{wemo.host}" _dev_info[ATTR_IDENTIFIERS] = {(DOMAIN, wemo.serial_number[:-1])} return _dev_info
Return DeviceCoordinator for device_id.
def async_get_coordinator(hass: HomeAssistant, device_id: str) -> DeviceCoordinator: """Return DeviceCoordinator for device_id.""" return _async_coordinators(hass)[device_id]
Validate that provided value is either just host or host:port. Returns (host, None) or (host, port) respectively.
def coerce_host_port(value: str) -> HostPortTuple: """Validate that provided value is either just host or host:port. Returns (host, None) or (host, port) respectively. """ host, _, port_str = value.partition(":") if not host: raise vol.Invalid("host cannot be empty") port = cv.port(port_str) if port_str else None return host, port
Handle a static config.
def validate_static_config(host: str, port: int | None) -> pywemo.WeMoDevice | None: """Handle a static config.""" url = pywemo.setup_url_for_address(host, port) if not url: _LOGGER.error( "Unable to get description url for WeMo at: %s", f"{host}:{port}" if port else host, ) return None try: device = pywemo.discovery.device_from_description(url) except ( pywemo.exceptions.ActionException, pywemo.exceptions.HTTPException, ) as err: _LOGGER.error("Unable to access WeMo at %s (%s)", url, err) return None return device
Determine correct states for a washer.
def washer_state(washer: WasherDryer) -> str | None: """Determine correct states for a washer.""" if washer.get_attribute("Cavity_OpStatusDoorOpen") == "1": return DOOR_OPEN machine_state = washer.get_machine_state() if machine_state == MachineState.RunningMainCycle: for func, cycle_name in CYCLE_FUNC: if func(washer): return cycle_name return MACHINE_STATE.get(machine_state)
Calculate days left until domain expires.
def _days_until_expiration(domain: Domain) -> int | None: """Calculate days left until domain expires.""" if domain.expiration_date is None: return None # We need to cast here, as (unlike Pyright) mypy isn't able to determine the type. return cast( int, (domain.expiration_date - dt_util.utcnow().replace(tzinfo=None)).days, )
Calculate days left until domain expires.
def _ensure_timezone(timestamp: datetime | None) -> datetime | None: """Calculate days left until domain expires.""" if timestamp is None: return None # If timezone info isn't provided by the Whois, assume UTC. if timestamp.tzinfo is None: return timestamp.replace(tzinfo=UTC) return timestamp
Generate a unique string for the entity.
def generate_unique_id(device, metric): """Generate a unique string for the entity.""" return f"{device.mac_address.replace(':', '')}-{metric.name}"