response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Trigger config flows for discovered devices. | def async_trigger_discovery(
hass: HomeAssistant,
discovered_devices: list[UnifiDevice],
) -> None:
"""Trigger config flows for discovered devices."""
for device in discovered_devices:
if device.services[UnifiService.Protect] and device.hw_addr:
discovery_flow.async_create_flow(
hass,
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=asdict(device),
) |
Generate a list of all the device entities. | def async_all_device_entities(
data: ProtectData,
klass: type[ProtectDeviceEntity],
camera_descs: Sequence[ProtectRequiredKeysMixin] | None = None,
light_descs: Sequence[ProtectRequiredKeysMixin] | None = None,
sense_descs: Sequence[ProtectRequiredKeysMixin] | None = None,
viewer_descs: Sequence[ProtectRequiredKeysMixin] | None = None,
lock_descs: Sequence[ProtectRequiredKeysMixin] | None = None,
chime_descs: Sequence[ProtectRequiredKeysMixin] | None = None,
all_descs: Sequence[ProtectRequiredKeysMixin] | None = None,
unadopted_descs: Sequence[ProtectRequiredKeysMixin] | None = None,
ufp_device: ProtectAdoptableDeviceModel | None = None,
) -> list[ProtectDeviceEntity]:
"""Generate a list of all the device entities."""
all_descs = list(all_descs or [])
unadopted_descs = list(unadopted_descs or [])
camera_descs = list(camera_descs or []) + all_descs
light_descs = list(light_descs or []) + all_descs
sense_descs = list(sense_descs or []) + all_descs
viewer_descs = list(viewer_descs or []) + all_descs
lock_descs = list(lock_descs or []) + all_descs
chime_descs = list(chime_descs or []) + all_descs
if ufp_device is None:
return (
_async_device_entities(
data, klass, ModelType.CAMERA, camera_descs, unadopted_descs
)
+ _async_device_entities(
data, klass, ModelType.LIGHT, light_descs, unadopted_descs
)
+ _async_device_entities(
data, klass, ModelType.SENSOR, sense_descs, unadopted_descs
)
+ _async_device_entities(
data, klass, ModelType.VIEWPORT, viewer_descs, unadopted_descs
)
+ _async_device_entities(
data, klass, ModelType.DOORLOCK, lock_descs, unadopted_descs
)
+ _async_device_entities(
data, klass, ModelType.CHIME, chime_descs, unadopted_descs
)
)
descs = []
if ufp_device.model is ModelType.CAMERA:
descs = camera_descs
elif ufp_device.model is ModelType.LIGHT:
descs = light_descs
elif ufp_device.model is ModelType.SENSOR:
descs = sense_descs
elif ufp_device.model is ModelType.VIEWPORT:
descs = viewer_descs
elif ufp_device.model is ModelType.DOORLOCK:
descs = lock_descs
elif ufp_device.model is ModelType.CHIME:
descs = chime_descs
if not descs and not unadopted_descs or ufp_device.model is None:
return []
return _async_device_entities(
data, klass, ufp_device.model, descs, unadopted_descs, ufp_device
) |
Convert unifi brightness 1..6 to hass format 0..255. | def unifi_brightness_to_hass(value: int) -> int:
"""Convert unifi brightness 1..6 to hass format 0..255."""
return min(255, round((value / 6) * 255)) |
Convert hass brightness 0..255 to unifi 1..6 scale. | def hass_to_unifi_brightness(value: int) -> int:
"""Convert hass brightness 0..255 to unifi 1..6 scale."""
return max(1, round((value / 255) * 6)) |
Get UniFi Protect event type from SimpleEventType. | def get_ufp_event(event_type: SimpleEventType) -> set[EventType]:
"""Get UniFi Protect event type from SimpleEventType."""
return EVENT_MAP[event_type] |
Check for usages of entities and return them. | def check_if_used(
hass: HomeAssistant, entry: ConfigEntry, entities: dict[str, EntityRef]
) -> dict[str, EntityUsage]:
"""Check for usages of entities and return them."""
entity_registry = er.async_get(hass)
refs: dict[str, EntityUsage] = {
ref: {"automations": {}, "scripts": {}} for ref in entities
}
for entity in er.async_entries_for_config_entry(entity_registry, entry.entry_id):
for ref_id, ref in entities.items():
if (
entity.domain == ref["platform"]
and entity.disabled_by is None
and ref["id"] in entity.unique_id
):
entity_automations = automations_with_entity(hass, entity.entity_id)
entity_scripts = scripts_with_entity(hass, entity.entity_id)
if entity_automations:
refs[ref_id]["automations"][entity.entity_id] = entity_automations
if entity_scripts:
refs[ref_id]["scripts"][entity.entity_id] = entity_scripts
return refs |
Create repairs for used entities that are deprecated. | def create_repair_if_used(
hass: HomeAssistant,
entry: ConfigEntry,
breaks_in: str,
entities: dict[str, EntityRef],
) -> None:
"""Create repairs for used entities that are deprecated."""
usages = check_if_used(hass, entry, entities)
for ref_id, refs in usages.items():
issue_id = f"deprecate_{ref_id}"
automations = refs["automations"]
scripts = refs["scripts"]
if automations or scripts:
items = sorted(
set(chain.from_iterable(chain(automations.values(), scripts.values())))
)
ir.async_create_issue(
hass,
DOMAIN,
issue_id,
is_fixable=False,
breaks_in_ha_version=breaks_in,
severity=IssueSeverity.WARNING,
translation_key=issue_id,
translation_placeholders={
"items": "* `" + "`\n* `".join(items) + "`\n"
},
)
else:
_LOGGER.debug("No found usages of %s", ref_id)
ir.async_delete_issue(hass, DOMAIN, issue_id) |
Check for usages of hdr_mode switch and package sensor and raise repair if it is used.
UniFi Protect v3.0.22 changed how HDR works so it is no longer a simple on/off toggle. There is
Always On, Always Off and Auto. So it has been migrated to a select. The old switch is now deprecated.
Additionally, the Package sensor is no longer functional due to how events work so a repair to notify users.
Added in 2024.4.0 | def async_deprecate_hdr_package(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Check for usages of hdr_mode switch and package sensor and raise repair if it is used.
UniFi Protect v3.0.22 changed how HDR works so it is no longer a simple on/off toggle. There is
Always On, Always Off and Auto. So it has been migrated to a select. The old switch is now deprecated.
Additionally, the Package sensor is no longer functional due to how events work so a repair to notify users.
Added in 2024.4.0
"""
create_repair_if_used(
hass,
entry,
"2024.10.0",
{
"hdr_switch": {"id": "hdr_mode", "platform": Platform.SWITCH},
"package_sensor": {
"id": "smart_obj_package",
"platform": Platform.BINARY_SENSOR,
},
},
) |
Split string to tuple. | def split_tuple(value: tuple[str, ...] | str | None) -> tuple[str, ...] | None:
"""Split string to tuple."""
if value is None:
return None
if TYPE_CHECKING:
assert isinstance(value, str)
return tuple(value.split(".")) |
Extract the MAC address from the registry entry unique id. | def _async_unique_id_to_mac(unique_id: str) -> str:
"""Extract the MAC address from the registry entry unique id."""
return unique_id.split("_")[0] |
Set up the global UniFi Protect services. | def async_setup_services(hass: HomeAssistant) -> None:
"""Set up the global UniFi Protect services."""
services = [
(
SERVICE_ADD_DOORBELL_TEXT,
functools.partial(add_doorbell_text, hass),
DOORBELL_TEXT_SCHEMA,
),
(
SERVICE_REMOVE_DOORBELL_TEXT,
functools.partial(remove_doorbell_text, hass),
DOORBELL_TEXT_SCHEMA,
),
(
SERVICE_SET_DEFAULT_DOORBELL_TEXT,
functools.partial(set_default_doorbell_text, hass),
DOORBELL_TEXT_SCHEMA,
),
(
SERVICE_SET_CHIME_PAIRED,
functools.partial(set_chime_paired_doorbells, hass),
CHIME_PAIRED_SCHEMA,
),
(
SERVICE_REMOVE_PRIVACY_ZONE,
functools.partial(remove_privacy_zone, hass),
REMOVE_PRIVACY_ZONE_SCHEMA,
),
]
for name, method, schema in services:
if hass.services.has_service(DOMAIN, name):
continue
hass.services.async_register(DOMAIN, name, method, schema=schema) |
Cleanup global UniFi Protect services (if all config entries unloaded). | def async_cleanup_services(hass: HomeAssistant) -> None:
"""Cleanup global UniFi Protect services (if all config entries unloaded)."""
loaded_entries = [
entry
for entry in hass.config_entries.async_entries(DOMAIN)
if entry.state == ConfigEntryState.LOADED
]
if len(loaded_entries) == 1:
for name in ALL_GLOBAL_SERIVCES:
hass.services.async_remove(DOMAIN, name) |
Fetch a nested attribute. | def get_nested_attr(obj: Any, attrs: tuple[str, ...]) -> Any:
"""Fetch a nested attribute."""
if len(attrs) == 1:
value = getattr(obj, attrs[0], None)
else:
value = obj
for key in attrs:
if (value := getattr(value, key, _SENTINEL)) is _SENTINEL:
return None
return value.value if isinstance(value, Enum) else value |
Get the short mac address from the full mac. | def _async_short_mac(mac: str) -> str:
"""Get the short mac address from the full mac."""
return _async_unifi_mac_from_hass(mac)[-6:] |
Get devices by type. | def async_get_devices_by_type(
bootstrap: Bootstrap, device_type: ModelType
) -> dict[str, ProtectAdoptableDeviceModel]:
"""Get devices by type."""
devices: dict[str, ProtectAdoptableDeviceModel] = getattr(
bootstrap, f"{device_type.value}s"
)
return devices |
Return all device by type. | def async_get_devices(
bootstrap: Bootstrap, model_type: Iterable[ModelType]
) -> Generator[ProtectAdoptableDeviceModel, None, None]:
"""Return all device by type."""
return (
device
for device_type in model_type
for device in async_get_devices_by_type(bootstrap, device_type).values()
) |
Get light motion mode for Flood Light. | def async_get_light_motion_current(obj: Light) -> str:
"""Get light motion mode for Flood Light."""
if (
obj.light_mode_settings.mode is LightModeType.MOTION
and obj.light_mode_settings.enable_at is LightModeEnableType.DARK
):
return f"{LightModeType.MOTION.value}Dark"
return obj.light_mode_settings.mode.value |
Generate entry specific dispatch ID. | def async_dispatch_id(entry: ConfigEntry, dispatch: str) -> str:
"""Generate entry specific dispatch ID."""
return f"{DOMAIN}.{entry.entry_id}.{dispatch}" |
Create ProtectApiClient from config entry. | def async_create_api_client(
hass: HomeAssistant, entry: ConfigEntry
) -> ProtectApiClient:
"""Create ProtectApiClient from config entry."""
session = async_create_clientsession(hass, cookie_jar=CookieJar(unsafe=True))
return ProtectApiClient(
host=entry.data[CONF_HOST],
port=entry.data[CONF_PORT],
username=entry.data[CONF_USERNAME],
password=entry.data[CONF_PASSWORD],
verify_ssl=entry.data[CONF_VERIFY_SSL],
session=session,
subscribed_models=DEVICES_FOR_SUBSCRIBE,
override_connection_host=entry.options.get(CONF_OVERRIDE_CHOST, False),
ignore_stats=not entry.options.get(CONF_ALL_UPDATES, False),
ignore_unadopted=False,
cache_dir=Path(hass.config.path(STORAGE_DIR, "unifiprotect")),
config_dir=Path(hass.config.path(STORAGE_DIR, "unifiprotect")),
) |
Get base name for cameras channel. | def get_camera_base_name(channel: CameraChannel) -> str:
"""Get base name for cameras channel."""
camera_name = channel.name
if channel.name != "Package Camera":
camera_name = f"{channel.name} Resolution Channel"
return camera_name |
Generate URL for event thumbnail. | def async_generate_thumbnail_url(
event_id: str,
nvr_id: str,
width: int | None = None,
height: int | None = None,
) -> str:
"""Generate URL for event thumbnail."""
url_format = ThumbnailProxyView.url or "{nvr_id}/{event_id}"
url = url_format.format(nvr_id=nvr_id, event_id=event_id)
params = {}
if width is not None:
params["width"] = str(width)
if height is not None:
params["height"] = str(height)
return f"{url}?{urlencode(params)}" |
Generate URL for event video. | def async_generate_event_video_url(event: Event) -> str:
"""Generate URL for event video."""
_validate_event(event)
if event.start is None or event.end is None:
raise ValueError("Event is ongoing")
url_format = VideoProxyView.url or "{nvr_id}/{camera_id}/{start}/{end}"
return url_format.format(
nvr_id=event.api.bootstrap.nvr.id,
camera_id=event.camera_id,
start=event.start.replace(microsecond=0).isoformat(),
end=event.end.replace(microsecond=0).isoformat(),
) |
Validate the configuration and return a Unifi direct scanner. | def get_scanner(hass: HomeAssistant, config: ConfigType) -> UnifiDeviceScanner | None:
"""Validate the configuration and return a Unifi direct scanner."""
scanner = UnifiDeviceScanner(config[DOMAIN])
return scanner if scanner.update_clients() else None |
Get signal name for updates to a config entry. | def _config_entry_update_signal_name(config_entry: ConfigEntry) -> str:
"""Get signal name for updates to a config entry."""
return CONFIG_ENTRY_UPDATE_SIGNAL_TEMPLATE.format(config_entry.unique_id) |
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
if old_attrs.get(ATTR_INSTALLED_VERSION) != new_attrs.get(ATTR_INSTALLED_VERSION):
return True
if old_attrs.get(ATTR_LATEST_VERSION) != new_attrs.get(ATTR_LATEST_VERSION):
return True
return False |
Return True if version is newer. | def _version_is_newer(latest_version: str, installed_version: str) -> bool:
"""Return True if version is newer."""
return AwesomeVersion(latest_version) > installed_version |
Extract user-friendly name from discovery. | def _friendly_name_from_discovery(discovery_info: ssdp.SsdpServiceInfo) -> str:
"""Extract user-friendly name from discovery."""
return cast(
str,
discovery_info.upnp.get(ssdp.ATTR_UPNP_FRIENDLY_NAME)
or discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME)
or discovery_info.ssdp_headers.get("_host", ""),
) |
Test if discovery is complete and usable. | def _is_complete_discovery(discovery_info: ssdp.SsdpServiceInfo) -> bool:
"""Test if discovery is complete and usable."""
return bool(
discovery_info.ssdp_udn
and discovery_info.ssdp_st
and discovery_info.ssdp_all_locations
and discovery_info.ssdp_usn
) |
Test if discovery is a complete IGD device. | def _is_igd_device(discovery_info: ssdp.SsdpServiceInfo) -> bool:
"""Test if discovery is a complete IGD device."""
root_device_info = discovery_info.upnp
return root_device_info.get(ssdp.ATTR_UPNP_DEVICE_TYPE) in {ST_IGD_V1, ST_IGD_V2} |
Get the preferred location (an IPv4 location) from a set of locations. | def get_preferred_location(locations: set[str]) -> str:
"""Get the preferred location (an IPv4 location) from a set of locations."""
# Prefer IPv4 over IPv6.
for location in locations:
if location.startswith(("http://[", "https://[")):
continue
return location
# Fallback to any.
for location in locations:
return location
raise ValueError("No location found") |
Convert serial ListPortInfo to USBDevice. | def usb_device_from_port(port: ListPortInfo) -> USBDevice:
"""Convert serial ListPortInfo to USBDevice."""
return USBDevice(
device=port.device,
vid=f"{hex(port.vid)[2:]:0>4}".upper(),
pid=f"{hex(port.pid)[2:]:0>4}".upper(),
serial_number=port.serial_number,
manufacturer=port.manufacturer,
description=port.description,
) |
Register to receive a callback when a scan should be initiated. | def async_register_scan_request_callback(
hass: HomeAssistant, callback: CALLBACK_TYPE
) -> CALLBACK_TYPE:
"""Register to receive a callback when a scan should be initiated."""
discovery: USBDiscovery = hass.data[DOMAIN]
return discovery.async_register_scan_request_callback(callback) |
Register to receive a callback when the initial USB scan is done.
If the initial scan is already done, the callback is called immediately. | def async_register_initial_scan_callback(
hass: HomeAssistant, callback: CALLBACK_TYPE
) -> CALLBACK_TYPE:
"""Register to receive a callback when the initial USB scan is done.
If the initial scan is already done, the callback is called immediately.
"""
discovery: USBDiscovery = hass.data[DOMAIN]
return discovery.async_register_initial_scan_callback(callback) |
Return True is a USB device is present. | def async_is_plugged_in(hass: HomeAssistant, matcher: USBCallbackMatcher) -> bool:
"""Return True is a USB device is present."""
vid = matcher.get("vid", "")
pid = matcher.get("pid", "")
serial_number = matcher.get("serial_number", "")
manufacturer = matcher.get("manufacturer", "")
description = matcher.get("description", "")
if (
vid != vid.upper()
or pid != pid.upper()
or serial_number != serial_number.lower()
or manufacturer != manufacturer.lower()
or description != description.lower()
):
raise ValueError(
f"vid and pid must be uppercase, the rest lowercase in matcher {matcher!r}"
)
usb_discovery: USBDiscovery = hass.data[DOMAIN]
return any(
_is_matching(USBDevice(*device_tuple), matcher)
for device_tuple in usb_discovery.seen
) |
Return a human readable name from USBDevice attributes. | def human_readable_device_name(
device: str,
serial_number: str | None,
manufacturer: str | None,
description: str | None,
vid: str | None,
pid: str | None,
) -> str:
"""Return a human readable name from USBDevice attributes."""
device_details = f"{device}, s/n: {serial_number or 'n/a'}"
manufacturer_details = f" - {manufacturer}" if manufacturer else ""
vendor_details = f" - {vid}:{pid}" if vid else ""
full_details = f"{device_details}{manufacturer_details}{vendor_details}"
if not description:
return full_details
return f"{description[:26]} - {full_details}" |
Return a /dev/serial/by-id match for given device if available. | def get_serial_by_id(dev_path: str) -> str:
"""Return a /dev/serial/by-id match for given device if available."""
by_id = "/dev/serial/by-id"
if not os.path.isdir(by_id):
return dev_path
for path in (entry.path for entry in os.scandir(by_id) if entry.is_symlink()):
if os.path.realpath(path) == dev_path:
return path
return dev_path |
Match a lowercase version of the name. | def _fnmatch_lower(name: str | None, pattern: str) -> bool:
"""Match a lowercase version of the name."""
if name is None:
return False
return fnmatch.fnmatch(name.lower(), pattern) |
Return True if a device matches. | def _is_matching(device: USBDevice, matcher: USBMatcher | USBCallbackMatcher) -> bool:
"""Return True if a device matches."""
if "vid" in matcher and device.vid != matcher["vid"]:
return False
if "pid" in matcher and device.pid != matcher["pid"]:
return False
if "serial_number" in matcher and not _fnmatch_lower(
device.serial_number, matcher["serial_number"]
):
return False
if "manufacturer" in matcher and not _fnmatch_lower(
device.manufacturer, matcher["manufacturer"]
):
return False
if "description" in matcher and not _fnmatch_lower(
device.description, matcher["description"]
):
return False
return True |
Validate value is a number. | def validate_is_number(value):
"""Validate value is a number."""
if is_number(value):
return value
raise vol.Invalid("Value is not a number") |
Check that the pattern is well-formed. | def validate_cron_pattern(pattern):
"""Check that the pattern is well-formed."""
if croniter.is_valid(pattern):
return pattern
raise vol.Invalid("Invalid pattern") |
Check that if cron pattern is used, then meter type and offsite must be removed. | def period_or_cron(config):
"""Check that if cron pattern is used, then meter type and offsite must be removed."""
if CONF_CRON_PATTERN in config and CONF_METER_TYPE in config:
raise vol.Invalid(f"Use <{CONF_CRON_PATTERN}> or <{CONF_METER_TYPE}>")
if (
CONF_CRON_PATTERN in config
and CONF_METER_OFFSET in config
and config[CONF_METER_OFFSET] != DEFAULT_OFFSET
):
raise vol.Invalid(
f"When <{CONF_CRON_PATTERN}> is used <{CONF_METER_OFFSET}> has no meaning"
)
return config |
Check that time period does not include more than 28 days. | def max_28_days(config):
"""Check that time period does not include more than 28 days."""
if config.days >= 28:
raise vol.Invalid(
"Unsupported offset of more than 28 days, please use a cron pattern."
)
return config |
Discover cameras on a Unifi NVR. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Discover cameras on a Unifi NVR."""
addr = config[CONF_NVR]
key = config[CONF_KEY]
password = config[CONF_PASSWORD]
port = config[CONF_PORT]
ssl = config[CONF_SSL]
try:
# Exceptions may be raised in all method calls to the nvr library.
nvrconn = nvr.UVCRemote(addr, port, key, ssl=ssl)
cameras = nvrconn.index()
identifier = "id" if nvrconn.server_version >= (3, 2, 0) else "uuid"
# Filter out airCam models, which are not supported in the latest
# version of UnifiVideo and which are EOL by Ubiquiti
cameras = [
camera
for camera in cameras
if "airCam" not in nvrconn.get_camera(camera[identifier])["model"]
]
except nvr.NotAuthorized:
_LOGGER.error("Authorization failure while connecting to NVR")
return
except nvr.NvrError as ex:
_LOGGER.error("NVR refuses to talk to me: %s", str(ex))
raise PlatformNotReady from ex
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to NVR: %s", str(ex))
raise PlatformNotReady from ex
add_entities(
[
UnifiVideoCamera(nvrconn, camera[identifier], camera["name"], password)
for camera in cameras
],
True,
) |
Convert millisecond timestamp to datetime. | def timestamp_ms_to_date(epoch_ms: int) -> datetime | None:
"""Convert millisecond timestamp to datetime."""
if epoch_ms:
return utc_from_timestamp(epoch_ms / 1000)
return None |
Create a function to test a device condition. | def async_condition_from_config(
hass: HomeAssistant, config: ConfigType
) -> condition.ConditionCheckerType:
"""Create a function to test a device condition."""
if config[CONF_TYPE] == "is_docked":
test_states = [STATE_DOCKED]
else:
test_states = [STATE_CLEANING, STATE_RETURNING]
registry = er.async_get(hass)
entity_id = er.async_resolve_entity_id(registry, config[CONF_ENTITY_ID])
def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
"""Test if an entity is a certain state."""
return (
entity_id is not None
and (state := hass.states.get(entity_id)) is not None
and state.state in test_states
)
return test_is_state |
Describe group on off states. | def async_describe_on_off_states(
hass: HomeAssistant, registry: "GroupIntegrationRegistry"
) -> None:
"""Describe group on off states."""
registry.on_off_states(
DOMAIN,
{
STATE_ON,
STATE_CLEANING,
STATE_RETURNING,
STATE_ERROR,
},
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}
for attr_name in changed_attrs:
if attr_name != ATTR_BATTERY_LEVEL:
return True
old_attr_value = old_attrs.get(attr_name)
new_attr_value = new_attrs.get(attr_name)
if new_attr_value is None or not check_valid_float(new_attr_value):
# New attribute value is invalid, ignore it
continue
if old_attr_value is None or not check_valid_float(old_attr_value):
# Old attribute value was invalid, we should report again
return True
if check_absolute_change(old_attr_value, new_attr_value, 1.0):
return True
# no significant attribute change detected
return False |
Return if the vacuum is on based on the statemachine. | def is_on(hass: HomeAssistant, entity_id: str) -> bool:
"""Return if the vacuum is on based on the statemachine."""
return hass.states.is_state(entity_id, STATE_ON) |
Set up the departure sensor. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the departure sensor."""
planner = vasttrafik.JournyPlanner(config.get(CONF_KEY), config.get(CONF_SECRET))
add_entities(
(
VasttrafikDepartureSensor(
planner,
departure.get(CONF_NAME),
departure.get(CONF_FROM),
departure.get(CONF_HEADING),
departure.get(CONF_LINES),
departure.get(CONF_DELAY),
)
for departure in config[CONF_DEPARTURES]
),
True,
) |
Build per module diagnostics info. | def _build_module_diagnostics_info(module: VelbusModule) -> dict[str, Any]:
"""Build per module diagnostics info."""
data: dict[str, Any] = {
"type": module.get_type_name(),
"address": module.get_addresses(),
"name": module.get_name(),
"sw_version": module.get_sw_version(),
"is_loaded": module.is_loaded(),
"channels": _build_channels_diagnostics_info(module.get_channels()),
}
return data |
Build diagnostics info for all channels. | def _build_channels_diagnostics_info(
channels: dict[str, VelbusChannel],
) -> dict[str, Any]:
"""Build diagnostics info for all channels."""
data: dict[str, Any] = {}
for channel in channels.values():
data[str(channel.get_channel_number())] = channel.get_channel_info()
return data |
Catch command exceptions. | def api_call(
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 OSError as exc:
raise HomeAssistantError(
f"Could not execute {func.__name__} service for {self.name}"
) from exc
return cmd_wrapper |
Migrate old device identifiers. | def _migrate_device_identifiers(hass: HomeAssistant, entry_id: str) -> None:
"""Migrate old device identifiers."""
dev_reg = dr.async_get(hass)
devices: list[dr.DeviceEntry] = dr.async_entries_for_config_entry(dev_reg, entry_id)
for device in devices:
old_identifier = list(next(iter(device.identifiers)))
if len(old_identifier) > 2:
new_identifier = {(old_identifier.pop(0), old_identifier.pop(0))}
_LOGGER.debug(
"migrate identifier '%s' to '%s'", device.identifiers, new_identifier
)
dev_reg.async_update_device(device.id, new_identifiers=new_identifier) |
Return the correct unit for temperature. | def temperature_unit(coordinator: VenstarDataUpdateCoordinator) -> str:
"""Return the correct unit for temperature."""
unit = UnitOfTemperature.CELSIUS
if coordinator.client.tempunits == coordinator.client.TEMPUNITS_F:
unit = UnitOfTemperature.FAHRENHEIT
return unit |
Get configured platforms for a controller. | def get_configured_platforms(controller_data: ControllerData) -> set[Platform]:
"""Get configured platforms for a controller."""
platforms: list[Platform] = list(controller_data.devices)
if controller_data.scenes:
platforms.append(Platform.SCENE)
return set(platforms) |
Get controller data from hass data. | def get_controller_data(
hass: HomeAssistant, config_entry: ConfigEntry
) -> ControllerData:
"""Get controller data from hass data."""
return hass.data[DOMAIN][config_entry.entry_id] |
Set controller data in hass data. | def set_controller_data(
hass: HomeAssistant, config_entry: ConfigEntry, data: ControllerData
) -> None:
"""Set controller data in hass data."""
hass.data[DOMAIN][config_entry.entry_id] = data |
Fix the id list by converting it to a supported int list. | def fix_device_id_list(data: list[Any]) -> list[int]:
"""Fix the id list by converting it to a supported int list."""
return str_to_int_list(list_to_str(data)) |
Convert a string to an int list. | def str_to_int_list(data: str) -> list[int]:
"""Convert a string to an int list."""
return [int(s) for s in LIST_REGEX.split(data) if len(s) > 0] |
Convert an int list to a string. | def list_to_str(data: list[Any]) -> str:
"""Convert an int list to a string."""
return " ".join([str(i) for i in data]) |
Create a standard options object. | def new_options(lights: list[int], exclude: list[int]) -> dict[str, list[int]]:
"""Create a standard options object."""
return {CONF_LIGHTS: lights, CONF_EXCLUDE: exclude} |
Return options schema. | def options_schema(
options: Mapping[str, Any] | None = None,
) -> dict[vol.Optional, type[str]]:
"""Return options schema."""
options = options or {}
return {
vol.Optional(
CONF_LIGHTS,
default=list_to_str(options.get(CONF_LIGHTS, [])),
): str,
vol.Optional(
CONF_EXCLUDE,
default=list_to_str(options.get(CONF_EXCLUDE, [])),
): str,
} |
Return options dict. | def options_data(user_input: dict[str, str]) -> dict[str, list[int]]:
"""Return options dict."""
return new_options(
str_to_int_list(user_input.get(CONF_LIGHTS, "")),
str_to_int_list(user_input.get(CONF_EXCLUDE, "")),
) |
Map vera classes to Home Assistant types. | def map_vera_device(
vera_device: veraApi.VeraDevice, remap: list[int]
) -> Platform | None:
"""Map vera classes to Home Assistant types."""
type_map = {
veraApi.VeraDimmer: Platform.LIGHT,
veraApi.VeraBinarySensor: Platform.BINARY_SENSOR,
veraApi.VeraSensor: Platform.SENSOR,
veraApi.VeraArmableDevice: Platform.SWITCH,
veraApi.VeraLock: Platform.LOCK,
veraApi.VeraThermostat: Platform.CLIMATE,
veraApi.VeraCurtain: Platform.COVER,
veraApi.VeraSceneController: Platform.SENSOR,
veraApi.VeraSwitch: Platform.SWITCH,
}
def map_special_case(instance_class: type, entity_type: Platform) -> Platform:
if instance_class is veraApi.VeraSwitch and vera_device.device_id in remap:
return Platform.LIGHT
return entity_type
return next(
iter(
map_special_case(instance_class, entity_type)
for instance_class, entity_type in type_map.items()
if isinstance(vera_device, instance_class)
),
None,
) |
Migrate old cookie file to new location. | def migrate_cookie_files(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Migrate old cookie file to new location."""
cookie_file = Path(hass.config.path(STORAGE_DIR, f"verisure_{entry.unique_id}"))
if cookie_file.exists():
cookie_file.rename(
hass.config.path(STORAGE_DIR, f"verisure_{entry.data[CONF_EMAIL]}")
) |
Add info from a peripheral to specified list. | def _add_entity_info(peripheral, device, entity_dict) -> None:
"""Add info from a peripheral to specified list."""
for measurement in peripheral.measurements:
entity_info = {
KEY_IDENTIFIER: peripheral.identifier,
KEY_UNIT: measurement.unit,
KEY_MEASUREMENT: measurement.name,
KEY_PARENT_NAME: device.name,
KEY_PARENT_MAC: device.mac,
}
key = f"{entity_info[KEY_PARENT_MAC]}/{entity_info[KEY_IDENTIFIER]}/{entity_info[KEY_MEASUREMENT]}"
entity_dict[key] = entity_info
return entity_dict |
Load platform with list of entity info. | def _load_platform(hass, config, entity_type, entity_info):
"""Load platform with list of entity info."""
hass.async_create_task(
async_load_platform(hass, entity_type, DOMAIN, entity_info, config)
) |
Build a dictionary of ALL VeSync devices. | def _build_device_dict(manager: VeSync) -> dict:
"""Build a dictionary of ALL VeSync devices."""
device_dict = {x.cid: x for x in manager.switches}
device_dict.update({x.cid: x for x in manager.fans})
device_dict.update({x.cid: x for x in manager.outlets})
device_dict.update({x.cid: x for x in manager.bulbs})
return device_dict |
Rebuild and redact values of a VeSync device. | def _redact_device_values(device: VeSyncBaseDevice) -> dict:
"""Rebuild and redact values of a VeSync device."""
data = {}
for key, item in device.__dict__.items():
if key not in KEYS_TO_REDACT:
data[key] = item
else:
data[key] = REDACTED
return data |
Check if device is online and add entity. | def _setup_entities(devices, async_add_entities):
"""Check if device is online and add entity."""
entities = []
for dev in devices:
if DEV_TYPE_TO_HA.get(SKU_TO_BASE_DEVICE.get(dev.device_type)) == "fan":
entities.append(VeSyncFanHA(dev))
else:
_LOGGER.warning(
"%s - Unknown device type - %s", dev.device_name, dev.device_type
)
continue
async_add_entities(entities, update_before_add=True) |
Check if device is online and add entity. | def _setup_entities(devices, async_add_entities):
"""Check if device is online and add entity."""
entities = []
for dev in devices:
if DEV_TYPE_TO_HA.get(dev.device_type) in ("walldimmer", "bulb-dimmable"):
entities.append(VeSyncDimmableLightHA(dev))
elif DEV_TYPE_TO_HA.get(dev.device_type) in ("bulb-tunable-white",):
entities.append(VeSyncTunableWhiteLightHA(dev))
else:
_LOGGER.debug(
"%s - Unknown device type - %s", dev.device_name, dev.device_type
)
continue
async_add_entities(entities, update_before_add=True) |
Update outlet details and energy usage. | def update_energy(device):
"""Update outlet details and energy usage."""
device.update()
device.update_energy() |
Get the base device of which a device is an instance. | def sku_supported(device, supported):
"""Get the base device of which a device is an instance."""
return SKU_TO_BASE_DEVICE.get(device.device_type) in supported |
Get the homeassistant device_type for a given device. | def ha_dev_type(device):
"""Get the homeassistant device_type for a given device."""
return DEV_TYPE_TO_HA.get(device.device_type) |
Check if device is online and add entity. | def _setup_entities(devices, async_add_entities):
"""Check if device is online and add entity."""
async_add_entities(
(
VeSyncSensorEntity(dev, description)
for dev in devices
for description in SENSORS
if description.exists_fn(dev)
),
update_before_add=True,
) |
Check if device is online and add entity. | def _setup_entities(devices, async_add_entities):
"""Check if device is online and add entity."""
entities = []
for dev in devices:
if DEV_TYPE_TO_HA.get(dev.device_type) == "outlet":
entities.append(VeSyncSwitchHA(dev))
elif DEV_TYPE_TO_HA.get(dev.device_type) == "switch":
entities.append(VeSyncLightSwitch(dev))
else:
_LOGGER.warning(
"%s - Unknown device type - %s", dev.device_name, dev.device_type
)
continue
async_add_entities(entities, update_before_add=True) |
Create ViCare binary sensor entities for a device. | def _build_entities(
device_list: list[ViCareDevice],
) -> list[ViCareBinarySensor]:
"""Create ViCare binary sensor entities for a device."""
entities: list[ViCareBinarySensor] = []
for device in device_list:
entities.extend(_build_entities_for_device(device.api, device.config))
entities.extend(
_build_entities_for_component(
get_circuits(device.api), device.config, CIRCUIT_SENSORS
)
)
entities.extend(
_build_entities_for_component(
get_burners(device.api), device.config, BURNER_SENSORS
)
)
entities.extend(
_build_entities_for_component(
get_compressors(device.api), device.config, COMPRESSOR_SENSORS
)
)
return entities |
Create device specific ViCare binary sensor entities. | def _build_entities_for_device(
device: PyViCareDevice,
device_config: PyViCareDeviceConfig,
) -> list[ViCareBinarySensor]:
"""Create device specific ViCare binary sensor entities."""
return [
ViCareBinarySensor(
device,
device_config,
description,
)
for description in GLOBAL_SENSORS
if is_supported(description.key, description, device)
] |
Create component specific ViCare binary sensor entities. | def _build_entities_for_component(
components: list[PyViCareHeatingDeviceWithComponent],
device_config: PyViCareDeviceConfig,
entity_descriptions: tuple[ViCareBinarySensorEntityDescription, ...],
) -> list[ViCareBinarySensor]:
"""Create component specific ViCare binary sensor entities."""
return [
ViCareBinarySensor(
component,
device_config,
description,
)
for component in components
for description in entity_descriptions
if is_supported(description.key, description, component)
] |
Create ViCare button entities for a device. | def _build_entities(
device_list: list[ViCareDevice],
) -> list[ViCareButton]:
"""Create ViCare button entities for a device."""
return [
ViCareButton(
device.api,
device.config,
description,
)
for device in device_list
for description in BUTTON_DESCRIPTIONS
if is_supported(description.key, description, device.api)
] |
Create ViCare climate entities for a device. | def _build_entities(
device_list: list[ViCareDevice],
) -> list[ViCareClimate]:
"""Create ViCare climate entities for a device."""
return [
ViCareClimate(
device.api,
circuit,
device.config,
"heating",
)
for device in device_list
for circuit in get_circuits(device.api)
] |
Create ViCare number entities for a device. | def _build_entities(
device_list: list[ViCareDevice],
) -> list[ViCareNumber]:
"""Create ViCare number entities for a device."""
entities: list[ViCareNumber] = [
ViCareNumber(
device.api,
device.config,
description,
)
for device in device_list
for description in DEVICE_ENTITY_DESCRIPTIONS
if is_supported(description.key, description, device.api)
]
entities.extend(
[
ViCareNumber(
circuit,
device.config,
description,
)
for device in device_list
for circuit in get_circuits(device.api)
for description in CIRCUIT_ENTITY_DESCRIPTIONS
if is_supported(description.key, description, circuit)
]
)
return entities |
Create ViCare sensor entities for a device. | def _build_entities(
device_list: list[ViCareDevice],
) -> list[ViCareSensor]:
"""Create ViCare sensor entities for a device."""
entities: list[ViCareSensor] = []
for device in device_list:
entities.extend(_build_entities_for_device(device.api, device.config))
entities.extend(
_build_entities_for_component(
get_circuits(device.api), device.config, CIRCUIT_SENSORS
)
)
entities.extend(
_build_entities_for_component(
get_burners(device.api), device.config, BURNER_SENSORS
)
)
entities.extend(
_build_entities_for_component(
get_compressors(device.api), device.config, COMPRESSOR_SENSORS
)
)
return entities |
Create device specific ViCare sensor entities. | def _build_entities_for_device(
device: PyViCareDevice,
device_config: PyViCareDeviceConfig,
) -> list[ViCareSensor]:
"""Create device specific ViCare sensor entities."""
return [
ViCareSensor(
device,
device_config,
description,
)
for description in GLOBAL_SENSORS
if is_supported(description.key, description, device)
] |
Create component specific ViCare sensor entities. | def _build_entities_for_component(
components: list[PyViCareHeatingDeviceWithComponent],
device_config: PyViCareDeviceConfig,
entity_descriptions: tuple[ViCareSensorEntityDescription, ...],
) -> list[ViCareSensor]:
"""Create component specific ViCare sensor entities."""
return [
ViCareSensor(
component,
device_config,
description,
)
for component in components
for description in entity_descriptions
if is_supported(description.key, description, component)
] |
Get device for device config. | def get_device(
entry: ConfigEntry, device_config: PyViCareDeviceConfig
) -> PyViCareDevice:
"""Get device for device config."""
return getattr(
device_config,
HEATING_TYPE_TO_CREATOR_METHOD[HeatingType(entry.data[CONF_HEATING_TYPE])],
)() |
Check if the PyViCare device supports the requested sensor. | def is_supported(
name: str,
entity_description: ViCareRequiredKeysMixin,
vicare_device,
) -> bool:
"""Check if the PyViCare device supports the requested sensor."""
try:
entity_description.value_getter(vicare_device)
except PyViCareNotSupportedFeatureError:
_LOGGER.debug("Feature not supported %s", name)
return False
except AttributeError as error:
_LOGGER.debug("Feature not supported %s: %s", name, error)
return False
_LOGGER.debug("Found entity %s", name)
return True |
Return the list of burners. | def get_burners(device: PyViCareDevice) -> list[PyViCareHeatingDeviceComponent]:
"""Return the list of burners."""
try:
return device.burners
except PyViCareNotSupportedFeatureError:
_LOGGER.debug("No burners found")
except AttributeError as error:
_LOGGER.debug("No burners found: %s", error)
return [] |
Return the list of circuits. | def get_circuits(device: PyViCareDevice) -> list[PyViCareHeatingDeviceComponent]:
"""Return the list of circuits."""
try:
return device.circuits
except PyViCareNotSupportedFeatureError:
_LOGGER.debug("No circuits found")
except AttributeError as error:
_LOGGER.debug("No circuits found: %s", error)
return [] |
Return the list of compressors. | def get_compressors(device: PyViCareDevice) -> list[PyViCareHeatingDeviceComponent]:
"""Return the list of compressors."""
try:
return device.compressors
except PyViCareNotSupportedFeatureError:
_LOGGER.debug("No compressors found")
except AttributeError as error:
_LOGGER.debug("No compressors found: %s", error)
return [] |
Create ViCare domestic hot water entities for a device. | def _build_entities(
device_list: list[ViCareDevice],
) -> list[ViCareWater]:
"""Create ViCare domestic hot water entities for a device."""
return [
ViCareWater(
device.api,
circuit,
device.config,
"domestic_hot_water",
)
for device in device_list
for circuit in get_circuits(device.api)
] |
Login via PyVicare API. | def vicare_login(
hass: HomeAssistant,
entry_data: Mapping[str, Any],
cache_duration=DEFAULT_CACHE_DURATION,
) -> PyViCare:
"""Login via PyVicare API."""
vicare_api = PyViCare()
vicare_api.setCacheDuration(cache_duration)
vicare_api.initWithCredentials(
entry_data[CONF_USERNAME],
entry_data[CONF_PASSWORD],
entry_data[CONF_CLIENT_ID],
hass.config.path(STORAGE_DIR, _TOKEN_FILENAME),
)
return vicare_api |
Set up PyVicare API. | def setup_vicare_api(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Set up PyVicare API."""
vicare_api = vicare_login(hass, entry.data)
device_config_list = get_supported_devices(vicare_api.devices)
if (number_of_devices := len(device_config_list)) > 1:
cache_duration = DEFAULT_CACHE_DURATION * number_of_devices
_LOGGER.debug(
"Found %s devices, adjusting cache duration to %s",
number_of_devices,
cache_duration,
)
vicare_api = vicare_login(hass, entry.data, cache_duration)
device_config_list = get_supported_devices(vicare_api.devices)
for device in device_config_list:
_LOGGER.debug(
"Found device: %s (online: %s)", device.getModel(), str(device.isOnline())
)
hass.data[DOMAIN][entry.entry_id][DEVICE_LIST] = [
ViCareDevice(config=device_config, api=get_device(entry, device_config))
for device_config in device_config_list
] |
Remove unsupported devices from the list. | def get_supported_devices(
devices: list[PyViCareDeviceConfig],
) -> list[PyViCareDeviceConfig]:
"""Remove unsupported devices from the list."""
return [
device_config
for device_config in devices
if device_config.getModel() not in UNSUPPORTED_DEVICES
] |
Attempt to connect and call the ping endpoint and, if successful, fetch basic information. | def _try_connect_and_fetch_basic_info(host, token):
"""Attempt to connect and call the ping endpoint and, if successful, fetch basic information."""
# Perform the ping. This doesn't validate authentication.
controller = VilfoClient(host=host, token=token)
result = {"type": None, "data": {}}
try:
controller.ping()
except VilfoException:
result["type"] = RESULT_CANNOT_CONNECT
result["data"] = CannotConnect
return result
# Perform a call that requires authentication.
try:
controller.get_board_information()
except VilfoAuthenticationException:
result["type"] = RESULT_INVALID_AUTH
result["data"] = InvalidAuth
return result
if controller.mac:
result["data"][CONF_ID] = controller.mac
result["data"][CONF_MAC] = controller.mac
else:
result["data"][CONF_ID] = host
result["data"][CONF_MAC] = None
result["type"] = RESULT_SUCCESS
return result |
Set up a Vivotek IP Camera. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up a Vivotek IP Camera."""
creds = f"{config[CONF_USERNAME]}:{config[CONF_PASSWORD]}"
args = {
"config": config,
"cam": VivotekCamera(
host=config[CONF_IP_ADDRESS],
port=(443 if config[CONF_SSL] else 80),
verify_ssl=config[CONF_VERIFY_SSL],
usr=config[CONF_USERNAME],
pwd=config[CONF_PASSWORD],
digest_auth=config[CONF_AUTHENTICATION] == HTTP_DIGEST_AUTHENTICATION,
sec_lvl=config[CONF_SECURITY_LEVEL],
),
"stream_source": (
f"rtsp://{creds}@{config[CONF_IP_ADDRESS]}:554/{config[CONF_STREAM_PATH]}"
),
}
add_entities([VivotekCam(**args)], True) |
Return schema defaults for init step based on user input/config dict.
Retain info already provided for future form views by setting them
as defaults in schema. | def _get_config_schema(input_dict: dict[str, Any] | None = None) -> vol.Schema:
"""Return schema defaults for init step based on user input/config dict.
Retain info already provided for future form views by setting them
as defaults in schema.
"""
if input_dict is None:
input_dict = {}
return vol.Schema(
{
vol.Required(
CONF_NAME, default=input_dict.get(CONF_NAME, DEFAULT_NAME)
): str,
vol.Required(CONF_HOST, default=input_dict.get(CONF_HOST)): str,
vol.Required(
CONF_DEVICE_CLASS,
default=input_dict.get(CONF_DEVICE_CLASS, DEFAULT_DEVICE_CLASS),
): vol.All(
str,
vol.Lower,
vol.In([MediaPlayerDeviceClass.TV, MediaPlayerDeviceClass.SPEAKER]),
),
vol.Optional(
CONF_ACCESS_TOKEN, default=input_dict.get(CONF_ACCESS_TOKEN, "")
): str,
},
extra=vol.REMOVE_EXTRA,
) |
Return schema defaults for pairing data based on user input.
Retain info already provided for future form views by setting
them as defaults in schema. | def _get_pairing_schema(input_dict: dict[str, Any] | None = None) -> vol.Schema:
"""Return schema defaults for pairing data based on user input.
Retain info already provided for future form views by setting
them as defaults in schema.
"""
if input_dict is None:
input_dict = {}
return vol.Schema(
{vol.Required(CONF_PIN, default=input_dict.get(CONF_PIN, "")): str}
) |
Check if host1 and host2 are the same. | def _host_is_same(host1: str, host2: str) -> bool:
"""Check if host1 and host2 are the same."""
host1 = host1.split(":")[0]
host1 = host1 if is_ip_address(host1) else socket.gethostbyname(host1)
host2 = host2.split(":")[0]
host2 = host2 if is_ip_address(host2) else socket.gethostbyname(host2)
return host1 == host2 |
Validate CONF_APPS is only used when CONF_DEVICE_CLASS is MediaPlayerDeviceClass.TV. | def validate_apps(config: ConfigType) -> ConfigType:
"""Validate CONF_APPS is only used when CONF_DEVICE_CLASS is MediaPlayerDeviceClass.TV."""
if (
config.get(CONF_APPS) is not None
and config[CONF_DEVICE_CLASS] != MediaPlayerDeviceClass.TV
):
raise vol.Invalid(
f"'{CONF_APPS}' can only be used if {CONF_DEVICE_CLASS}' is"
f" '{MediaPlayerDeviceClass.TV}'"
)
return config |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.