response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Return all automations that reference the area.
def automations_with_area(hass: HomeAssistant, area_id: str) -> list[str]: """Return all automations that reference the area.""" return _automations_with_x(hass, area_id, "referenced_areas")
Return all areas in an automation.
def areas_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]: """Return all areas in an automation.""" return _x_in_automation(hass, entity_id, "referenced_areas")
Return all automations that reference the floor.
def automations_with_floor(hass: HomeAssistant, floor_id: str) -> list[str]: """Return all automations that reference the floor.""" return _automations_with_x(hass, floor_id, "referenced_floors")
Return all floors in an automation.
def floors_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]: """Return all floors in an automation.""" return _x_in_automation(hass, entity_id, "referenced_floors")
Return all automations that reference the label.
def automations_with_label(hass: HomeAssistant, label_id: str) -> list[str]: """Return all automations that reference the label.""" return _automations_with_x(hass, label_id, "referenced_labels")
Return all labels in an automation.
def labels_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]: """Return all labels in an automation.""" return _x_in_automation(hass, entity_id, "referenced_labels")
Return all automations that reference the blueprint.
def automations_with_blueprint(hass: HomeAssistant, blueprint_path: str) -> list[str]: """Return all automations that reference the blueprint.""" if DOMAIN not in hass.data: return [] component: EntityComponent[BaseAutomationEntity] = hass.data[DOMAIN] return [ automation_entity.entity_id for automation_entity in component.entities if automation_entity.referenced_blueprint == blueprint_path ]
Return the blueprint the automation is based on or None.
def blueprint_in_automation(hass: HomeAssistant, entity_id: str) -> str | None: """Return the blueprint the automation is based on or None.""" if DOMAIN not in hass.data: return None component: EntityComponent[BaseAutomationEntity] = hass.data[DOMAIN] if (automation_entity := component.get_entity(entity_id)) is None: return None return automation_entity.referenced_blueprint
Return the configured name of an automation.
def _automation_name(automation_config: AutomationEntityConfig) -> str: """Return the configured name of an automation.""" config_block = automation_config.config_block list_no = automation_config.list_no return config_block.get(CONF_ALIAS) or f"{DOMAIN} {list_no}"
Return False if an automation's config has been changed.
def _automation_matches_config( automation: BaseAutomationEntity | None, config: AutomationEntityConfig | None ) -> bool: """Return False if an automation's config has been changed.""" if not automation: return False if not config: return False name = _automation_name(config) return automation.name == name and automation.raw_config == config.raw_config
Extract devices from a trigger config.
def _trigger_extract_devices(trigger_conf: dict) -> list[str]: """Extract devices from a trigger config.""" if trigger_conf[CONF_PLATFORM] == "device": return [trigger_conf[CONF_DEVICE_ID]] if ( trigger_conf[CONF_PLATFORM] == "event" and CONF_EVENT_DATA in trigger_conf and CONF_DEVICE_ID in trigger_conf[CONF_EVENT_DATA] and isinstance(trigger_conf[CONF_EVENT_DATA][CONF_DEVICE_ID], str) ): return [trigger_conf[CONF_EVENT_DATA][CONF_DEVICE_ID]] if trigger_conf[CONF_PLATFORM] == "tag" and CONF_DEVICE_ID in trigger_conf: return trigger_conf[CONF_DEVICE_ID] # type: ignore[no-any-return] return []
Extract entities from a trigger config.
def _trigger_extract_entities(trigger_conf: dict) -> list[str]: """Extract entities from a trigger config.""" if trigger_conf[CONF_PLATFORM] in ("state", "numeric_state"): return trigger_conf[CONF_ENTITY_ID] # type: ignore[no-any-return] if trigger_conf[CONF_PLATFORM] == "calendar": return [trigger_conf[CONF_ENTITY_ID]] if trigger_conf[CONF_PLATFORM] == "zone": return trigger_conf[CONF_ENTITY_ID] + [trigger_conf[CONF_ZONE]] # type: ignore[no-any-return] if trigger_conf[CONF_PLATFORM] == "geo_location": return [trigger_conf[CONF_ZONE]] if trigger_conf[CONF_PLATFORM] == "sun": return ["sun.sun"] if ( trigger_conf[CONF_PLATFORM] == "event" and CONF_EVENT_DATA in trigger_conf and CONF_ENTITY_ID in trigger_conf[CONF_EVENT_DATA] and isinstance(trigger_conf[CONF_EVENT_DATA][CONF_ENTITY_ID], str) and valid_entity_id(trigger_conf[CONF_EVENT_DATA][CONF_ENTITY_ID]) ): return [trigger_conf[CONF_EVENT_DATA][CONF_ENTITY_ID]] return []
Get automation config.
def websocket_config( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Get automation config.""" component: EntityComponent[BaseAutomationEntity] = hass.data[DOMAIN] automation = component.get_entity(msg["entity_id"]) if automation is None: connection.send_error( msg["id"], websocket_api.const.ERR_NOT_FOUND, "Entity not found" ) return connection.send_result( msg["id"], { "config": automation.raw_config, }, )
Set up the Avea platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Avea platform.""" try: nearby_bulbs = avea.discover_avea_bulbs() for bulb in nearby_bulbs: bulb.get_name() bulb.get_brightness() except OSError as err: raise PlatformNotReady from err add_entities(AveaLight(bulb) for bulb in nearby_bulbs)
Set up an Avion switch.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up an Avion switch.""" avion = importlib.import_module("avion") lights = [ AvionLight( avion.Avion( mac=address, passphrase=device_config[CONF_API_KEY], name=device_config.get(CONF_NAME), object_id=device_config.get(CONF_ID), connect=False, ) ) for address, device_config in config[CONF_DEVICES].items() ] if CONF_USERNAME in config and CONF_PASSWORD in config: lights.extend( AvionLight(device) for device in avion.get_devices( config[CONF_USERNAME], config[CONF_PASSWORD] ) ) add_entities(lights)
Make sure event ID is int.
def event_id_is_int(event_id: str) -> bool: """Make sure event ID is int.""" try: _ = int(event_id) except ValueError: return False return True
Validate event ID is int.
def guard_suite_supported_fn(hub: AxisHub, event: Event) -> bool: """Validate event ID is int.""" _, _, profile_id = event.id.partition("Profile") return event_id_is_int(profile_id)
Validate event ID is int.
def object_analytics_supported_fn(hub: AxisHub, event: Event) -> bool: """Validate event ID is int.""" _, _, profile_id = event.id.partition("Scenario") return event_id_is_int(profile_id)
Get guard suite item name.
def guard_suite_name_fn( handler: FenceGuardHandler | LoiteringGuardHandler | MotionGuardHandler | Vmd4Handler, event: Event, event_type: str, ) -> str: """Get guard suite item name.""" if handler.initialized and (profiles := handler["0"].profiles): for profile_id, profile in profiles.items(): camera_id = profile.camera if event.id == f"Camera{camera_id}Profile{profile_id}": return f"{event_type} {profile.name}" return ""
Fence guard name.
def fence_guard_name_fn(hub: AxisHub, event: Event) -> str: """Fence guard name.""" return guard_suite_name_fn(hub.api.vapix.fence_guard, event, "Fence Guard")
Loitering guard name.
def loitering_guard_name_fn(hub: AxisHub, event: Event) -> str: """Loitering guard name.""" return guard_suite_name_fn(hub.api.vapix.loitering_guard, event, "Loitering Guard")
Motion guard name.
def motion_guard_name_fn(hub: AxisHub, event: Event) -> str: """Motion guard name.""" return guard_suite_name_fn(hub.api.vapix.motion_guard, event, "Motion Guard")
Motion detection 4 name.
def motion_detection_4_name_fn(hub: AxisHub, event: Event) -> str: """Motion detection 4 name.""" return guard_suite_name_fn(hub.api.vapix.vmd4, event, "VMD4")
Get object analytics name.
def object_analytics_name_fn(hub: AxisHub, event: Event) -> str: """Get object analytics name.""" if hub.api.vapix.object_analytics.initialized and ( scenarios := hub.api.vapix.object_analytics["0"].scenarios ): for scenario_id, scenario in scenarios.items(): device_id = scenario.devices[0]["id"] if event.id == f"Device{device_id}Scenario{scenario_id}": return f"Object Analytics {scenario.name}" return ""
Provide Axis light entity name.
def light_name_fn(hub: AxisHub, event: Event) -> str: """Provide Axis light entity name.""" event_type = TOPIC_TO_EVENT_TYPE[event.topic_base] light_id = f"led{event.id}" light_type = hub.api.vapix.light_control[light_id].light_type return f"{light_type} {event_type} {event.id}"
Get the notification service.
def get_service( hass: HomeAssistant, config: ConfigType, discovery_info: DiscoveryInfoType | None = None, ) -> ServiceBusNotificationService | None: """Get the notification service.""" connection_string: str = config[CONF_CONNECTION_STRING] queue_name: str | None = config.get(CONF_QUEUE_NAME) topic_name: str | None = config.get(CONF_TOPIC_NAME) # Library can do synchronous IO when creating the clients. # Passes in loop here, but can't run setup on the event loop. servicebus = ServiceBusClient.from_connection_string( connection_string, loop=hass.loop ) client: ServiceBusSender | None = None try: if queue_name: client = servicebus.get_queue_sender(queue_name) elif topic_name: client = servicebus.get_topic_sender(topic_name) except (ServiceBusConnectionError, MessagingEntityNotFoundError) as err: _LOGGER.error( "Connection error while creating client for queue/topic '%s'. %s", queue_name or topic_name, err, ) return None return ServiceBusNotificationService(client) if client else None
Register the http views.
def async_register_http_views(hass: HomeAssistant) -> None: """Register the http views.""" hass.http.register_view(DownloadBackupView)
Generate a backup slug.
def _generate_slug(date: str, name: str) -> str: """Generate a backup slug.""" return hashlib.sha1(f"{date} - {name}".lower().encode()).hexdigest()[:8]
Register websocket commands.
def async_register_websocket_handlers(hass: HomeAssistant, with_hassio: bool) -> None: """Register websocket commands.""" if with_hassio: websocket_api.async_register_command(hass, handle_backup_end) websocket_api.async_register_command(hass, handle_backup_start) return websocket_api.async_register_command(hass, handle_info) websocket_api.async_register_command(hass, handle_create) websocket_api.async_register_command(hass, handle_remove)
Set up Baidu TTS component.
def get_engine(hass, config, discovery_info=None): """Set up Baidu TTS component.""" return BaiduTTSProvider(hass, config)
Get the device.
def get_device(hass: HomeAssistant | None, unique_id: str) -> DeviceEntry | None: """Get the device.""" if not isinstance(hass, HomeAssistant): return None device_registry = dr.async_get(hass) device = device_registry.async_get_device({(DOMAIN, unique_id)}) assert device return device
Update probability using Bayes' rule.
def update_probability( prior: float, prob_given_true: float, prob_given_false: float ) -> float: """Update probability using Bayes' rule.""" numerator = prob_given_true * prior denominator = numerator + prob_given_false * (1 - prior) return numerator / denominator
If there are mirrored entries, the user is probably using a workaround for a patched bug.
def raise_mirrored_entries( hass: HomeAssistant, observations: list[Observation], text: str = "" ) -> None: """If there are mirrored entries, the user is probably using a workaround for a patched bug.""" if len(observations) != 2: return if observations[0].is_mirror(observations[1]): ir.async_create_issue( hass, DOMAIN, "mirrored_entry/" + text, breaks_in_ha_version="2022.10.0", is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="manual_migration", translation_placeholders={"entity": text}, learn_more_url="https://github.com/home-assistant/core/pull/67631", )
In previous 2022.9 and earlier, prob_given_false was optional and had a default version.
def raise_no_prob_given_false(hass: HomeAssistant, text: str) -> None: """In previous 2022.9 and earlier, prob_given_false was optional and had a default version.""" ir.async_create_issue( hass, DOMAIN, f"no_prob_given_false/{text}", breaks_in_ha_version="2022.10.0", is_fixable=False, severity=ir.IssueSeverity.ERROR, translation_key="no_prob_given_false", translation_placeholders={"entity": text}, learn_more_url="https://github.com/home-assistant/core/pull/67631", )
Validate the configuration and return a Bbox scanner.
def get_scanner(hass: HomeAssistant, config: ConfigType) -> BboxDeviceScanner | None: """Validate the configuration and return a Bbox scanner.""" scanner = BboxDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
Set up the Bbox sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Bbox sensor.""" # Create a data fetcher to support all of the configured sensors. Then make # the first call to init the data. try: bbox_data = BboxData() bbox_data.update() except requests.exceptions.HTTPError as error: _LOGGER.error(error) return name = config[CONF_NAME] monitored_variables = config[CONF_MONITORED_VARIABLES] entities: list[BboxSensor | BboxUptimeSensor] = [ BboxSensor(bbox_data, name, description) for description in SENSOR_TYPES if description.key in monitored_variables ] entities.extend( [ BboxUptimeSensor(bbox_data, name, description) for description in SENSOR_TYPES_UPTIME if description.key in monitored_variables ] ) add_entities(entities, True)
Set up the beewi_smartclim platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the beewi_smartclim platform.""" mac = config[CONF_MAC] prefix = config[CONF_NAME] poller = BeewiSmartClimPoller(mac) sensors = [] for sensor_type in SENSOR_TYPES: device = sensor_type[0] name = sensor_type[1] unit = sensor_type[2] # `prefix` is the name configured by the user for the sensor, we're appending # the device type at the end of the name (garden -> garden temperature) if prefix: name = f"{prefix} {name}" sensors.append(BeewiSmartclimSensor(poller, name, mac, device, unit)) add_entities(sensors)
Evaluate state based on configuration.
def async_condition_from_config( hass: HomeAssistant, config: ConfigType ) -> condition.ConditionCheckerType: """Evaluate state based on configuration.""" condition_type = config[CONF_TYPE] if condition_type in 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)
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 return False
Set up the Bitcoin sensors.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Bitcoin sensors.""" currency = config[CONF_CURRENCY] if currency not in exchangerates.get_ticker(): _LOGGER.warning("Currency %s is not available. Using USD", currency) currency = DEFAULT_CURRENCY data = BitcoinData() entities = [ BitcoinSensor(data, currency, description) for description in SENSOR_TYPES if description.key in config[CONF_DISPLAY_OPTIONS] ] add_entities(entities, True)
Set up the Bizkaibus public transport sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Bizkaibus public transport sensor.""" name = config[CONF_NAME] stop = config[CONF_STOP_ID] route = config[CONF_ROUTE] data = Bizkaibus(stop, route) add_entities([BizkaibusSensor(data, name)], True)
Set up the Monoprice Blackbird 4k 8x8 HDBaseT Matrix platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Monoprice Blackbird 4k 8x8 HDBaseT Matrix platform.""" if DATA_BLACKBIRD not in hass.data: hass.data[DATA_BLACKBIRD] = {} port = config.get(CONF_PORT) host = config.get(CONF_HOST) connection = None if port is not None: try: blackbird = get_blackbird(port) connection = port except SerialException: _LOGGER.error("Error connecting to the Blackbird controller") return if host is not None: try: blackbird = get_blackbird(host, False) connection = host except TimeoutError: _LOGGER.error("Error connecting to the Blackbird controller") return sources = { source_id: extra[CONF_NAME] for source_id, extra in config[CONF_SOURCES].items() } devices = [] for zone_id, extra in config[CONF_ZONES].items(): _LOGGER.info("Adding zone %d - %s", zone_id, extra[CONF_NAME]) unique_id = f"{connection}-{zone_id}" device = BlackbirdZone(blackbird, sources, zone_id, extra[CONF_NAME]) hass.data[DATA_BLACKBIRD][unique_id] = device devices.append(device) add_entities(devices, True) def service_handle(service: ServiceCall) -> None: """Handle for services.""" entity_ids = service.data.get(ATTR_ENTITY_ID) source = service.data.get(ATTR_SOURCE) if entity_ids: devices = [ device for device in hass.data[DATA_BLACKBIRD].values() if device.entity_id in entity_ids ] else: devices = hass.data[DATA_BLACKBIRD].values() for device in devices: if service.service == SERVICE_SETALLZONES: device.set_all_zones(source) hass.services.register( DOMAIN, SERVICE_SETALLZONES, service_handle, schema=BLACKBIRD_SETALLZONES_SCHEMA )
Return a list with host and port.
def host_port(data): """Return a list with host and port.""" return (data[CONF_HOST], data[CONF_PORT])
Create a schema with given values as default.
def create_schema(previous_input=None): """Create a schema with given values as default.""" if previous_input is not None: host, port = host_port(previous_input) else: host = DEFAULT_HOST port = DEFAULT_PORT return vol.Schema( { vol.Required(CONF_HOST, default=host): str, vol.Required(CONF_PORT, default=port): int, vol.Inclusive(CONF_USERNAME, "auth"): str, vol.Inclusive(CONF_PASSWORD, "auth"): str, } )
Return proper session object.
def get_maybe_authenticated_session( hass: HomeAssistant, password: str | None, username: str | None ) -> aiohttp.ClientSession: """Return proper session object.""" if username and password: auth = aiohttp.BasicAuth(login=username, password=password) return async_create_clientsession(hass, auth=auth) return async_get_clientsession(hass)
Set up the services for the Blink integration.
def setup_services(hass: HomeAssistant) -> None: """Set up the services for the Blink integration.""" def collect_coordinators( device_ids: list[str], ) -> list[BlinkUpdateCoordinator]: config_entries: list[ConfigEntry] = [] registry = dr.async_get(hass) for target in device_ids: device = registry.async_get(target) if device: device_entries: list[ConfigEntry] = [] for entry_id in device.config_entries: entry = hass.config_entries.async_get_entry(entry_id) if entry and entry.domain == DOMAIN: device_entries.append(entry) if not device_entries: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_device", translation_placeholders={"target": target, "domain": DOMAIN}, ) config_entries.extend(device_entries) else: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="device_not_found", translation_placeholders={"target": target}, ) coordinators: list[BlinkUpdateCoordinator] = [] for config_entry in config_entries: if config_entry.state != ConfigEntryState.LOADED: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="not_loaded", translation_placeholders={"target": config_entry.title}, ) coordinators.append(hass.data[DOMAIN][config_entry.entry_id]) return coordinators async def send_pin(call: ServiceCall): """Call blink to send new pin.""" for entry_id in call.data[ATTR_CONFIG_ENTRY_ID]: if not (config_entry := hass.config_entries.async_get_entry(entry_id)): raise ServiceValidationError( translation_domain=DOMAIN, translation_key="integration_not_found", translation_placeholders={"target": DOMAIN}, ) if config_entry.state != ConfigEntryState.LOADED: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="not_loaded", translation_placeholders={"target": config_entry.title}, ) coordinator = hass.data[DOMAIN][entry_id] await coordinator.api.auth.send_auth_key( coordinator.api, call.data[CONF_PIN], ) async def blink_refresh(call: ServiceCall): """Call blink to refresh info.""" ir.async_create_issue( hass, DOMAIN, "service_deprecation", breaks_in_ha_version="2024.7.0", is_fixable=True, is_persistent=True, severity=ir.IssueSeverity.WARNING, translation_key="service_deprecation", ) for coordinator in collect_coordinators(call.data[ATTR_DEVICE_ID]): await coordinator.api.refresh(force_cache=True) # Register all the above services # Refresh service is deprecated and will be removed in 7/2024 service_mapping = [ (blink_refresh, SERVICE_REFRESH, SERVICE_UPDATE_SCHEMA), (send_pin, SERVICE_SEND_PIN, SERVICE_SEND_PIN_SCHEMA), ] for service_handler, service_name, schema in service_mapping: hass.services.async_register( DOMAIN, service_name, service_handler, schema=schema, )
Set up Blinkstick device specified by serial number.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up Blinkstick device specified by serial number.""" name = config[CONF_NAME] serial = config[CONF_SERIAL] stick = blinkstick.find_by_serial(serial) add_entities([BlinkStickLight(stick, name)], True)
Set up the Blockchain.com sensors.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Blockchain.com sensors.""" addresses: list[str] = config[CONF_ADDRESSES] name: str = config[CONF_NAME] for address in addresses: if not validate_address(address): _LOGGER.error("Bitcoin address is not valid: %s", address) return add_entities([BlockchainSensor(name, addresses)], True)
Set up the available BloomSky weather binary sensors.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the available BloomSky weather binary sensors.""" # Default needed in case of discovery if discovery_info is not None: return sensors = config[CONF_MONITORED_CONDITIONS] bloomsky = hass.data[DOMAIN] for device in bloomsky.devices.values(): for variable in sensors: add_entities([BloomSkySensor(bloomsky, device, variable)], True)
Set up access to BloomSky cameras.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up access to BloomSky cameras.""" if discovery_info is not None: return bloomsky = hass.data[DOMAIN] for device in bloomsky.devices.values(): add_entities([BloomSkyCamera(bloomsky, device)])
Set up the available BloomSky weather sensors.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the available BloomSky weather sensors.""" # Default needed in case of discovery if discovery_info is not None: return sensors = config[CONF_MONITORED_CONDITIONS] bloomsky = hass.data[DOMAIN] for device in bloomsky.devices.values(): for variable in sensors: add_entities([BloomSkySensor(bloomsky, device, variable)], True)
Set up the BloomSky integration.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the BloomSky integration.""" api_key = config[DOMAIN][CONF_API_KEY] try: bloomsky = BloomSky(api_key, hass.config.units is METRIC_SYSTEM) except RuntimeError: return False hass.data[DOMAIN] = bloomsky for platform in PLATFORMS: discovery.load_platform(hass, platform, DOMAIN, {}, config) return True
Convert a device key to an entity key.
def device_key_to_bluetooth_entity_key( device_key: DeviceKey, ) -> PassiveBluetoothEntityKey: """Convert a device key to an entity key.""" return PassiveBluetoothEntityKey(device_key.key, device_key.device_id)
Convert a sensor update to a bluetooth data update.
def sensor_update_to_bluetooth_data_update( sensor_update: SensorUpdate, ) -> PassiveBluetoothDataUpdate: """Convert a sensor update to a bluetooth data update.""" return PassiveBluetoothDataUpdate( devices={ device_id: sensor_device_info_to_hass_device_info(device_info) for device_id, device_info in sensor_update.devices.items() }, entity_descriptions={ device_key_to_bluetooth_entity_key(device_key): SENSOR_DESCRIPTIONS[ (description.device_class, description.native_unit_of_measurement) ] for device_key, description in sensor_update.entity_descriptions.items() if description.device_class and description.native_unit_of_measurement }, entity_data={ device_key_to_bluetooth_entity_key(device_key): sensor_values.native_value for device_key, sensor_values in sensor_update.entity_values.items() }, entity_names={}, )
Convert a GitHub url to the raw content. Async friendly.
def _get_github_import_url(url: str) -> str: """Convert a GitHub url to the raw content. Async friendly. """ if url.startswith("https://raw.githubusercontent.com/"): return url if (match := GITHUB_FILE_PATTERN.match(url)) is None: raise UnsupportedUrl("Not a GitHub file url") repo, path = match.groups() return f"https://raw.githubusercontent.com/{repo}/{path}"
Convert a forum post url to an import url. Async friendly.
def _get_community_post_import_url(url: str) -> str: """Convert a forum post url to an import url. Async friendly. """ if (match := COMMUNITY_TOPIC_PATTERN.match(url)) is None: raise UnsupportedUrl("Not a topic url") _topic, post = match.groups() json_url = url if post is not None: # Chop off post part, ie /2 json_url = json_url[: -len(post) - 1] json_url += ".json" return json_url
Extract a blueprint from a community post JSON. Async friendly.
def _extract_blueprint_from_community_topic( url: str, topic: dict, ) -> ImportedBlueprint: """Extract a blueprint from a community post JSON. Async friendly. """ block_content: str blueprint = None post = topic["post_stream"]["posts"][0] for match in COMMUNITY_CODE_BLOCK.finditer(post["cooked"]): block_syntax, block_content = match.groups() if block_syntax not in ("auto", "yaml"): continue block_content = html.unescape(block_content.strip()) try: data = yaml.parse_yaml(block_content) except HomeAssistantError: if block_syntax == "yaml": raise continue if not is_blueprint_config(data): continue assert isinstance(data, dict) blueprint = Blueprint(data) break if blueprint is None: raise HomeAssistantError( "No valid blueprint found in the topic. Blueprint syntax blocks need to be" " marked as YAML or no syntax." ) return ImportedBlueprint( f'{post["username"]}/{topic["slug"]}', block_content, blueprint )
Validate a Home Assistant version.
def version_validator(value: Any) -> str: """Validate a Home Assistant version.""" if not isinstance(value, str): raise vol.Invalid("Version needs to be a string") parts = value.split(".") if len(parts) != 3: raise vol.Invalid("Version needs to be formatted as {major}.{minor}.{patch}") try: [int(p) for p in parts] except ValueError: raise vol.Invalid( "Major, minor and patch version needs to be an integer" ) from None return value
Return if it is a blueprint config.
def is_blueprint_config(config: Any) -> bool: """Return if it is a blueprint config.""" return isinstance(config, dict) and CONF_BLUEPRINT in config
Return if it is a blueprint instance config.
def is_blueprint_instance_config(config: Any) -> bool: """Return if it is a blueprint instance config.""" return isinstance(config, dict) and CONF_USE_BLUEPRINT in config
Validate value has a YAML suffix.
def validate_yaml_suffix(value: str) -> str: """Validate value has a YAML suffix.""" if not value.endswith(".yaml"): raise vol.Invalid("Path needs to end in .yaml") return value
Set up the websocket API.
def async_setup(hass: HomeAssistant) -> None: """Set up the websocket API.""" websocket_api.async_register_command(hass, ws_list_blueprints) websocket_api.async_register_command(hass, ws_import_blueprint) websocket_api.async_register_command(hass, ws_save_blueprint) websocket_api.async_register_command(hass, ws_delete_blueprint)
Add Bluesound players.
def _add_player(hass, async_add_entities, host, port=None, name=None): """Add Bluesound players.""" @callback def _init_player(event=None): """Start polling.""" hass.async_create_task(player.async_init()) @callback def _start_polling(event=None): """Start polling.""" player.start_polling() @callback def _stop_polling(): """Stop polling.""" player.stop_polling() @callback def _add_player_cb(): """Add player after first sync fetch.""" if player.id in [x.id for x in hass.data[DATA_BLUESOUND]]: _LOGGER.warning("Player already added %s", player.id) return hass.data[DATA_BLUESOUND].append(player) async_add_entities([player]) _LOGGER.info("Added device with name: %s", player.name) if hass.is_running: _start_polling() else: hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _start_polling) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _stop_polling) player = BluesoundPlayer(hass, host, port, name, _add_player_cb) if hass.is_running: _init_player() else: hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _init_player)
Get the bluetooth manager.
def _get_manager(hass: HomeAssistant) -> HomeAssistantBluetoothManager: """Get the bluetooth manager.""" return cast(HomeAssistantBluetoothManager, hass.data[DATA_MANAGER])
Return a HaBleakScannerWrapper. This is a wrapper around our BleakScanner singleton that allows multiple integrations to share the same BleakScanner.
def async_get_scanner(hass: HomeAssistant) -> HaBleakScannerWrapper: """Return a HaBleakScannerWrapper. This is a wrapper around our BleakScanner singleton that allows multiple integrations to share the same BleakScanner. """ return HaBleakScannerWrapper()
Return a scanner for a given source. This method is only intended to be used by integrations that implement a bluetooth client and need to interact with a scanner directly. It is not intended to be used by integrations that need to interact with a device.
def async_scanner_by_source(hass: HomeAssistant, source: str) -> BaseHaScanner | None: """Return a scanner for a given source. This method is only intended to be used by integrations that implement a bluetooth client and need to interact with a scanner directly. It is not intended to be used by integrations that need to interact with a device. """ return _get_manager(hass).async_scanner_by_source(source)
Return the number of scanners currently in use.
def async_scanner_count(hass: HomeAssistant, connectable: bool = True) -> int: """Return the number of scanners currently in use.""" return _get_manager(hass).async_scanner_count(connectable)
Return the discovered devices list.
def async_discovered_service_info( hass: HomeAssistant, connectable: bool = True ) -> Iterable[BluetoothServiceInfoBleak]: """Return the discovered devices list.""" if DATA_MANAGER not in hass.data: return [] return _get_manager(hass).async_discovered_service_info(connectable)
Return the last service info for an address.
def async_last_service_info( hass: HomeAssistant, address: str, connectable: bool = True ) -> BluetoothServiceInfoBleak | None: """Return the last service info for an address.""" if DATA_MANAGER not in hass.data: return None return _get_manager(hass).async_last_service_info(address, connectable)
Return BLEDevice for an address if its present.
def async_ble_device_from_address( hass: HomeAssistant, address: str, connectable: bool = True ) -> BLEDevice | None: """Return BLEDevice for an address if its present.""" if DATA_MANAGER not in hass.data: return None return _get_manager(hass).async_ble_device_from_address(address, connectable)
Return all discovered BluetoothScannerDevice for an address.
def async_scanner_devices_by_address( hass: HomeAssistant, address: str, connectable: bool = True ) -> list[BluetoothScannerDevice]: """Return all discovered BluetoothScannerDevice for an address.""" return _get_manager(hass).async_scanner_devices_by_address(address, connectable)
Check if an address is present in the bluetooth device list.
def async_address_present( hass: HomeAssistant, address: str, connectable: bool = True ) -> bool: """Check if an address is present in the bluetooth device list.""" if DATA_MANAGER not in hass.data: return False return _get_manager(hass).async_address_present(address, connectable)
Register to receive a callback on bluetooth change. mode is currently not used as we only support active scanning. Passive scanning will be available in the future. The flag is required to be present to avoid a future breaking change when we support passive scanning. Returns a callback that can be used to cancel the registration.
def async_register_callback( hass: HomeAssistant, callback: BluetoothCallback, match_dict: BluetoothCallbackMatcher | None, mode: BluetoothScanningMode, ) -> Callable[[], None]: """Register to receive a callback on bluetooth change. mode is currently not used as we only support active scanning. Passive scanning will be available in the future. The flag is required to be present to avoid a future breaking change when we support passive scanning. Returns a callback that can be used to cancel the registration. """ return _get_manager(hass).async_register_callback(callback, match_dict)
Register to receive a callback when an address is unavailable. Returns a callback that can be used to cancel the registration.
def async_track_unavailable( hass: HomeAssistant, callback: Callable[[BluetoothServiceInfoBleak], None], address: str, connectable: bool = True, ) -> Callable[[], None]: """Register to receive a callback when an address is unavailable. Returns a callback that can be used to cancel the registration. """ return _get_manager(hass).async_track_unavailable(callback, address, connectable)
Trigger discovery of devices which have already been seen.
def async_rediscover_address(hass: HomeAssistant, address: str) -> None: """Trigger discovery of devices which have already been seen.""" _get_manager(hass).async_rediscover_address(address)
Register a BleakScanner.
def async_register_scanner( hass: HomeAssistant, scanner: BaseHaScanner, connection_slots: int | None = None, ) -> CALLBACK_TYPE: """Register a BleakScanner.""" return _get_manager(hass).async_register_scanner(scanner, connection_slots)
Get the advertisement callback.
def async_get_advertisement_callback( hass: HomeAssistant, ) -> Callable[[BluetoothServiceInfoBleak], None]: """Get the advertisement callback.""" return _get_manager(hass).scanner_adv_received
Get the learned advertising interval for a MAC address.
def async_get_learned_advertising_interval( hass: HomeAssistant, address: str ) -> float | None: """Get the learned advertising interval for a MAC address.""" return _get_manager(hass).async_get_learned_advertising_interval(address)
Get the fallback availability timeout for a MAC address.
def async_get_fallback_availability_interval( hass: HomeAssistant, address: str ) -> float | None: """Get the fallback availability timeout for a MAC address.""" return _get_manager(hass).async_get_fallback_availability_interval(address)
Override the fallback availability timeout for a MAC address.
def async_set_fallback_availability_interval( hass: HomeAssistant, address: str, interval: float ) -> None: """Override the fallback availability timeout for a MAC address.""" _get_manager(hass).async_set_fallback_availability_interval(address, interval)
Return the adapter display info.
def adapter_display_info(adapter: str, details: AdapterDetails) -> str: """Return the adapter display info.""" name = adapter_human_name(adapter, details[ADAPTER_ADDRESS]) model = adapter_model(details) manufacturer = details[ADAPTER_MANUFACTURER] or "Unknown" return f"{name} {manufacturer} {model}"
Return if we have seen all fields.
def seen_all_fields( previous_match: IntegrationMatchHistory, advertisement_data: AdvertisementData ) -> bool: """Return if we have seen all fields.""" if not previous_match.manufacturer_data and advertisement_data.manufacturer_data: return False if advertisement_data.service_data and ( not previous_match.service_data or not previous_match.service_data.issuperset(advertisement_data.service_data) ): return False if advertisement_data.service_uuids and ( not previous_match.service_uuids or not previous_match.service_uuids.issuperset(advertisement_data.service_uuids) ): return False return True
Convert a local name to an index. We check the local name matchers here and raise a ValueError if they try to setup a matcher that will is overly broad as would match too many devices and cause a performance hit.
def _local_name_to_index_key(local_name: str) -> str: """Convert a local name to an index. We check the local name matchers here and raise a ValueError if they try to setup a matcher that will is overly broad as would match too many devices and cause a performance hit. """ match_part = local_name[:LOCAL_NAME_MIN_MATCH_LENGTH] if "*" in match_part or "[" in match_part: raise ValueError( "Local name matchers may not have patterns in the first " f"{LOCAL_NAME_MIN_MATCH_LENGTH} characters because they " f"would match too broadly ({local_name})" ) return match_part
Check if a ble device and advertisement_data matches the matcher.
def ble_device_matches( matcher: BluetoothMatcherOptional, service_info: BluetoothServiceInfoBleak, ) -> bool: """Check if a ble device and advertisement_data matches the matcher.""" # Don't check address here since all callers already # check the address and we don't want to double check # since it would result in an unreachable reject case. if matcher.get(CONNECTABLE, True) and not service_info.connectable: return False if ( service_uuid := matcher.get(SERVICE_UUID) ) and service_uuid not in service_info.service_uuids: return False if ( service_data_uuid := matcher.get(SERVICE_DATA_UUID) ) and service_data_uuid not in service_info.service_data: return False if manufacturer_id := matcher.get(MANUFACTURER_ID): if manufacturer_id not in service_info.manufacturer_data: return False if manufacturer_data_start := matcher.get(MANUFACTURER_DATA_START): if not service_info.manufacturer_data[manufacturer_id].startswith( bytes(manufacturer_data_start) ): return False if (local_name := matcher.get(LOCAL_NAME)) and not _memorized_fnmatch( service_info.name, local_name, ): return False return True
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. Bluetooth 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. Bluetooth 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))
Deserialize an entity description.
def deserialize_entity_description( descriptions_class: type[EntityDescription], data: dict[str, Any] ) -> EntityDescription: """Deserialize an entity description.""" # pylint: disable=protected-access result: dict[str, Any] = {} if hasattr(descriptions_class, "_dataclass"): descriptions_class = descriptions_class._dataclass for field in cached_fields(descriptions_class): field_name = field.name # It would be nice if field.type returned the actual # type instead of a str so we could avoid writing this # out, but it doesn't. If we end up using this in more # places we can add a `as_dict` and a `from_dict` # method to these classes if field_name == CONF_ENTITY_CATEGORY: value = try_parse_enum(EntityCategory, data.get(field_name)) else: value = data.get(field_name) result[field_name] = value return descriptions_class(**result)
Serialize an entity description.
def serialize_entity_description(description: EntityDescription) -> dict[str, Any]: """Serialize an entity description.""" return { field.name: value for field in cached_fields(type(description)) if (value := getattr(description, field.name)) != field.default }
Register a coordinator to have its processors data restored.
def async_register_coordinator_for_restore( hass: HomeAssistant, coordinator: PassiveBluetoothProcessorCoordinator ) -> CALLBACK_TYPE: """Register a coordinator to have its processors data restored.""" data: PassiveBluetoothProcessorData = hass.data[PASSIVE_UPDATE_PROCESSOR] coordinators = data.coordinators coordinators.add(coordinator) if restore_key := coordinator.restore_key: coordinator.restore_data = data.all_restore_data.setdefault(restore_key, {}) @callback def _unregister_coordinator_for_restore() -> None: """Unregister a coordinator.""" coordinators.remove(coordinator) return _unregister_coordinator_for_restore
Load the device and advertisement_data history. Only loads if available on the current system.
def async_load_history_from_system( adapters: BluetoothAdapters, storage: BluetoothStorage ) -> tuple[dict[str, BluetoothServiceInfoBleak], dict[str, BluetoothServiceInfoBleak]]: """Load the device and advertisement_data history. Only loads if available on the current system. """ now_monotonic = monotonic_time_coarse() connectable_loaded_history: dict[str, BluetoothServiceInfoBleak] = {} all_loaded_history: dict[str, BluetoothServiceInfoBleak] = {} # Restore local adapters for address, history in adapters.history.items(): if ( not (existing_all := connectable_loaded_history.get(address)) or history.advertisement_data.rssi > existing_all.rssi ): connectable_loaded_history[address] = all_loaded_history[address] = ( BluetoothServiceInfoBleak.from_device_and_advertisement_data( history.device, history.advertisement_data, history.source, now_monotonic, True, ) ) # Restore remote adapters for scanner in storage.scanners(): if not (adv_history := storage.async_get_advertisement_history(scanner)): continue connectable = adv_history.connectable discovered_device_timestamps = adv_history.discovered_device_timestamps for ( address, (device, advertisement_data), ) in adv_history.discovered_device_advertisement_datas.items(): service_info = BluetoothServiceInfoBleak.from_device_and_advertisement_data( device, advertisement_data, scanner, discovered_device_timestamps[address], connectable, ) if ( not (existing_all := all_loaded_history.get(address)) or service_info.rssi > existing_all.rssi ): all_loaded_history[address] = service_info if connectable and ( not (existing_connectable := connectable_loaded_history.get(address)) or service_info.rssi > existing_connectable.rssi ): connectable_loaded_history[address] = service_info return all_loaded_history, connectable_loaded_history
Return the adapter title.
def adapter_title(adapter: str, details: AdapterDetails) -> str: """Return the adapter title.""" unique_name = adapter_unique_name(adapter, details[ADAPTER_ADDRESS]) model = details.get(ADAPTER_PRODUCT, "Unknown") manufacturer = details[ADAPTER_MANUFACTURER] or "Unknown" return f"{manufacturer} {model} ({unique_name})"
Migrate config entries to support multiple.
def async_migrate_entries( hass: HomeAssistant, adapters: dict[str, AdapterDetails], default_adapter: str ) -> None: """Migrate config entries to support multiple.""" current_entries = hass.config_entries.async_entries(DOMAIN) for entry in current_entries: if entry.unique_id: continue address = DEFAULT_ADDRESS adapter = entry.options.get(CONF_ADAPTER, default_adapter) if adapter in adapters: address = adapters[adapter][ADAPTER_ADDRESS] hass.config_entries.async_update_entry( entry, title=adapter_unique_name(adapter, address), unique_id=address )
Check whether a device is a bluetooth device by its mac.
def is_bluetooth_device(device: Device) -> bool: """Check whether a device is a bluetooth device by its mac.""" return device.mac is not None and device.mac[:3].upper() == BT_PREFIX
Discover Bluetooth devices.
def discover_devices(device_id: int) -> list[tuple[str, str]]: """Discover Bluetooth devices.""" try: result = bluetooth.discover_devices( duration=8, lookup_names=True, flush_cache=True, lookup_class=False, device_id=device_id, ) except OSError as ex: # OSError is generally thrown if a bluetooth device isn't found _LOGGER.error("Couldn't discover bluetooth devices: %s", ex) return [] _LOGGER.debug("Bluetooth devices discovered = %d", len(result)) return result
Lookup a Bluetooth device name.
def lookup_name(mac: str) -> str | None: """Lookup a Bluetooth device name.""" _LOGGER.debug("Scanning %s", mac) return bluetooth.lookup_name(mac, timeout=5)
Convert a MyBMWVehicle to a dictionary using MyBMWJSONEncoder.
def vehicle_to_dict(vehicle: MyBMWVehicle | None) -> dict: """Convert a MyBMWVehicle to a dictionary using MyBMWJSONEncoder.""" retval: dict = json.loads(json.dumps(vehicle, cls=MyBMWJSONEncoder)) return retval
Get the BMW notification service.
def get_service( hass: HomeAssistant, config: ConfigType, discovery_info: DiscoveryInfoType | None = None, ) -> BMWNotificationService: """Get the BMW notification service.""" coordinator: BMWDataUpdateCoordinator = hass.data[DOMAIN][ (discovery_info or {})[CONF_ENTITY_ID] ] targets = {} if not coordinator.read_only: targets.update({v.name: v for v in coordinator.account.vehicles}) return BMWNotificationService(targets)
Safely convert and round a value from ValueWithUnit.
def convert_and_round( state: ValueWithUnit, converter: Callable[[float | None, str], float], precision: int, ) -> float | None: """Safely convert and round a value from ValueWithUnit.""" if state.value and state.unit: return round( converter(state.value, UNIT_MAP.get(state.unit, state.unit)), precision ) if state.value: return state.value return None
Convert bond 0-open 100-closed to hass 0-closed 100-open.
def _bond_to_hass_position(bond_position: int) -> int: """Convert bond 0-open 100-closed to hass 0-closed 100-open.""" return abs(bond_position - 100)
Convert hass 0-closed 100-open to bond 0-open 100-closed.
def _hass_to_bond_position(hass_position: int) -> int: """Convert hass 0-closed 100-open to bond 0-open 100-closed.""" return 100 - hass_position