response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Copy discovery data into config entry data. | def async_populate_data_from_discovery(
current_data: Mapping[str, Any],
data_updates: dict[str, Any],
device: FluxLEDDiscovery,
) -> None:
"""Copy discovery data into config entry data."""
for conf_key, discovery_key in CONF_TO_DISCOVERY.items():
if (
device.get(discovery_key) is not None
and conf_key
not in data_updates # Prefer the model num from TCP instead of UDP
and current_data.get(conf_key) != device[discovery_key] # type: ignore[literal-required]
):
data_updates[conf_key] = device[discovery_key] |
Update a config entry from a flux_led discovery. | def async_update_entry_from_discovery(
hass: HomeAssistant,
entry: config_entries.ConfigEntry,
device: FluxLEDDiscovery,
model_num: int | None,
allow_update_mac: bool,
) -> bool:
"""Update a config entry from a flux_led discovery."""
data_updates: dict[str, Any] = {}
mac_address = device[ATTR_ID]
assert mac_address is not None
updates: dict[str, Any] = {}
formatted_mac = dr.format_mac(mac_address)
if not entry.unique_id or (
allow_update_mac
and entry.unique_id != formatted_mac
and mac_matches_by_one(formatted_mac, entry.unique_id)
):
updates["unique_id"] = formatted_mac
if model_num and entry.data.get(CONF_MODEL_NUM) != model_num:
data_updates[CONF_MODEL_NUM] = model_num
async_populate_data_from_discovery(entry.data, data_updates, device)
if is_ip_address(entry.title):
updates["title"] = async_name_from_discovery(device, model_num)
title_matches_name = entry.title == entry.data.get(CONF_NAME)
if data_updates or title_matches_name:
updates["data"] = {**entry.data, **data_updates}
if title_matches_name:
del updates["data"][CONF_NAME]
# If the title has changed and the config entry is loaded, a listener is
# in place, and we should not reload
if updates and not ("title" in updates and entry.state is ConfigEntryState.LOADED):
return hass.config_entries.async_update_entry(entry, **updates)
return False |
Check if a device was already discovered via a broadcast discovery. | def async_get_discovery(hass: HomeAssistant, host: str) -> FluxLEDDiscovery | None:
"""Check if a device was already discovered via a broadcast discovery."""
discoveries: list[FluxLEDDiscovery] = hass.data[DOMAIN][FLUX_LED_DISCOVERY]
for discovery in discoveries:
if discovery[ATTR_IPADDR] == host:
return discovery
return None |
Clear the host from the discovery cache. | def async_clear_discovery_cache(hass: HomeAssistant, host: str) -> None:
"""Clear the host from the discovery cache."""
domain_data = hass.data[DOMAIN]
discoveries: list[FluxLEDDiscovery] = domain_data[FLUX_LED_DISCOVERY]
domain_data[FLUX_LED_DISCOVERY] = [
discovery for discovery in discoveries if discovery[ATTR_IPADDR] != host
] |
Trigger config flows for discovered devices. | def async_trigger_discovery(
hass: HomeAssistant,
discovered_devices: list[FluxLEDDiscovery],
) -> None:
"""Trigger config flows for discovered devices."""
for device in discovered_devices:
discovery_flow.async_create_flow(
hass,
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data={**device},
) |
Convert a device registry formatted mac to flux mac. | def format_as_flux_mac(mac: str | None) -> str | None:
"""Convert a device registry formatted mac to flux mac."""
return None if mac is None else mac.replace(":", "").upper() |
Check if a mac address is only one digit off.
Some of the devices have two mac addresses which are
one off from each other. We need to treat them as the same
since its the same device. | def mac_matches_by_one(formatted_mac_1: str, formatted_mac_2: str) -> bool:
"""Check if a mac address is only one digit off.
Some of the devices have two mac addresses which are
one off from each other. We need to treat them as the same
since its the same device.
"""
mac_int_1 = int(formatted_mac_1.replace(":", ""), 16)
mac_int_2 = int(formatted_mac_2.replace(":", ""), 16)
return abs(mac_int_1 - mac_int_2) < 2 |
Map the flux color mode to Home Assistant color mode. | def _flux_color_mode_to_hass(
flux_color_mode: str | None, flux_color_modes: set[str]
) -> ColorMode:
"""Map the flux color mode to Home Assistant color mode."""
if flux_color_mode is None:
return ColorMode.ONOFF
if flux_color_mode == FLUX_COLOR_MODE_DIM:
if len(flux_color_modes) > 1:
return ColorMode.WHITE
return ColorMode.BRIGHTNESS
return FLUX_COLOR_MODE_TO_HASS.get(flux_color_mode, ColorMode.ONOFF) |
Convert hass brightness to effect brightness. | def _effect_brightness(brightness: int) -> int:
"""Convert hass brightness to effect brightness."""
return round(brightness / 255 * 100) |
Convert an multicolor effect string to MultiColorEffects. | def _str_to_multi_color_effect(effect_str: str) -> MultiColorEffects:
"""Convert an multicolor effect string to MultiColorEffects."""
for effect in MultiColorEffects:
if effect.name.lower() == effect_str:
return effect
# unreachable due to schema validation
raise RuntimeError |
RGB brightness is zero. | def _is_zero_rgb_brightness(rgb: tuple[int, int, int]) -> bool:
"""RGB brightness is zero."""
return all(byte == 0 for byte in rgb) |
Ensure the RGB value will not turn off the device from a turn on command. | def _min_rgb_brightness(rgb: tuple[int, int, int]) -> tuple[int, int, int]:
"""Ensure the RGB value will not turn off the device from a turn on command."""
if _is_zero_rgb_brightness(rgb):
return (MIN_RGB_BRIGHTNESS, MIN_RGB_BRIGHTNESS, MIN_RGB_BRIGHTNESS)
return rgb |
Scale an RGB tuple to minimum brightness. | def _min_scaled_rgb_brightness(rgb: tuple[int, int, int]) -> tuple[int, int, int]:
"""Scale an RGB tuple to minimum brightness."""
return color_hsv_to_RGB(*color_RGB_to_hsv(*rgb)[:2], 1) |
Ensure the RGBW value will not turn off the device from a turn on command.
For RGBW, we also need to ensure that there is at least one
value in the RGB fields or the device will switch to CCT mode unexpectedly.
If the new value being set is all zeros, scale the current
color to brightness of 1 so we do not unexpected switch to white | def _min_rgbw_brightness(
rgbw: tuple[int, int, int, int], current_rgbw: tuple[int, int, int, int]
) -> tuple[int, int, int, int]:
"""Ensure the RGBW value will not turn off the device from a turn on command.
For RGBW, we also need to ensure that there is at least one
value in the RGB fields or the device will switch to CCT mode unexpectedly.
If the new value being set is all zeros, scale the current
color to brightness of 1 so we do not unexpected switch to white
"""
if _is_zero_rgb_brightness(rgbw[:3]):
return (*_min_scaled_rgb_brightness(current_rgbw[:3]), rgbw[3])
return (*_min_rgb_brightness(rgbw[:3]), rgbw[3]) |
Ensure the RGBWC value will not turn off the device from a turn on command.
For RGBWC, we also need to ensure that there is at least one
value in the RGB fields or the device will switch to CCT mode unexpectedly
If the new value being set is all zeros, scale the current
color to brightness of 1 so we do not unexpected switch to white | def _min_rgbwc_brightness(
rgbwc: tuple[int, int, int, int, int], current_rgbwc: tuple[int, int, int, int, int]
) -> tuple[int, int, int, int, int]:
"""Ensure the RGBWC value will not turn off the device from a turn on command.
For RGBWC, we also need to ensure that there is at least one
value in the RGB fields or the device will switch to CCT mode unexpectedly
If the new value being set is all zeros, scale the current
color to brightness of 1 so we do not unexpected switch to white
"""
if _is_zero_rgb_brightness(rgbwc[:3]):
return (*_min_scaled_rgb_brightness(current_rgbwc[:3]), rgbwc[3], rgbwc[4])
return (*_min_rgb_brightness(rgbwc[:3]), rgbwc[3], rgbwc[4]) |
Create a AIOWifiLedBulb from a host. | def async_wifi_bulb_for_host(
host: str, discovery: FluxLEDDiscovery | None
) -> AIOWifiLedBulb:
"""Create a AIOWifiLedBulb from a host."""
return AIOWifiLedBulb(host, discovery=discovery) |
Return the list of files, applying filter. | def get_files_list(folder_path: str, filter_term: str) -> list[str]:
"""Return the list of files, applying filter."""
query = folder_path + filter_term
return glob.glob(query) |
Return the sum of the size in bytes of files in the list. | def get_size(files_list: list[str]) -> int:
"""Return the sum of the size in bytes of files in the list."""
size_list = [os.stat(f).st_size for f in files_list if os.path.isfile(f)]
return sum(size_list) |
Set up the folder sensor. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the folder sensor."""
path: str = config[CONF_FOLDER_PATHS]
if not hass.config.is_allowed_path(path):
_LOGGER.error("Folder %s is not valid or allowed", path)
else:
folder = Folder(path, config[CONF_FILTER])
add_entities([folder], True) |
Return the Watchdog EventHandler object. | def create_event_handler(patterns: list[str], hass: HomeAssistant) -> EventHandler:
"""Return the Watchdog EventHandler object."""
return EventHandler(patterns, hass) |
Create an OwnTone uri. | def create_owntone_uri(media_type: str, id_or_path: str) -> str:
"""Create an OwnTone uri."""
return f"library:{MEDIA_TYPE_TO_OWNTONE_TYPE[media_type]}:{quote(id_or_path)}" |
Create a media_content_id.
Either owntone_uri or both type and id_or_path must be specified. | def create_media_content_id(
title: str,
owntone_uri: str = "",
media_type: str = "",
id_or_path: str = "",
subtype: str = "",
) -> str:
"""Create a media_content_id.
Either owntone_uri or both type and id_or_path must be specified.
"""
if not owntone_uri:
owntone_uri = create_owntone_uri(media_type, id_or_path)
return f"{URI_SCHEMA}:{quote(title)}:{owntone_uri}:{subtype}" |
Return whether this media_content_id is from our integration. | def is_owntone_media_content_id(media_content_id: str) -> bool:
"""Return whether this media_content_id is from our integration."""
return media_content_id[: len(URI_SCHEMA)] == URI_SCHEMA |
Convert media_content_id to OwnTone URI. | def convert_to_owntone_uri(media_content_id: str) -> str:
"""Convert media_content_id to OwnTone URI."""
return ":".join(media_content_id.split(":")[2:-1]) |
Convert the results into a browse media response. | def create_browse_media_response(
master: media_player.ForkedDaapdMaster,
media_content: MediaContent,
result: list[dict[str, int | str]],
children: list[BrowseMedia] | None = None,
) -> BrowseMedia:
"""Convert the results into a browse media response."""
internal_request = is_internal_request(master.hass)
if not children: # Directory searches will pass in subdirectories as children
children = []
for item in result:
if item.get("data_kind") == "spotify" or (
"path" in item and cast(str, item["path"]).startswith("spotify")
): # Exclude spotify data from OwnTone library
continue
assert isinstance(item["uri"], str)
media_type = OWNTONE_TYPE_TO_MEDIA_TYPE[item["uri"].split(":")[1]]
title = item.get("name") or item.get("title") # only tracks use title
assert isinstance(title, str)
media_content_id = create_media_content_id(
title=f"{media_content.title} / {title}",
owntone_uri=item["uri"],
subtype=media_content.subtype,
)
if artwork := item.get("artwork_url"):
thumbnail = (
master.api.full_url(cast(str, artwork))
if internal_request
else master.get_browse_image_url(media_type, media_content_id)
)
else:
thumbnail = None
children.append(
BrowseMedia(
title=title,
media_class=MEDIA_TYPE_TO_MEDIA_CLASS[media_type],
media_content_id=media_content_id,
media_content_type=media_type,
can_play=media_type in CAN_PLAY_TYPE,
can_expand=media_type in CAN_EXPAND_TYPE,
thumbnail=thumbnail,
)
)
return BrowseMedia(
title=media_content.id_or_path
if media_content.type == MEDIA_TYPE_DIRECTORY
else media_content.title,
media_class=MEDIA_TYPE_TO_MEDIA_CLASS[media_content.type],
media_content_id="",
media_content_type=media_content.type,
can_play=media_content.type in CAN_PLAY_TYPE,
can_expand=media_content.type in CAN_EXPAND_TYPE,
children=children,
) |
Return the base of our OwnTone library. | def base_owntone_library() -> BrowseMedia:
"""Return the base of our OwnTone library."""
children = [
BrowseMedia(
title=name,
media_class=media_class,
media_content_id=create_media_content_id(
title=name, media_type=media_type, subtype=media_subtype
),
media_content_type=MEDIA_TYPE_DIRECTORY,
can_play=False,
can_expand=True,
)
for name, (media_class, media_type, media_subtype) in TOP_LEVEL_LIBRARY.items()
]
return BrowseMedia(
title="OwnTone Library",
media_class=MediaClass.APP,
media_content_id=create_media_content_id(
title="OwnTone Library", media_type=MediaType.APP
),
media_content_type=MediaType.APP,
can_play=False,
can_expand=True,
children=children,
thumbnail="https://brands.home-assistant.io/_/forked_daapd/logo.png",
) |
Create response to describe contents of library. | def library(other: Sequence[BrowseMedia] | None) -> BrowseMedia:
"""Create response to describe contents of library."""
top_level_items = [
BrowseMedia(
title="OwnTone Library",
media_class=MediaClass.APP,
media_content_id=create_media_content_id(
title="OwnTone Library", media_type=MediaType.APP
),
media_content_type=MediaType.APP,
can_play=False,
can_expand=True,
thumbnail="https://brands.home-assistant.io/_/forked_daapd/logo.png",
)
]
if other:
top_level_items.extend(other)
return BrowseMedia(
title="OwnTone",
media_class=MediaClass.DIRECTORY,
media_content_id="",
media_content_type=MEDIA_TYPE_DIRECTORY,
can_play=False,
can_expand=True,
children=top_level_items,
) |
Fill in schema dict defaults from user_input. | def fill_in_schema_dict(some_input):
"""Fill in schema dict defaults from user_input."""
schema_dict = {}
for field, _type in DATA_SCHEMA_DICT.items():
if some_input.get(str(field)):
schema_dict[vol.Optional(str(field), default=some_input[str(field)])] = (
_type
)
else:
schema_dict[field] = _type
return schema_dict |
Validate the configuration and return a FortiOSDeviceScanner. | def get_scanner(hass: HomeAssistant, config: ConfigType) -> FortiOSDeviceScanner | None:
"""Validate the configuration and return a FortiOSDeviceScanner."""
host = config[DOMAIN][CONF_HOST]
verify_ssl = config[DOMAIN][CONF_VERIFY_SSL]
token = config[DOMAIN][CONF_TOKEN]
fgt = FortiOSAPI()
try:
fgt.tokenlogin(host, token, verify_ssl, None, 12, "root")
except ConnectionError as ex:
_LOGGER.error("ConnectionError to FortiOS API: %s", ex)
return None
except Exception as ex: # pylint: disable=broad-except
_LOGGER.error("Failed to login to FortiOS API: %s", ex)
return None
status_json = fgt.monitor("system/status", "")
current_version = AwesomeVersion(status_json["version"])
minimum_version = AwesomeVersion("6.4.3")
if current_version < minimum_version:
_LOGGER.error(
"Unsupported FortiOS version: %s. Version %s and newer are supported",
current_version,
minimum_version,
)
return None
return FortiOSDeviceScanner(fgt) |
Set up the Foursquare component. | def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Foursquare component."""
config = config[DOMAIN]
def checkin_user(call: ServiceCall) -> None:
"""Check a user in on Swarm."""
url = f"https://api.foursquare.com/v2/checkins/add?oauth_token={config[CONF_ACCESS_TOKEN]}&v=20160802&m=swarm"
response = requests.post(url, data=call.data, timeout=10)
if response.status_code not in (HTTPStatus.OK, HTTPStatus.CREATED):
_LOGGER.exception(
"Error checking in user. Response %d: %s:",
response.status_code,
response.reason,
)
hass.bus.fire(EVENT_CHECKIN, {"text": response.text})
# Register our service with Home Assistant.
hass.services.register(
DOMAIN, "checkin", checkin_user, schema=CHECKIN_SERVICE_SCHEMA
)
hass.http.register_view(FoursquarePushReceiver(config[CONF_PUSH_SECRET]))
return True |
Add new cameras from the router. | def add_entities(
hass: HomeAssistant,
router: FreeboxRouter,
async_add_entities: AddEntitiesCallback,
tracked: set[str],
) -> None:
"""Add new cameras from the router."""
new_tracked: list[FreeboxCamera] = []
for nodeid, node in router.home_devices.items():
if (node["category"] != FreeboxHomeCategory.CAMERA) or (nodeid in tracked):
continue
new_tracked.append(FreeboxCamera(hass, router, node))
tracked.add(nodeid)
if new_tracked:
async_add_entities(new_tracked, True) |
Add new tracker entities from the router. | def add_entities(
router: FreeboxRouter, async_add_entities: AddEntitiesCallback, tracked: set[str]
) -> None:
"""Add new tracker entities from the router."""
new_tracked = []
for mac, device in router.devices.items():
if mac in tracked:
continue
new_tracked.append(FreeboxDevice(router, device))
tracked.add(mac)
async_add_entities(new_tracked, True) |
Return a device icon from its type. | def icon_for_freebox_device(device: dict[str, Any]) -> str:
"""Return a device icon from its type."""
return DEVICE_ICONS.get(device["host_type"], "mdi:help-network") |
Validate if a String is a JSON value or not. | def is_json(json_str: str) -> bool:
"""Validate if a String is a JSON value or not."""
try:
json.loads(json_str)
except (ValueError, TypeError) as err:
_LOGGER.error(
"Failed to parse JSON '%s', error '%s'",
json_str,
err,
)
return False
return True |
Get the Free Mobile SMS notification service. | def get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> FreeSMSNotificationService:
"""Get the Free Mobile SMS notification service."""
return FreeSMSNotificationService(config[CONF_USERNAME], config[CONF_ACCESS_TOKEN]) |
Add new WOL button entities from the AVM device. | def _async_wol_buttons_list(
avm_wrapper: AvmWrapper,
data_fritz: FritzData,
) -> list[FritzBoxWOLButton]:
"""Add new WOL button entities from the AVM device."""
_LOGGER.debug("Setting up %s buttons", BUTTON_TYPE_WOL)
new_wols: list[FritzBoxWOLButton] = []
if avm_wrapper.unique_id not in data_fritz.wol_buttons:
data_fritz.wol_buttons[avm_wrapper.unique_id] = set()
for mac, device in avm_wrapper.devices.items():
if _is_tracked(mac, data_fritz.wol_buttons.values()):
_LOGGER.debug("Skipping wol button creation for device %s", device.hostname)
continue
if device.connection_type != CONNECTION_TYPE_LAN:
_LOGGER.debug(
"Skipping wol button creation for device %s, not connected via LAN",
device.hostname,
)
continue
new_wols.append(FritzBoxWOLButton(avm_wrapper, device))
data_fritz.wol_buttons[avm_wrapper.unique_id].add(mac)
_LOGGER.debug("Creating %s wol buttons", len(new_wols))
return new_wols |
Check if device is already tracked. | def _is_tracked(mac: str, current_devices: ValuesView) -> bool:
"""Check if device is already tracked."""
return any(mac in tracked for tracked in current_devices) |
Check if device should be filtered out from trackers. | def device_filter_out_from_trackers(
mac: str,
device: FritzDevice,
current_devices: ValuesView,
) -> bool:
"""Check if device should be filtered out from trackers."""
reason: str | None = None
if device.ip_address == "":
reason = "Missing IP"
elif _is_tracked(mac, current_devices):
reason = "Already tracked"
if reason:
_LOGGER.debug(
"Skip adding device %s [%s], reason: %s", device.hostname, mac, reason
)
return bool(reason) |
Filter only relevant entities. | def _cleanup_entity_filter(device: er.RegistryEntry) -> bool:
"""Filter only relevant entities."""
return device.domain == DEVICE_TRACKER_DOMAIN or (
device.domain == DEVICE_SWITCH_DOMAIN and "_internet_access" in device.entity_id
) |
Inform that HA is stopping. | def _ha_is_stopping(activity: str) -> None:
"""Inform that HA is stopping."""
_LOGGER.info("Cannot execute %s: HomeAssistant is shutting down", activity) |
Add new tracker entities from the AVM device. | def _async_add_entities(
avm_wrapper: AvmWrapper,
async_add_entities: AddEntitiesCallback,
data_fritz: FritzData,
) -> None:
"""Add new tracker entities from the AVM device."""
new_tracked = []
if avm_wrapper.unique_id not in data_fritz.tracked:
data_fritz.tracked[avm_wrapper.unique_id] = set()
for mac, device in avm_wrapper.devices.items():
if device_filter_out_from_trackers(mac, device, data_fritz.tracked.values()):
continue
new_tracked.append(FritzBoxTracker(avm_wrapper, device))
data_fritz.tracked[avm_wrapper.unique_id].add(mac)
async_add_entities(new_tracked) |
Calculate uptime with deviation. | def _uptime_calculation(seconds_uptime: float, last_value: datetime | None) -> datetime:
"""Calculate uptime with deviation."""
delta_uptime = utcnow() - timedelta(seconds=seconds_uptime)
if (
not last_value
or abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION
):
return delta_uptime
return last_value |
Return uptime from device. | def _retrieve_device_uptime_state(
status: FritzStatus, last_value: datetime
) -> datetime:
"""Return uptime from device."""
return _uptime_calculation(status.device_uptime, last_value) |
Return uptime from connection. | def _retrieve_connection_uptime_state(
status: FritzStatus, last_value: datetime | None
) -> datetime:
"""Return uptime from connection."""
return _uptime_calculation(status.connection_uptime, last_value) |
Return external ip from device. | def _retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str:
"""Return external ip from device."""
return status.external_ip |
Return external ipv6 from device. | def _retrieve_external_ipv6_state(status: FritzStatus, last_value: str) -> str:
"""Return external ipv6 from device."""
return str(status.external_ipv6) |
Return upload transmission rate. | def _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:
"""Return upload transmission rate."""
return round(status.transmission_rate[0] / 1000, 1) |
Return download transmission rate. | def _retrieve_kb_s_received_state(status: FritzStatus, last_value: str) -> float:
"""Return download transmission rate."""
return round(status.transmission_rate[1] / 1000, 1) |
Return upload max transmission rate. | def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:
"""Return upload max transmission rate."""
return round(status.max_bit_rate[0] / 1000, 1) |
Return download max transmission rate. | def _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) -> float:
"""Return download max transmission rate."""
return round(status.max_bit_rate[1] / 1000, 1) |
Return upload total data. | def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float:
"""Return upload total data."""
return round(status.bytes_sent / 1000 / 1000 / 1000, 1) |
Return download total data. | def _retrieve_gb_received_state(status: FritzStatus, last_value: str) -> float:
"""Return download total data."""
return round(status.bytes_received / 1000 / 1000 / 1000, 1) |
Return upload link rate. | def _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:
"""Return upload link rate."""
return round(status.max_linked_bit_rate[0] / 1000, 1) |
Return download link rate. | def _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) -> float:
"""Return download link rate."""
return round(status.max_linked_bit_rate[1] / 1000, 1) |
Return upload noise margin. | def _retrieve_link_noise_margin_sent_state(
status: FritzStatus, last_value: str
) -> float:
"""Return upload noise margin."""
return status.noise_margin[0] / 10 |
Return download noise margin. | def _retrieve_link_noise_margin_received_state(
status: FritzStatus, last_value: str
) -> float:
"""Return download noise margin."""
return status.noise_margin[1] / 10 |
Return upload line attenuation. | def _retrieve_link_attenuation_sent_state(
status: FritzStatus, last_value: str
) -> float:
"""Return upload line attenuation."""
return status.attenuation[0] / 10 |
Return download line attenuation. | def _retrieve_link_attenuation_received_state(
status: FritzStatus, last_value: str
) -> float:
"""Return download line attenuation."""
return status.attenuation[1] / 10 |
Get coordinator for given config entry id. | def get_coordinator(
hass: HomeAssistant, config_entry_id: str
) -> FritzboxDataUpdateCoordinator:
"""Get coordinator for given config entry id."""
coordinator: FritzboxDataUpdateCoordinator = hass.data[DOMAIN][config_entry_id][
CONF_COORDINATOR
]
return coordinator |
Check suitablity for eco temperature sensor. | def suitable_eco_temperature(device: FritzhomeDevice) -> bool:
"""Check suitablity for eco temperature sensor."""
return device.has_thermostat and device.eco_temperature is not None |
Check suitablity for comfort temperature sensor. | def suitable_comfort_temperature(device: FritzhomeDevice) -> bool:
"""Check suitablity for comfort temperature sensor."""
return device.has_thermostat and device.comfort_temperature is not None |
Check suitablity for next scheduled temperature sensor. | def suitable_nextchange_temperature(device: FritzhomeDevice) -> bool:
"""Check suitablity for next scheduled temperature sensor."""
return device.has_thermostat and device.nextchange_temperature is not None |
Check suitablity for next scheduled changed time sensor. | def suitable_nextchange_time(device: FritzhomeDevice) -> bool:
"""Check suitablity for next scheduled changed time sensor."""
return device.has_thermostat and device.nextchange_endperiod is not None |
Check suitablity for temperature sensor. | def suitable_temperature(device: FritzhomeDevice) -> bool:
"""Check suitablity for temperature sensor."""
return device.has_temperature_sensor and not device.has_thermostat |
Determine proper entity category for temperature sensor. | def entity_category_temperature(device: FritzhomeDevice) -> EntityCategory | None:
"""Determine proper entity category for temperature sensor."""
if device.has_switch or device.has_lightbulb:
return EntityCategory.DIAGNOSTIC
return None |
Return native value for next scheduled preset sensor. | def value_nextchange_preset(device: FritzhomeDevice) -> str:
"""Return native value for next scheduled preset sensor."""
if device.nextchange_temperature == device.eco_temperature:
return PRESET_ECO
return PRESET_COMFORT |
Return native value for current scheduled preset sensor. | def value_scheduled_preset(device: FritzhomeDevice) -> str:
"""Return native value for current scheduled preset sensor."""
if device.nextchange_temperature == device.eco_temperature:
return PRESET_COMFORT
return PRESET_ECO |
Return the title of the config flow. | def create_title(info: FroniusConfigEntryData) -> str:
"""Return the title of the config flow."""
return (
f"SolarNet {'Datalogger' if info['is_logger'] else 'Inverter'}"
f" at {info['host']}"
) |
Return a status message for a given status code. | def get_inverter_status_message(code: StateType) -> InverterStatusCodeOption:
"""Return a status message for a given status code."""
return _INVERTER_STATUS_CODES.get(code, InverterStatusCodeOption.INVALID) |
Return a location_description for a given location code. | def get_meter_location_description(code: StateType) -> MeterLocationCodeOption | None:
"""Return a location_description for a given location code."""
match int(code): # type: ignore[arg-type]
case 0:
return MeterLocationCodeOption.FEED_IN
case 1:
return MeterLocationCodeOption.CONSUMPTION_PATH
case 3:
return MeterLocationCodeOption.GENERATOR
case 4:
return MeterLocationCodeOption.EXT_BATTERY
case _ as _code if 256 <= _code <= 511:
return MeterLocationCodeOption.SUBLOAD
return None |
Return a status message for a given status code. | def get_ohmpilot_state_message(code: StateType) -> OhmPilotStateCodeOption | None:
"""Return a status message for a given status code."""
return _OHMPILOT_STATE_CODES.get(code) |
Set up frontend storage. | def _initialize_frontend_storage(hass: HomeAssistant) -> None:
"""Set up frontend storage."""
if DATA_STORAGE in hass.data:
return
hass.data[DATA_STORAGE] = ({}, {}) |
Decorate function to provide data. | def with_store(
orig_func: Callable[
[HomeAssistant, ActiveConnection, dict[str, Any], Store, dict[str, Any]],
Coroutine[Any, Any, None],
],
) -> Callable[
[HomeAssistant, ActiveConnection, dict[str, Any]], Coroutine[Any, Any, None]
]:
"""Decorate function to provide data."""
@wraps(orig_func)
async def with_store_func(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Provide user specific data and store to function."""
user_id = connection.user.id
store, user_data = await async_user_store(hass, user_id)
await orig_func(hass, connection, msg, store, user_data)
return with_store_func |
Register a built-in panel. | def async_register_built_in_panel(
hass: HomeAssistant,
component_name: str,
sidebar_title: str | None = None,
sidebar_icon: str | None = None,
frontend_url_path: str | None = None,
config: dict[str, Any] | None = None,
require_admin: bool = False,
*,
update: bool = False,
config_panel_domain: str | None = None,
) -> None:
"""Register a built-in panel."""
panel = Panel(
component_name,
sidebar_title,
sidebar_icon,
frontend_url_path,
config,
require_admin,
config_panel_domain,
)
panels = hass.data.setdefault(DATA_PANELS, {})
if not update and panel.frontend_url_path in panels:
raise ValueError(f"Overwriting panel {panel.frontend_url_path}")
panels[panel.frontend_url_path] = panel
hass.bus.async_fire(EVENT_PANELS_UPDATED) |
Remove a built-in panel. | def async_remove_panel(hass: HomeAssistant, frontend_url_path: str) -> None:
"""Remove a built-in panel."""
panel = hass.data.get(DATA_PANELS, {}).pop(frontend_url_path, None)
if panel is None:
_LOGGER.warning("Removing unknown panel %s", frontend_url_path)
hass.bus.async_fire(EVENT_PANELS_UPDATED) |
Register extra js or module url to load. | def add_extra_js_url(hass: HomeAssistant, url: str, es5: bool = False) -> None:
"""Register extra js or module url to load."""
key = DATA_EXTRA_JS_URL_ES5 if es5 else DATA_EXTRA_MODULE_URL
hass.data[key].add(url) |
Add a keyval to the manifest.json. | def add_manifest_json_key(key: str, val: Any) -> None:
"""Add a keyval to the manifest.json."""
MANIFEST_JSON.update_key(key, val) |
Return root path to the frontend files. | def _frontend_root(dev_repo_path: str | None) -> pathlib.Path:
"""Return root path to the frontend files."""
if dev_repo_path is not None:
return pathlib.Path(dev_repo_path) / "hass_frontend"
# Keep import here so that we can import frontend without installing reqs
# pylint: disable-next=import-outside-toplevel
import hass_frontend
return hass_frontend.where() |
Handle get panels command. | def websocket_get_panels(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle get panels command."""
user_is_admin = connection.user.is_admin
panels = {
panel_key: panel.to_response()
for panel_key, panel in connection.hass.data[DATA_PANELS].items()
if user_is_admin or not panel.require_admin
}
connection.send_message(websocket_api.result_message(msg["id"], panels)) |
Handle get themes command. | def websocket_get_themes(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle get themes command."""
if hass.config.recovery_mode or hass.config.safe_mode:
connection.send_message(
websocket_api.result_message(
msg["id"],
{
"themes": {},
"default_theme": "default",
},
)
)
return
connection.send_message(
websocket_api.result_message(
msg["id"],
{
"themes": hass.data[DATA_THEMES],
"default_theme": hass.data[DATA_DEFAULT_THEME],
"default_dark_theme": hass.data.get(DATA_DEFAULT_DARK_THEME),
},
)
) |
Create response payload for a single media item.
Used by async_browse_media. | def _item_preset_payload(preset: Preset, player_mode: str) -> BrowseMedia:
"""Create response payload for a single media item.
Used by async_browse_media.
"""
return BrowseMedia(
title=preset.name,
media_class=MediaClass.CHANNEL,
media_content_type=MediaType.CHANNEL,
# We add 1 to the preset key to keep it in sync with the numbering shown
# on the interface of the device
media_content_id=f"{player_mode}/{MEDIA_CONTENT_ID_PRESET}/{int(preset.key)+1}",
can_play=True,
can_expand=False,
) |
Create response payload for a single media item.
Used by async_browse_media. | def _item_payload(
key, item: dict[str, str], player_mode: str, parent_keys: list[str]
) -> BrowseMedia:
"""Create response payload for a single media item.
Used by async_browse_media.
"""
assert "label" in item or "name" in item
assert "type" in item
title = item.get("label") or item.get("name") or "Unknown"
title = title.strip()
media_content_id = "/".join(
[player_mode, MEDIA_CONTENT_ID_CHANNELS, *parent_keys, key]
)
media_class = (
FSAPI_ITEM_TYPE_TO_MEDIA_CLASS.get(int(item["type"])) or MediaClass.CHANNEL
)
return BrowseMedia(
title=title,
media_class=media_class,
media_content_type=MediaClass.CHANNEL,
media_content_id=media_content_id,
can_play=(media_class != MediaClass.DIRECTORY),
can_expand=(media_class == MediaClass.DIRECTORY),
) |
Return the hostname from a url. | def hostname_from_url(url: str) -> str:
"""Return the hostname from a url."""
return str(urlparse(url).hostname) |
Check if a MAC address is valid, non-locally administered address. | def valid_global_mac_address(mac: str | None) -> bool:
"""Check if a MAC address is valid, non-locally administered address."""
if not isinstance(mac, str):
return False
try:
first_octet = int(mac.split(":")[0], 16)
# If the second least-significant bit is set, it's a locally administered address, should not be used as an ID
return not bool(first_octet & 0x2)
except ValueError:
return False |
Convert storage values from bytes to megabytes. | def round_storage(value: int) -> float:
"""Convert storage values from bytes to megabytes."""
return round(value * 0.000001, 1) |
Truncate URL if longer than 256. | def truncate_url(value: StateType) -> tuple[StateType, dict[str, Any]]:
"""Truncate URL if longer than 256."""
url = str(value)
truncated = len(url) > 256
extra_state_attributes = {
"full_url": url,
"truncated": truncated,
}
if truncated:
return (url[0:255], extra_state_attributes)
return (url, extra_state_attributes) |
Set up the light platform for each FutureNow unit. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the light platform for each FutureNow unit."""
lights = []
for channel, device_config in config[CONF_DEVICES].items():
device = {}
device["name"] = device_config[CONF_NAME]
device["dimmable"] = device_config["dimmable"]
device["channel"] = channel
device["driver"] = config[CONF_DRIVER]
device["host"] = config[CONF_HOST]
device["port"] = config[CONF_PORT]
lights.append(FutureNowLight(device))
add_entities(lights, True) |
Convert the given Home Assistant light level (0-255) to FutureNow (0-100). | def to_futurenow_level(level):
"""Convert the given Home Assistant light level (0-255) to FutureNow (0-100)."""
return round((level * 100) / 255) |
Convert the given FutureNow (0-100) light level to Home Assistant (0-255). | def to_hass_level(level):
"""Convert the given FutureNow (0-100) light level to Home Assistant (0-255)."""
return int((level * 255) / 100) |
Set up the Garadget covers. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Garadget covers."""
covers = []
devices = config[CONF_COVERS]
for device_id, device_config in devices.items():
args = {
"name": device_config.get(CONF_NAME),
"device_id": device_config.get(CONF_DEVICE, device_id),
"username": device_config.get(CONF_USERNAME),
"password": device_config.get(CONF_PASSWORD),
"access_token": device_config.get(CONF_ACCESS_TOKEN),
}
covers.append(GaradgetCover(hass, args))
add_entities(covers) |
Check if device is supported. | def _is_supported(discovery_info: BluetoothServiceInfo):
"""Check if device is supported."""
if ScanService not in discovery_info.service_uuids:
return False
if not (data := discovery_info.manufacturer_data.get(ManufacturerData.company)):
_LOGGER.debug("Missing manufacturer data: %s", discovery_info)
return False
manufacturer_data = ManufacturerData.decode(data)
product_type = ProductType.from_manufacturer_data(manufacturer_data)
if product_type not in (
ProductType.PUMP,
ProductType.VALVE,
ProductType.WATER_COMPUTER,
):
_LOGGER.debug("Unsupported device: %s", manufacturer_data)
return False
return True |
Set up a cached client that keeps connection after last use. | def get_connection(hass: HomeAssistant, address: str) -> CachedConnection:
"""Set up a cached client that keeps connection after last use."""
def _device_lookup() -> BLEDevice:
device = bluetooth.async_ble_device_from_address(
hass, address, connectable=True
)
if not device:
raise DeviceUnavailable("Unable to find device")
return device
return CachedConnection(DISCONNECT_DELAY, _device_lookup) |
Set up the GC100 devices. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the GC100 devices."""
binary_sensors = []
ports = config[CONF_PORTS]
for port in ports:
for port_addr, port_name in port.items():
binary_sensors.append(
GC100BinarySensor(port_name, port_addr, hass.data[DATA_GC100])
)
add_entities(binary_sensors, True) |
Set up the GC100 devices. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the GC100 devices."""
switches = []
ports = config[CONF_PORTS]
for port in ports:
for port_addr, port_name in port.items():
switches.append(GC100Switch(port_name, port_addr, hass.data[DATA_GC100]))
add_entities(switches, True) |
Set up the gc100 component. | def setup(hass: HomeAssistant, base_config: ConfigType) -> bool:
"""Set up the gc100 component."""
config = base_config[DOMAIN]
host = config[CONF_HOST]
port = config[CONF_PORT]
gc_device = gc100.GC100SocketClient(host, port)
def cleanup_gc100(event):
"""Stuff to do before stopping."""
gc_device.quit()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, cleanup_gc100)
hass.data[DATA_GC100] = GC100Device(hass, gc_device)
return True |
Generate httpx.Auth object from credentials. | def generate_auth(device_info: Mapping[str, Any]) -> httpx.Auth | None:
"""Generate httpx.Auth object from credentials."""
username: str | None = device_info.get(CONF_USERNAME)
password: str | None = device_info.get(CONF_PASSWORD)
authentication = device_info.get(CONF_AUTHENTICATION)
if username and password:
if authentication == HTTP_DIGEST_AUTHENTICATION:
return httpx.DigestAuth(username=username, password=password)
return httpx.BasicAuth(username=username, password=password)
return None |
Create schema for camera config setup. | def build_schema(
user_input: Mapping[str, Any],
is_options_flow: bool = False,
show_advanced_options: bool = False,
) -> vol.Schema:
"""Create schema for camera config setup."""
spec = {
vol.Optional(
CONF_STILL_IMAGE_URL,
description={"suggested_value": user_input.get(CONF_STILL_IMAGE_URL, "")},
): str,
vol.Optional(
CONF_STREAM_SOURCE,
description={"suggested_value": user_input.get(CONF_STREAM_SOURCE, "")},
): str,
vol.Optional(
CONF_RTSP_TRANSPORT,
description={"suggested_value": user_input.get(CONF_RTSP_TRANSPORT)},
): vol.In(RTSP_TRANSPORTS),
vol.Optional(
CONF_AUTHENTICATION,
description={"suggested_value": user_input.get(CONF_AUTHENTICATION)},
): vol.In([HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION]),
vol.Optional(
CONF_USERNAME,
description={"suggested_value": user_input.get(CONF_USERNAME, "")},
): str,
vol.Optional(
CONF_PASSWORD,
description={"suggested_value": user_input.get(CONF_PASSWORD, "")},
): str,
vol.Required(
CONF_FRAMERATE,
description={"suggested_value": user_input.get(CONF_FRAMERATE, 2)},
): vol.All(vol.Range(min=0, min_included=False), cv.positive_float),
vol.Required(
CONF_VERIFY_SSL, default=user_input.get(CONF_VERIFY_SSL, True)
): bool,
}
if is_options_flow:
spec[
vol.Required(
CONF_LIMIT_REFETCH_TO_URL_CHANGE,
default=user_input.get(CONF_LIMIT_REFETCH_TO_URL_CHANGE, False),
)
] = bool
if show_advanced_options:
spec[
vol.Required(
CONF_USE_WALLCLOCK_AS_TIMESTAMPS,
default=user_input.get(CONF_USE_WALLCLOCK_AS_TIMESTAMPS, False),
)
] = bool
return vol.Schema(spec) |
Get the format of downloaded bytes that could be an image. | def get_image_type(image: bytes) -> str | None:
"""Get the format of downloaded bytes that could be an image."""
fmt = None
imagefile = io.BytesIO(image)
with contextlib.suppress(PIL.UnidentifiedImageError):
img = PIL.Image.open(imagefile)
fmt = img.format.lower() if img.format else None
if fmt is None:
# if PIL can't figure it out, could be svg.
with contextlib.suppress(UnicodeDecodeError):
if image.decode("utf-8").lstrip().startswith("<svg"):
return "svg+xml"
return fmt |
Convert a camera url into a string suitable for a camera name. | def slug(
hass: HomeAssistant, template: str | template_helper.Template | None
) -> str | None:
"""Convert a camera url into a string suitable for a camera name."""
url = ""
if not template:
return None
if not isinstance(template, template_helper.Template):
template = template_helper.Template(template, hass)
try:
url = template.async_render(parse_result=False)
return slugify(yarl.URL(url).host)
except (ValueError, TemplateError, TypeError) as err:
_LOGGER.error("Syntax error in '%s': %s", template, err)
return None |
Set up previews for camera feeds during config flow. | def register_preview(hass: HomeAssistant) -> None:
"""Set up previews for camera feeds during config flow."""
hass.data.setdefault(DOMAIN, {})
if not hass.data[DOMAIN].get(IMAGE_PREVIEWS_ACTIVE):
_LOGGER.debug("Registering camera image preview handler")
hass.http.register_view(CameraImagePreview(hass))
hass.data[DOMAIN][IMAGE_PREVIEWS_ACTIVE] = True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.