response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Convert wilight position 1..255 to hass format 0..100. | def wilight_to_hass_position(value: int) -> int:
"""Convert wilight position 1..255 to hass format 0..100."""
return min(100, round((value * 100) / 255)) |
Convert hass position 0..100 to wilight 1..255 scale. | def hass_to_wilight_position(value: int) -> int:
"""Convert hass position 0..100 to wilight 1..255 scale."""
return min(255, round((value * 255) / 100)) |
Parse configuration and add WiLight light entities. | def entities_from_discovered_wilight(api_device: PyWiLightDevice) -> list[LightEntity]:
"""Parse configuration and add WiLight light entities."""
entities: list[LightEntity] = []
for item in api_device.items:
if item["type"] != ITEM_LIGHT:
continue
index = item["index"]
item_name = item["name"]
if item["sub_type"] == LIGHT_ON_OFF:
entities.append(WiLightLightOnOff(api_device, index, item_name))
elif item["sub_type"] == LIGHT_DIMMER:
entities.append(WiLightLightDimmer(api_device, index, item_name))
elif item["sub_type"] == LIGHT_COLOR:
entities.append(WiLightLightColor(api_device, index, item_name))
return entities |
Convert wilight hue 1..255 to hass 0..360 scale. | def wilight_to_hass_hue(value: int) -> float:
"""Convert wilight hue 1..255 to hass 0..360 scale."""
return min(360, round((value * 360) / 255, 3)) |
Convert hass hue 0..360 to wilight 1..255 scale. | def hass_to_wilight_hue(value: float) -> int:
"""Convert hass hue 0..360 to wilight 1..255 scale."""
return min(255, round((value * 255) / 360)) |
Convert wilight saturation 1..255 to hass 0..100 scale. | def wilight_to_hass_saturation(value: int) -> float:
"""Convert wilight saturation 1..255 to hass 0..100 scale."""
return min(100, round((value * 100) / 255, 3)) |
Convert hass saturation 0..100 to wilight 1..255 scale. | def hass_to_wilight_saturation(value: float) -> int:
"""Convert hass saturation 0..100 to wilight 1..255 scale."""
return min(255, round((value * 255) / 100)) |
Create an API Device. | def create_api_device(host: str) -> PyWiLightDevice:
"""Create an API Device."""
try:
return pywilight.device_from_host(host)
except (
requests.exceptions.ConnectionError,
requests.exceptions.Timeout,
) as err:
_LOGGER.error("Unable to access WiLight at %s (%s)", host, err)
return None |
Check rules for WiLight Trigger. | def wilight_trigger(value: Any) -> str | None:
"""Check rules for WiLight Trigger."""
step = 1
err_desc = "Value is None"
result_128 = False
result_24 = False
result_60 = False
result_2 = False
if value is not None:
step = 2
err_desc = "Expected a string"
if (step == 2) & isinstance(value, str):
step = 3
err_desc = "String should only contain 8 decimals character"
if re.search(r"^([0-9]{8})$", value) is not None:
step = 4
err_desc = "First 3 character should be less than 128"
result_128 = int(value[0:3]) < 128
result_24 = int(value[3:5]) < 24
result_60 = int(value[5:7]) < 60
result_2 = int(value[7:8]) < 2
if (step == 4) & result_128:
step = 5
err_desc = "Hour part should be less than 24"
if (step == 5) & result_24:
step = 6
err_desc = "Minute part should be less than 60"
if (step == 6) & result_60:
step = 7
err_desc = "Active part should be less than 2"
if (step == 7) & result_2:
return value
raise vol.Invalid(err_desc) |
Convert wilight trigger to hass description.
Ex: "12719001" -> "sun mon tue wed thu fri sat 19:00 On"
"00000000" -> "00:00 Off" | def wilight_to_hass_trigger(value: str | None) -> str | None:
"""Convert wilight trigger to hass description.
Ex: "12719001" -> "sun mon tue wed thu fri sat 19:00 On"
"00000000" -> "00:00 Off"
"""
if value is None:
return value
locale.setlocale(locale.LC_ALL, "")
week_days = list(calendar.day_abbr)
days = bin(int(value[0:3]))[2:].zfill(8)
desc = ""
if int(days[7:8]) == 1:
desc += f"{week_days[6]} "
if int(days[6:7]) == 1:
desc += f"{week_days[0]} "
if int(days[5:6]) == 1:
desc += f"{week_days[1]} "
if int(days[4:5]) == 1:
desc += f"{week_days[2]} "
if int(days[3:4]) == 1:
desc += f"{week_days[3]} "
if int(days[2:3]) == 1:
desc += f"{week_days[4]} "
if int(days[1:2]) == 1:
desc += f"{week_days[5]} "
desc += f"{value[3:5]}:{value[5:7]} "
if int(value[7:8]) == 1:
desc += "On"
else:
desc += "Off"
return desc |
Parse configuration and add WiLight switch entities. | def entities_from_discovered_wilight(api_device: PyWiLightDevice) -> tuple[Any]:
"""Parse configuration and add WiLight switch entities."""
entities: Any = []
for item in api_device.items:
if item["type"] == ITEM_SWITCH:
index = item["index"]
item_name = item["name"]
if item["sub_type"] == SWITCH_VALVE:
entities.append(WiLightValveSwitch(api_device, index, item_name))
elif item["sub_type"] == SWITCH_PAUSE_VALVE:
entities.append(WiLightValvePauseSwitch(api_device, index, item_name))
return entities |
Convert wilight pause_time seconds to hass hour. | def wilight_to_hass_pause_time(value: int) -> int:
"""Convert wilight pause_time seconds to hass hour."""
return round(value / 3600) |
Convert hass pause_time hours to wilight seconds. | def hass_to_wilight_pause_time(value: int) -> int:
"""Convert hass pause_time hours to wilight seconds."""
return round(value * 3600) |
Migrate old unique id to new one with use of tag's uuid. | def async_migrate_unique_id(
hass: HomeAssistant, tag: SensorTag, domain: str, key: str
) -> None:
"""Migrate old unique id to new one with use of tag's uuid."""
registry = er.async_get(hass)
new_unique_id = f"{tag.uuid}_{key}"
if registry.async_get_entity_id(domain, DOMAIN, new_unique_id):
return
old_unique_id = f"{tag.tag_id}_{key}"
if entity_id := registry.async_get_entity_id(domain, DOMAIN, old_unique_id):
_LOGGER.debug("Updating unique id for %s %s", key, entity_id)
registry.async_update_entity(entity_id, new_unique_id=new_unique_id) |
Set up the Wireless Sensor Tag component. | def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Wireless Sensor Tag component."""
conf = config[DOMAIN]
username = conf.get(CONF_USERNAME)
password = conf.get(CONF_PASSWORD)
try:
wirelesstags = WirelessTags(username=username, password=password)
platform = WirelessTagPlatform(hass, wirelesstags)
platform.load_tags()
platform.start_monitoring()
hass.data[DOMAIN] = platform
except (ConnectTimeout, HTTPError, WirelessTagsException) as ex:
_LOGGER.error("Unable to connect to wirelesstag.net service: %s", str(ex))
persistent_notification.create(
hass,
f"Error: {ex}<br />Please restart hass after fixing this.",
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
return False
return True |
Return human-readable category. | def get_event_name(category: WorkoutCategory) -> str:
"""Return human-readable category."""
name = category.name.lower().capitalize()
return name.replace("_", " ") |
Return a list of present goals. | def get_current_goals(goals: Goals) -> set[str]:
"""Return a list of present goals."""
result = set()
for goal in (STEP_GOAL, SLEEP_GOAL, WEIGHT_GOAL):
if getattr(goals, goal):
result.add(goal)
return result |
Produce common json output. | def json_message_response(message: str, message_code: int) -> Response:
"""Produce common json output."""
return HomeAssistantView.json({"message": message, "code": message_code}) |
Return webhook handler. | def get_webhook_handler(
withings_data: WithingsData,
) -> Callable[[HomeAssistant, str, Request], Awaitable[Response | None]]:
"""Return webhook handler."""
async def async_webhook_handler(
hass: HomeAssistant, webhook_id: str, request: Request
) -> Response | None:
# Handle http post calls to the path.
if not request.body_exists:
return json_message_response("No request body", message_code=12)
params = await request.post()
if "appli" not in params:
return json_message_response(
"Parameter appli not provided", message_code=20
)
notification_category = to_enum(
NotificationCategory,
int(params.getone("appli")), # type: ignore[arg-type]
NotificationCategory.UNKNOWN,
)
for coordinator in withings_data.coordinators:
if notification_category in coordinator.notification_categories:
await coordinator.async_webhook_data_updated(notification_category)
return json_message_response("Success", message_code=0)
return async_webhook_handler |
Trigger config flows for discovered devices. | def async_trigger_discovery(
hass: HomeAssistant,
discovered_devices: list[DiscoveredBulb],
) -> 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=asdict(device),
) |
Create the PilotBuilder for turn on. | def _async_pilot_builder(**kwargs: Any) -> PilotBuilder:
"""Create the PilotBuilder for turn on."""
brightness = kwargs.get(ATTR_BRIGHTNESS)
if ATTR_RGBWW_COLOR in kwargs:
return PilotBuilder(brightness=brightness, rgbww=kwargs[ATTR_RGBWW_COLOR])
if ATTR_RGBW_COLOR in kwargs:
return PilotBuilder(brightness=brightness, rgbw=kwargs[ATTR_RGBW_COLOR])
if ATTR_COLOR_TEMP in kwargs:
return PilotBuilder(
brightness=brightness,
colortemp=color_temperature_mired_to_kelvin(kwargs[ATTR_COLOR_TEMP]),
)
if ATTR_EFFECT in kwargs:
scene_id = get_id_from_scene_name(kwargs[ATTR_EFFECT])
if scene_id == 1000: # rhythm
return PilotBuilder()
return PilotBuilder(brightness=brightness, scene=scene_id)
return PilotBuilder(brightness=brightness) |
Get the short mac address from the full mac. | def _short_mac(mac: str) -> str:
"""Get the short mac address from the full mac."""
return mac.replace(":", "").upper()[-6:] |
Generate a name from bulb_type and mac. | def name_from_bulb_type_and_mac(bulb_type: BulbType, mac: str) -> str:
"""Generate a name from bulb_type and mac."""
if bulb_type.bulb_type == BulbClass.RGB:
if bulb_type.white_channels == 2:
description = "RGBWW Tunable"
else:
description = "RGBW Tunable"
else:
description = bulb_type.bulb_type.value
return f"{DEFAULT_NAME} {description} {_short_mac(mac)}" |
Decorate WLED calls to handle WLED exceptions.
A decorator that wraps the passed in function, catches WLED errors,
and handles the availability of the device in the data coordinator. | def wled_exception_handler(
func: Callable[Concatenate[_WLEDEntityT, _P], Coroutine[Any, Any, Any]],
) -> Callable[Concatenate[_WLEDEntityT, _P], Coroutine[Any, Any, None]]:
"""Decorate WLED calls to handle WLED exceptions.
A decorator that wraps the passed in function, catches WLED errors,
and handles the availability of the device in the data coordinator.
"""
async def handler(self: _WLEDEntityT, *args: _P.args, **kwargs: _P.kwargs) -> None:
try:
await func(self, *args, **kwargs)
self.coordinator.async_update_listeners()
except WLEDConnectionError as error:
self.coordinator.last_update_success = False
self.coordinator.async_update_listeners()
raise HomeAssistantError("Error communicating with WLED API") from error
except WLEDError as error:
raise HomeAssistantError("Invalid response from WLED API") from error
return handler |
Update segments. | def async_update_segments(
coordinator: WLEDDataUpdateCoordinator,
current_ids: set[int],
async_add_entities: AddEntitiesCallback,
) -> None:
"""Update segments."""
segment_ids = {light.segment_id for light in coordinator.data.state.segments}
new_entities: list[WLEDMainLight | WLEDSegmentLight] = []
# More than 1 segment now? No main? Add main controls
if not coordinator.keep_main_light and (
len(current_ids) < 2 and len(segment_ids) > 1
):
new_entities.append(WLEDMainLight(coordinator))
# Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids:
current_ids.add(segment_id)
new_entities.append(WLEDSegmentLight(coordinator, segment_id))
async_add_entities(new_entities) |
Update segments. | def async_update_segments(
coordinator: WLEDDataUpdateCoordinator,
current_ids: set[int],
async_add_entities: AddEntitiesCallback,
) -> None:
"""Update segments."""
segment_ids = {segment.segment_id for segment in coordinator.data.state.segments}
new_entities: list[WLEDNumber] = []
# Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids:
current_ids.add(segment_id)
new_entities.extend(
WLEDNumber(coordinator, segment_id, desc) for desc in NUMBERS
)
async_add_entities(new_entities) |
Update segments. | def async_update_segments(
coordinator: WLEDDataUpdateCoordinator,
current_ids: set[int],
async_add_entities: AddEntitiesCallback,
) -> None:
"""Update segments."""
segment_ids = {segment.segment_id for segment in coordinator.data.state.segments}
new_entities: list[WLEDPaletteSelect] = []
# Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids:
current_ids.add(segment_id)
new_entities.append(WLEDPaletteSelect(coordinator, segment_id))
async_add_entities(new_entities) |
Update segments. | def async_update_segments(
coordinator: WLEDDataUpdateCoordinator,
current_ids: set[int],
async_add_entities: AddEntitiesCallback,
) -> None:
"""Update segments."""
segment_ids = {segment.segment_id for segment in coordinator.data.state.segments}
new_entities: list[WLEDReverseSwitch] = []
# Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids:
current_ids.add(segment_id)
new_entities.append(WLEDReverseSwitch(coordinator, segment_id))
async_add_entities(new_entities) |
Validate and adds to list of dates to add or remove. | def validate_dates(holiday_list: list[str]) -> list[str]:
"""Validate and adds to list of dates to add or remove."""
calc_holidays: list[str] = []
for add_date in holiday_list:
if add_date.find(",") > 0:
dates = add_date.split(",", maxsplit=1)
d1 = dt_util.parse_date(dates[0])
d2 = dt_util.parse_date(dates[1])
if d1 is None or d2 is None:
LOGGER.error("Incorrect dates in date range: %s", add_date)
continue
_range: timedelta = d2 - d1
for i in range(_range.days + 1):
day: date = d1 + timedelta(days=i)
calc_holidays.append(day.strftime("%Y-%m-%d"))
continue
calc_holidays.append(add_date)
return calc_holidays |
Update schema with province from country. | def add_province_and_language_to_schema(
schema: vol.Schema,
country: str | None,
) -> vol.Schema:
"""Update schema with province from country."""
if not country:
return schema
all_countries = list_supported_countries(include_aliases=False)
language_schema = {}
province_schema = {}
_country = country_holidays(country=country)
if country_default_language := (_country.default_language):
selectable_languages = _country.supported_languages
new_selectable_languages = [lang[:2] for lang in selectable_languages]
language_schema = {
vol.Optional(
CONF_LANGUAGE, default=country_default_language
): LanguageSelector(
LanguageSelectorConfig(languages=new_selectable_languages)
)
}
if provinces := all_countries.get(country):
province_schema = {
vol.Optional(CONF_PROVINCE): SelectSelector(
SelectSelectorConfig(
options=provinces,
mode=SelectSelectorMode.DROPDOWN,
translation_key=CONF_PROVINCE,
)
),
}
return vol.Schema({**DATA_SCHEMA_OPT.schema, **language_schema, **province_schema}) |
Validate date range. | def _is_valid_date_range(check_date: str, error: type[HomeAssistantError]) -> bool:
"""Validate date range."""
if check_date.find(",") > 0:
dates = check_date.split(",", maxsplit=1)
for date in dates:
if dt_util.parse_date(date) is None:
raise error("Incorrect date in range")
return True
return False |
Validate custom dates for add/remove holidays. | def validate_custom_dates(user_input: dict[str, Any]) -> None:
"""Validate custom dates for add/remove holidays."""
for add_date in user_input[CONF_ADD_HOLIDAYS]:
if (
not _is_valid_date_range(add_date, AddDateRangeError)
and dt_util.parse_date(add_date) is None
):
raise AddDatesError("Incorrect date")
year: int = dt_util.now().year
if country := user_input.get(CONF_COUNTRY):
language = user_input.get(CONF_LANGUAGE)
province = user_input.get(CONF_PROVINCE)
obj_holidays = country_holidays(
country=country,
subdiv=province,
years=year,
language=language,
)
if (
supported_languages := obj_holidays.supported_languages
) and language == "en":
for lang in supported_languages:
if lang.startswith("en"):
obj_holidays = country_holidays(
country,
subdiv=province,
years=year,
language=lang,
)
else:
obj_holidays = HolidayBase(years=year)
for remove_date in user_input[CONF_REMOVE_HOLIDAYS]:
if (
not _is_valid_date_range(remove_date, RemoveDateRangeError)
and dt_util.parse_date(remove_date) is None
and obj_holidays.get_named(remove_date) == []
):
raise RemoveDatesError("Incorrect date or name") |
Set up the WorldTidesInfo sensor. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the WorldTidesInfo sensor."""
name = config.get(CONF_NAME)
lat = config.get(CONF_LATITUDE, hass.config.latitude)
lon = config.get(CONF_LONGITUDE, hass.config.longitude)
key = config.get(CONF_API_KEY)
if None in (lat, lon):
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
tides = WorldTidesInfoSensor(name, lat, lon, key)
tides.update()
if tides.data.get("error") == "No location found":
_LOGGER.error("Location not available")
return
add_entities([tides]) |
Verify a connection can be made to the WS66i. | def _verify_connection(ws66i: WS66i) -> bool:
"""Verify a connection can be made to the WS66i."""
try:
ws66i.open()
except ConnectionError as err:
raise CannotConnect from err
# Connection successful. Verify correct port was opened
# Test on FIRST_ZONE because this zone will always be valid
ret_val = ws66i.zone_status(FIRST_ZONE)
ws66i.close()
return bool(ret_val) |
Generate zones list by searching for presence of zones. | def _find_zones(hass: HomeAssistant, ws66i: WS66i) -> list[int]:
"""Generate zones list by searching for presence of zones."""
# Zones 11 - 16 are the master amp
# Zones 21,31 - 26,36 are the daisy-chained amps
zone_list = []
for amp_num in range(1, 4):
if amp_num > 1:
# Don't add entities that aren't present
status = ws66i.zone_status(amp_num * 10 + 1)
if status is None:
break
for zone_num in range(1, 7):
zone_id = (amp_num * 10) + zone_num
zone_list.append(zone_id)
_LOGGER.info("Detected %d amp(s)", amp_num - 1)
return zone_list |
Set up the WSDOT sensor. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the WSDOT sensor."""
sensors = []
for travel_time in config[CONF_TRAVEL_TIMES]:
name = travel_time.get(CONF_NAME) or travel_time.get(CONF_ID)
sensors.append(
WashingtonStateTravelTimeSensor(
name, config.get(CONF_API_KEY), travel_time.get(CONF_ID)
)
)
add_entities(sensors, True) |
Convert WSDOT timestamp to datetime. | def _parse_wsdot_timestamp(timestamp):
"""Convert WSDOT timestamp to datetime."""
if not timestamp:
return None
# ex: Date(1485040200000-0800)
milliseconds, tzone = re.search(r"Date\((\d+)([+-]\d\d)\d\d\)", timestamp).groups()
return datetime.fromtimestamp(
int(milliseconds) / 1000, tz=timezone(timedelta(hours=int(tzone)))
) |
Create Wyoming satellite/device from config entry and Wyoming service. | def _make_satellite(
hass: HomeAssistant, config_entry: ConfigEntry, service: WyomingService
) -> WyomingSatellite:
"""Create Wyoming satellite/device from config entry and Wyoming service."""
satellite_info = service.info.satellite
assert satellite_info is not None
dev_reg = dr.async_get(hass)
# Use config entry id since only one satellite per entry is supported
satellite_id = config_entry.entry_id
device = dev_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
identifiers={(DOMAIN, satellite_id)},
name=satellite_info.name,
suggested_area=satellite_info.area,
)
satellite_device = SatelliteDevice(
satellite_id=satellite_id,
device_id=device.id,
)
return WyomingSatellite(hass, service, satellite_device) |
Execute X10 command and check output. | def x10_command(command):
"""Execute X10 command and check output."""
return check_output(["heyu", *command.split(" ")], stderr=STDOUT) |
Get on/off status for given unit. | def get_unit_status(code):
"""Get on/off status for given unit."""
output = check_output(["heyu", "onstate", code])
return int(output.decode("utf-8")[0]) |
Set up the x10 Light platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the x10 Light platform."""
is_cm11a = True
try:
x10_command("info")
except CalledProcessError as err:
_LOGGER.info("Assuming that the device is CM17A: %s", err.output)
is_cm11a = False
add_entities(X10Light(light, is_cm11a) for light in config[CONF_DEVICES]) |
Update friends. | def async_update_friends(
coordinator: XboxUpdateCoordinator,
current: dict[str, list[XboxBinarySensorEntity]],
async_add_entities,
) -> None:
"""Update friends."""
new_ids = set(coordinator.data.presence)
current_ids = set(current)
# Process new favorites, add them to Home Assistant
new_entities: list[XboxBinarySensorEntity] = []
for xuid in new_ids - current_ids:
current[xuid] = [
XboxBinarySensorEntity(coordinator, xuid, attribute)
for attribute in PRESENCE_ATTRIBUTES
]
new_entities = new_entities + current[xuid]
async_add_entities(new_entities)
# Process deleted favorites, remove them from Home Assistant
for xuid in current_ids - new_ids:
coordinator.hass.async_create_task(
async_remove_entities(xuid, coordinator, current)
) |
Create response payload for a single media item. | def item_payload(item: InstalledPackage, images: dict[str, list[Image]]):
"""Create response payload for a single media item."""
thumbnail = None
image = _find_media_image(images.get(item.one_store_product_id, []))
if image is not None:
thumbnail = image.uri
if thumbnail[0] == "/":
thumbnail = f"https:{thumbnail}"
return BrowseMedia(
media_class=TYPE_MAP[item.content_type].cls,
media_content_id=item.one_store_product_id,
media_content_type=TYPE_MAP[item.content_type].type,
title=item.name,
can_play=True,
can_expand=False,
thumbnail=thumbnail,
) |
Parse identifier. | def async_parse_identifier(
item: MediaSourceItem,
) -> tuple[str, str, str]:
"""Parse identifier."""
identifier = item.identifier or ""
start = ["", "", ""]
items = identifier.lstrip("/").split("~~", 2)
return tuple(items + start[len(items) :]) |
Build individual game. | def _build_game_item(item: InstalledPackage, images: dict[str, list[Image]]):
"""Build individual game."""
thumbnail = ""
image = _find_media_image(images.get(item.one_store_product_id, []))
if image is not None:
thumbnail = image.uri
if thumbnail[0] == "/":
thumbnail = f"https:{thumbnail}"
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{item.title_id}#{item.name}#{thumbnail}",
media_class=MediaClass.GAME,
media_content_type="",
title=item.name,
can_play=False,
can_expand=True,
children_media_class=MediaClass.DIRECTORY,
thumbnail=thumbnail,
) |
Build base categories for Xbox media. | def _build_categories(title):
"""Build base categories for Xbox media."""
_, name, thumbnail = title.split("#", 2)
base = BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}",
media_class=MediaClass.GAME,
media_content_type="",
title=name,
can_play=False,
can_expand=True,
children=[],
children_media_class=MediaClass.DIRECTORY,
thumbnail=thumbnail,
)
owners = ["my", "community"]
kinds = ["gameclips", "screenshots"]
for owner in owners:
for kind in kinds:
base.children.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{owner}#{kind}",
media_class=MediaClass.DIRECTORY,
media_content_type="",
title=f"{owner.title()} {kind.title()}",
can_play=False,
can_expand=True,
children_media_class=MEDIA_CLASS_MAP[kind],
)
)
return base |
Build individual media item. | def _build_media_item(title: str, category: str, item: XboxMediaItem):
"""Build individual media item."""
kind = category.split("#", 1)[1]
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{category}~~{item.uri}",
media_class=item.media_class,
media_content_type=MIME_TYPE_MAP[kind],
title=item.caption,
can_play=True,
can_expand=False,
thumbnail=item.thumbnail,
) |
Update friends. | def async_update_friends(
coordinator: XboxUpdateCoordinator,
current: dict[str, list[XboxSensorEntity]],
async_add_entities,
) -> None:
"""Update friends."""
new_ids = set(coordinator.data.presence)
current_ids = set(current)
# Process new favorites, add them to Home Assistant
new_entities: list[XboxSensorEntity] = []
for xuid in new_ids - current_ids:
current[xuid] = [
XboxSensorEntity(coordinator, xuid, attribute)
for attribute in SENSOR_ATTRIBUTES
]
new_entities = new_entities + current[xuid]
async_add_entities(new_entities)
# Process deleted favorites, remove them from Home Assistant
for xuid in current_ids - new_ids:
coordinator.hass.async_create_task(
async_remove_entities(xuid, coordinator, current)
) |
Build presence data from a person. | def _build_presence_data(person: Person) -> PresenceData:
"""Build presence data from a person."""
active_app: PresenceDetail | None = None
with suppress(StopIteration):
active_app = next(
presence for presence in person.presence_details if presence.is_primary
)
return PresenceData(
xuid=person.xuid,
gamertag=person.gamertag,
display_pic=person.display_pic_raw,
online=person.presence_state == "Online",
status=person.presence_text,
in_party=person.multiplayer_summary.in_party > 0,
in_game=active_app is not None and active_app.is_game,
in_multiplayer=person.multiplayer_summary.in_multiplayer_session,
gamer_score=person.gamer_score,
gold_tenure=person.detail.tenure,
account_tier=person.detail.account_tier,
) |
Validate the configuration and return a Xiaomi Device Scanner. | def get_scanner(hass: HomeAssistant, config: ConfigType) -> XiaomiDeviceScanner | None:
"""Validate the configuration and return a Xiaomi Device Scanner."""
scanner = XiaomiDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None |
Get device list for the given host. | def _retrieve_list(host, token, **kwargs):
"""Get device list for the given host."""
url = "http://{}/cgi-bin/luci/;stok={}/api/misystem/devicelist"
url = url.format(host, token)
try:
res = requests.get(url, timeout=10, **kwargs)
except requests.exceptions.Timeout:
_LOGGER.exception("Connection to the router timed out at URL %s", url)
return
if res.status_code != HTTPStatus.OK:
_LOGGER.exception("Connection failed with http code %s", res.status_code)
return
try:
result = res.json()
except ValueError:
# If json decoder could not parse the response
_LOGGER.exception("Failed to parse response from mi router")
return
try:
xiaomi_code = result["code"]
except KeyError:
_LOGGER.exception("No field code in response from mi router. %s", result)
return
if xiaomi_code == 0:
try:
return result["list"]
except KeyError:
_LOGGER.exception("No list in response from mi router. %s", result)
return
else:
_LOGGER.info(
"Receive wrong Xiaomi code %s, expected 0 in response %s",
xiaomi_code,
result,
)
return |
Get authentication token for the given host+username+password. | def _get_token(host, username, password):
"""Get authentication token for the given host+username+password."""
url = f"http://{host}/cgi-bin/luci/api/xqsystem/login"
data = {"username": username, "password": password}
try:
res = requests.post(url, data=data, timeout=5)
except requests.exceptions.Timeout:
_LOGGER.exception("Connection to the router timed out")
return
if res.status_code == HTTPStatus.OK:
try:
result = res.json()
except ValueError:
# If JSON decoder could not parse the response
_LOGGER.exception("Failed to parse response from mi router")
return
try:
return result["token"]
except KeyError:
error_message = (
"Xiaomi token cannot be refreshed, response from "
"url: [%s] \nwith parameter: [%s] \nwas: [%s]"
)
_LOGGER.exception(error_message, url, data, result)
return
else:
_LOGGER.error(
"Invalid response: [%s] at url: [%s] with data [%s]", res, url, data
) |
Set up the Xiaomi component. | def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Xiaomi component."""
def play_ringtone_service(call: ServiceCall) -> None:
"""Service to play ringtone through Gateway."""
ring_id = call.data.get(ATTR_RINGTONE_ID)
gateway: XiaomiGateway = call.data[ATTR_GW_MAC]
kwargs = {"mid": ring_id}
if (ring_vol := call.data.get(ATTR_RINGTONE_VOL)) is not None:
kwargs["vol"] = ring_vol
gateway.write_to_hub(gateway.sid, **kwargs)
def stop_ringtone_service(call: ServiceCall) -> None:
"""Service to stop playing ringtone on Gateway."""
gateway: XiaomiGateway = call.data[ATTR_GW_MAC]
gateway.write_to_hub(gateway.sid, mid=10000)
def add_device_service(call: ServiceCall) -> None:
"""Service to add a new sub-device within the next 30 seconds."""
gateway: XiaomiGateway = call.data[ATTR_GW_MAC]
gateway.write_to_hub(gateway.sid, join_permission="yes")
persistent_notification.async_create(
hass,
(
"Join permission enabled for 30 seconds! "
"Please press the pairing button of the new device once."
),
title="Xiaomi Aqara Gateway",
)
def remove_device_service(call: ServiceCall) -> None:
"""Service to remove a sub-device from the gateway."""
device_id = call.data.get(ATTR_DEVICE_ID)
gateway: XiaomiGateway = call.data[ATTR_GW_MAC]
gateway.write_to_hub(gateway.sid, remove_device=device_id)
gateway_only_schema = _add_gateway_to_schema(hass, vol.Schema({}))
hass.services.register(
DOMAIN,
SERVICE_PLAY_RINGTONE,
play_ringtone_service,
schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_PLAY_RINGTONE),
)
hass.services.register(
DOMAIN, SERVICE_STOP_RINGTONE, stop_ringtone_service, schema=gateway_only_schema
)
hass.services.register(
DOMAIN, SERVICE_ADD_DEVICE, add_device_service, schema=gateway_only_schema
)
hass.services.register(
DOMAIN,
SERVICE_REMOVE_DEVICE,
remove_device_service,
schema=_add_gateway_to_schema(hass, SERVICE_SCHEMA_REMOVE_DEVICE),
)
return True |
Extend a voluptuous schema with a gateway validator. | def _add_gateway_to_schema(hass, schema):
"""Extend a voluptuous schema with a gateway validator."""
def gateway(sid):
"""Convert sid to a gateway."""
sid = str(sid).replace(":", "").lower()
for gateway in hass.data[DOMAIN][GATEWAYS_KEY].values():
if gateway.sid == sid:
return gateway
raise vol.Invalid(f"Unknown gateway sid {sid}")
kwargs = {}
if (xiaomi_data := hass.data.get(DOMAIN)) is not None:
gateways = list(xiaomi_data[GATEWAYS_KEY].values())
# If the user has only 1 gateway, make it the default for services.
if len(gateways) == 1:
kwargs["default"] = gateways[0].sid
return schema.extend({vol.Required(ATTR_GW_MAC, **kwargs): gateway}) |
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): BINARY_SENSOR_DESCRIPTIONS[
description.device_class
]
for device_key, description in sensor_update.binary_entity_descriptions.items()
if description.device_class
},
entity_data={
device_key_to_bluetooth_entity_key(device_key): sensor_values.native_value
for device_key, sensor_values in sensor_update.binary_entity_values.items()
},
entity_names={
device_key_to_bluetooth_entity_key(device_key): sensor_values.name
for device_key, sensor_values in sensor_update.binary_entity_values.items()
},
) |
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) |
Get available triggers for a given model. | def _async_trigger_model_data(
hass: HomeAssistant, device_id: str
) -> TriggerModelData | None:
"""Get available triggers for a given model."""
device_registry = dr.async_get(hass)
device = device_registry.async_get(device_id)
if device and device.model and (model_data := MODEL_DATA.get(device.model)):
return model_data
return None |
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
},
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={
device_key_to_bluetooth_entity_key(device_key): sensor_values.name
for device_key, sensor_values in sensor_update.entity_values.items()
},
) |
Process a BluetoothServiceInfoBleak, running side effects and returning sensor data. | def process_service_info(
hass: HomeAssistant,
entry: config_entries.ConfigEntry,
data: XiaomiBluetoothDeviceData,
service_info: BluetoothServiceInfoBleak,
device_registry: DeviceRegistry,
) -> SensorUpdate:
"""Process a BluetoothServiceInfoBleak, running side effects and returning sensor data."""
update = data.update(service_info)
coordinator: XiaomiActiveBluetoothProcessorCoordinator = hass.data[DOMAIN][
entry.entry_id
]
discovered_event_classes = coordinator.discovered_event_classes
if entry.data.get(CONF_SLEEPY_DEVICE, False) != data.sleepy_device:
hass.config_entries.async_update_entry(
entry,
data=entry.data | {CONF_SLEEPY_DEVICE: data.sleepy_device},
)
if update.events:
address = service_info.device.address
for device_key, event in update.events.items():
sensor_device_info = update.devices[device_key.device_id]
device = device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
connections={(CONNECTION_BLUETOOTH, address)},
identifiers={(BLUETOOTH_DOMAIN, address)},
manufacturer=sensor_device_info.manufacturer,
model=sensor_device_info.model,
name=sensor_device_info.name,
sw_version=sensor_device_info.sw_version,
hw_version=sensor_device_info.hw_version,
)
# event_class may be postfixed with a number, ie 'button_2'
# but if there is only one button then it will be 'button'
event_class = event.device_key.key
event_type = event.event_type
ble_event = XiaomiBleEvent(
device_id=device.id,
address=address,
event_class=event_class, # ie 'button'
event_type=event_type, # ie 'press'
event_properties=event.event_properties,
)
if event_class not in discovered_event_classes:
discovered_event_classes.add(event_class)
hass.config_entries.async_update_entry(
entry,
data=entry.data
| {CONF_DISCOVERED_EVENT_CLASSES: list(discovered_event_classes)},
)
async_dispatcher_send(
hass, format_discovered_event_class(address), event_class, ble_event
)
hass.bus.async_fire(XIAOMI_BLE_EVENT, cast(dict, ble_event))
async_dispatcher_send(
hass,
format_event_dispatcher_name(address, event_class),
ble_event,
)
# If device isn't pending we know it has seen at least one broadcast with a payload
# If that payload was encrypted and the bindkey was not verified then we need to reauth
if (
not data.pending
and data.encryption_scheme != EncryptionScheme.NONE
and not data.bindkey_verified
):
entry.async_start_reauth(hass, data={"device": data})
return update |
Format an event dispatcher name. | def format_event_dispatcher_name(address: str, event_class: str) -> str:
"""Format an event dispatcher name."""
return f"{DOMAIN}_event_{address}_{event_class}" |
Format a discovered event class. | def format_discovered_event_class(address: str) -> str:
"""Format a discovered event class."""
return f"{DOMAIN}_discovered_event_class_{address}" |
Only vacuums with mop should have binary sensor registered. | def _setup_vacuum_sensors(hass, config_entry, async_add_entities):
"""Only vacuums with mop should have binary sensor registered."""
if config_entry.data[CONF_MODEL] not in MODELS_VACUUM_WITH_MOP:
return
device = hass.data[DOMAIN][config_entry.entry_id].get(KEY_DEVICE)
coordinator = hass.data[DOMAIN][config_entry.entry_id][KEY_COORDINATOR]
entities = []
sensors = VACUUM_SENSORS
if config_entry.data[CONF_MODEL] in MODELS_VACUUM_WITH_SEPARATE_MOP:
sensors = VACUUM_SENSORS_SEPARATE_MOP
for sensor, description in sensors.items():
parent_key_data = getattr(coordinator.data, description.parent_key)
if getattr(parent_key_data, description.key, None) is None:
_LOGGER.debug(
"It seems the %s does not support the %s as the initial value is None",
config_entry.data[CONF_MODEL],
description.key,
)
continue
entities.append(
XiaomiGenericBinarySensor(
device,
config_entry,
f"{sensor}_{config_entry.unique_id}",
coordinator,
description,
)
)
async_add_entities(entities) |
Return a Xiaomi MiIO device scanner. | def get_scanner(
hass: HomeAssistant, config: ConfigType
) -> XiaomiMiioDeviceScanner | None:
"""Return a Xiaomi MiIO device scanner."""
scanner = None
host = config[DOMAIN][CONF_HOST]
token = config[DOMAIN][CONF_TOKEN]
_LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])
try:
device = WifiRepeater(host, token)
device_info = device.info()
_LOGGER.info(
"%s %s %s detected",
device_info.model,
device_info.firmware_version,
device_info.hardware_version,
)
scanner = XiaomiMiioDeviceScanner(device)
except DeviceException as ex:
_LOGGER.error("Device unavailable or token incorrect: %s", ex)
return scanner |
Set up the Xiaomi vacuum sensors. | def _setup_vacuum_sensors(hass, config_entry, async_add_entities):
"""Set up the Xiaomi vacuum sensors."""
device = hass.data[DOMAIN][config_entry.entry_id].get(KEY_DEVICE)
coordinator = hass.data[DOMAIN][config_entry.entry_id][KEY_COORDINATOR]
entities = []
for sensor, description in VACUUM_SENSORS.items():
parent_key_data = getattr(coordinator.data, description.parent_key)
if getattr(parent_key_data, description.key, None) is None:
_LOGGER.debug(
"It seems the %s does not support the %s as the initial value is None",
config_entry.data[CONF_MODEL],
description.key,
)
continue
entities.append(
XiaomiGenericSensor(
device,
config_entry,
f"{sensor}_{config_entry.unique_id}",
coordinator,
description,
)
)
async_add_entities(entities) |
Return the platforms belonging to a config_entry. | def get_platforms(config_entry):
"""Return the platforms belonging to a config_entry."""
model = config_entry.data[CONF_MODEL]
flow_type = config_entry.data[CONF_FLOW_TYPE]
if flow_type == CONF_GATEWAY:
return GATEWAY_PLATFORMS
if flow_type == CONF_DEVICE:
if model in MODELS_SWITCH:
return SWITCH_PLATFORMS
if model in MODELS_HUMIDIFIER:
return HUMIDIFIER_PLATFORMS
if model in MODELS_FAN:
return FAN_PLATFORMS
if model in MODELS_LIGHT:
return LIGHT_PLATFORMS
for vacuum_model in MODELS_VACUUM:
if model.startswith(vacuum_model):
return VACUUM_PLATFORMS
for air_monitor_model in MODELS_AIR_MONITOR:
if model.startswith(air_monitor_model):
return AIR_MONITOR_PLATFORMS
_LOGGER.error(
(
"Unsupported device found! Please create an issue at "
"https://github.com/syssi/xiaomi_airpurifier/issues "
"and provide the following data: %s"
),
model,
)
return [] |
Set up the Xiaomi TV platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Xiaomi TV platform."""
# If a hostname is set. Discovery is skipped.
host = config.get(CONF_HOST)
name = config.get(CONF_NAME)
if host is not None:
# Check if there's a valid TV at the IP address.
if not pymitv.Discover().check_ip(host):
_LOGGER.error("Could not find Xiaomi TV with specified IP: %s", host)
else:
# Register TV with Home Assistant.
add_entities([XiaomiTV(host, name)])
else:
# Otherwise, discover TVs on network.
add_entities(XiaomiTV(tv, DEFAULT_NAME) for tv in pymitv.Discover().scan()) |
Set up the XS1 thermostat platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the XS1 thermostat platform."""
actuators = hass.data[COMPONENT_DOMAIN][ACTUATORS]
sensors = hass.data[COMPONENT_DOMAIN][SENSORS]
thermostat_entities = []
for actuator in actuators:
if actuator.type() == ActuatorType.TEMPERATURE:
# Search for a matching sensor (by name)
actuator_name = actuator.name()
matching_sensor = None
for sensor in sensors:
if actuator_name in sensor.name():
matching_sensor = sensor
break
thermostat_entities.append(XS1ThermostatEntity(actuator, matching_sensor))
add_entities(thermostat_entities) |
Set up the XS1 sensor platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the XS1 sensor platform."""
sensors = hass.data[COMPONENT_DOMAIN][SENSORS]
actuators = hass.data[COMPONENT_DOMAIN][ACTUATORS]
sensor_entities = []
for sensor in sensors:
belongs_to_climate_actuator = False
for actuator in actuators:
if (
actuator.type() == ActuatorType.TEMPERATURE
and actuator.name() in sensor.name()
):
belongs_to_climate_actuator = True
break
if not belongs_to_climate_actuator:
sensor_entities.append(XS1Sensor(sensor))
add_entities(sensor_entities) |
Set up the XS1 switch platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the XS1 switch platform."""
actuators = hass.data[COMPONENT_DOMAIN][ACTUATORS]
add_entities(
XS1SwitchEntity(actuator)
for actuator in actuators
if (actuator.type() == ActuatorType.SWITCH)
or (actuator.type() == ActuatorType.DIMMER)
) |
Set up XS1 integration. | def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up XS1 integration."""
_LOGGER.debug("Initializing XS1")
host = config[DOMAIN][CONF_HOST]
port = config[DOMAIN][CONF_PORT]
ssl = config[DOMAIN][CONF_SSL]
user = config[DOMAIN].get(CONF_USERNAME)
password = config[DOMAIN].get(CONF_PASSWORD)
# initialize XS1 API
try:
xs1 = xs1_api_client.XS1(
host=host, port=port, ssl=ssl, user=user, password=password
)
except ConnectionError as error:
_LOGGER.error(
"Failed to create XS1 API client because of a connection error: %s",
error,
)
return False
_LOGGER.debug("Establishing connection to XS1 gateway and retrieving data")
hass.data[DOMAIN] = {}
actuators = xs1.get_all_actuators(enabled=True)
sensors = xs1.get_all_sensors(enabled=True)
hass.data[DOMAIN][ACTUATORS] = actuators
hass.data[DOMAIN][SENSORS] = sensors
_LOGGER.debug("Loading platforms for XS1 integration")
# Load platforms for supported devices
for platform in PLATFORMS:
discovery.load_platform(hass, platform, DOMAIN, {}, config)
return True |
Return a BluetoothCallbackMatcher for the given local_name and address. | def bluetooth_callback_matcher(
local_name: str, address: str
) -> BluetoothCallbackMatcher:
"""Return a BluetoothCallbackMatcher for the given local_name and address."""
# On MacOS, coreblueooth uses UUIDs for addresses so we must
# have a unique local_name to match since the system
# hides the address from us.
if local_name_is_unique(local_name) and platform.system() == "Darwin":
return BluetoothCallbackMatcher({LOCAL_NAME: local_name})
# On every other platform we actually get the mac address
# which is needed for the older August locks that use the
# older version of the underlying protocol.
return BluetoothCallbackMatcher({ADDRESS: address}) |
Return the service info for the given local_name and address. | def async_find_existing_service_info(
hass: HomeAssistant, local_name: str, address: str
) -> BluetoothServiceInfoBleak | None:
"""Return the service info for the given local_name and address."""
has_unique_local_name = local_name_is_unique(local_name)
for service_info in async_discovered_service_info(hass):
device = service_info.device
if (
has_unique_local_name and device.name == local_name
) or device.address == address:
return service_info
return None |
Convert a Bluetooth address to a short address. | def short_address(address: str) -> str:
"""Convert a Bluetooth address to a short address."""
split_address = address.replace("-", ":").split(":")
return f"{split_address[-2].upper()}{split_address[-1].upper()}"[-4:] |
Return a human readable name for the given name, local_name, and address. | def human_readable_name(name: str | None, local_name: str, address: str) -> str:
"""Return a human readable name for the given name, local_name, and address."""
return f"{name or local_name} ({short_address(address)})" |
Discover receivers from configuration in the network. | def _discovery(config_info):
"""Discover receivers from configuration in the network."""
if config_info.from_discovery:
receivers = rxv.RXV(
config_info.ctrl_url,
model_name=config_info.model,
friendly_name=config_info.name,
unit_desc_url=config_info.desc_url,
).zone_controllers()
_LOGGER.debug("Receivers: %s", receivers)
elif config_info.host is None:
receivers = []
for recv in rxv.find():
receivers.extend(recv.zone_controllers())
else:
receivers = rxv.RXV(config_info.ctrl_url, config_info.name).zone_controllers()
return receivers |
Generate a more human readable model. | def async_format_model(model: str) -> str:
"""Generate a more human readable model."""
return model.replace("_", " ").title() |
Generate a more human readable id. | def async_format_id(id_: str) -> str:
"""Generate a more human readable id."""
return hex(int(id_, 16)) if id_ else "None" |
Generate a more human readable name. | def async_format_model_id(model: str, id_: str) -> str:
"""Generate a more human readable name."""
return f"{async_format_model(model)} {async_format_id(id_)}" |
Generate name from capabilities. | def _async_unique_name(capabilities: dict) -> str:
"""Generate name from capabilities."""
model_id = async_format_model_id(capabilities["model"], capabilities["id"])
return f"Yeelight {model_id}" |
Check if a push update needs the bg_power workaround.
Some devices will push the incorrect state for bg_power.
To work around this any time we are pushed an update
with bg_power, we force poll state which will be correct. | def update_needs_bg_power_workaround(data):
"""Check if a push update needs the bg_power workaround.
Some devices will push the incorrect state for bg_power.
To work around this any time we are pushed an update
with bg_power, we force poll state which will be correct.
"""
return "bg_power" in data |
Parse transitions config into initialized objects. | def _transitions_config_parser(transitions):
"""Parse transitions config into initialized objects."""
transition_objects = []
for transition_config in transitions:
transition, params = list(transition_config.items())[0]
transition_objects.append(getattr(yeelight, transition)(*params))
return transition_objects |
Define a wrapper to catch exceptions from the bulb. | def _async_cmd(
func: Callable[Concatenate[_YeelightBaseLightT, _P], Coroutine[Any, Any, _R]],
) -> Callable[Concatenate[_YeelightBaseLightT, _P], Coroutine[Any, Any, _R | None]]:
"""Define a wrapper to catch exceptions from the bulb."""
async def _async_wrap(
self: _YeelightBaseLightT, *args: _P.args, **kwargs: _P.kwargs
) -> _R | None:
for attempts in range(2):
try:
_LOGGER.debug("Calling %s with %s %s", func, args, kwargs)
return await func(self, *args, **kwargs)
except TimeoutError as ex:
# The wifi likely dropped, so we want to retry once since
# python-yeelight will auto reconnect
if attempts == 0:
continue
raise HomeAssistantError(
f"Timed out when calling {func.__name__} for bulb "
f"{self.device.name} at {self.device.host}: {str(ex) or type(ex)}"
) from ex
except OSError as ex:
# A network error happened, the bulb is likely offline now
self.device.async_mark_unavailable()
self.async_state_changed()
raise HomeAssistantError(
f"Error when calling {func.__name__} for bulb "
f"{self.device.name} at {self.device.host}: {str(ex) or type(ex)}"
) from ex
except BulbException as ex:
# The bulb likely responded but had an error
raise HomeAssistantError(
f"Error when calling {func.__name__} for bulb "
f"{self.device.name} at {self.device.host}: {str(ex) or type(ex)}"
) from ex
return None
return _async_wrap |
Set up custom services. | def _async_setup_services(hass: HomeAssistant):
"""Set up custom services."""
async def _async_start_flow(entity, service_call):
params = {**service_call.data}
params.pop(ATTR_ENTITY_ID)
params[ATTR_TRANSITIONS] = _transitions_config_parser(params[ATTR_TRANSITIONS])
await entity.async_start_flow(**params)
async def _async_set_color_scene(entity, service_call):
await entity.async_set_scene(
SceneClass.COLOR,
*service_call.data[ATTR_RGB_COLOR],
service_call.data[ATTR_BRIGHTNESS],
)
async def _async_set_hsv_scene(entity, service_call):
await entity.async_set_scene(
SceneClass.HSV,
*service_call.data[ATTR_HS_COLOR],
service_call.data[ATTR_BRIGHTNESS],
)
async def _async_set_color_temp_scene(entity, service_call):
await entity.async_set_scene(
SceneClass.CT,
service_call.data[ATTR_KELVIN],
service_call.data[ATTR_BRIGHTNESS],
)
async def _async_set_color_flow_scene(entity, service_call):
flow = Flow(
count=service_call.data[ATTR_COUNT],
action=Flow.actions[service_call.data[ATTR_ACTION]],
transitions=_transitions_config_parser(service_call.data[ATTR_TRANSITIONS]),
)
await entity.async_set_scene(SceneClass.CF, flow)
async def _async_set_auto_delay_off_scene(entity, service_call):
await entity.async_set_scene(
SceneClass.AUTO_DELAY_OFF,
service_call.data[ATTR_BRIGHTNESS],
service_call.data[ATTR_MINUTES],
)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
SERVICE_SET_MODE, SERVICE_SCHEMA_SET_MODE, "async_set_mode"
)
platform.async_register_entity_service(
SERVICE_START_FLOW, SERVICE_SCHEMA_START_FLOW, _async_start_flow
)
platform.async_register_entity_service(
SERVICE_SET_COLOR_SCENE, SERVICE_SCHEMA_SET_COLOR_SCENE, _async_set_color_scene
)
platform.async_register_entity_service(
SERVICE_SET_HSV_SCENE, SERVICE_SCHEMA_SET_HSV_SCENE, _async_set_hsv_scene
)
platform.async_register_entity_service(
SERVICE_SET_COLOR_TEMP_SCENE,
SERVICE_SCHEMA_SET_COLOR_TEMP_SCENE,
_async_set_color_temp_scene,
)
platform.async_register_entity_service(
SERVICE_SET_COLOR_FLOW_SCENE,
SERVICE_SCHEMA_SET_COLOR_FLOW_SCENE,
_async_set_color_flow_scene,
)
platform.async_register_entity_service(
SERVICE_SET_AUTO_DELAY_OFF_SCENE,
SERVICE_SCHEMA_SET_AUTO_DELAY_OFF_SCENE,
_async_set_auto_delay_off_scene,
)
platform.async_register_entity_service(
SERVICE_SET_MUSIC_MODE, SERVICE_SCHEMA_SET_MUSIC_MODE, "async_set_music_mode"
) |
Move options from data for imported entries.
Initialize options with default values for other entries.
Copy the unique id to CONF_ID if it is missing | def _async_normalize_config_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Move options from data for imported entries.
Initialize options with default values for other entries.
Copy the unique id to CONF_ID if it is missing
"""
if not entry.options:
hass.config_entries.async_update_entry(
entry,
data={
CONF_HOST: entry.data.get(CONF_HOST),
CONF_ID: entry.data.get(CONF_ID) or entry.unique_id,
CONF_DETECTED_MODEL: entry.data.get(CONF_DETECTED_MODEL),
},
options={
CONF_NAME: entry.data.get(CONF_NAME, ""),
CONF_MODEL: entry.data.get(
CONF_MODEL, entry.data.get(CONF_DETECTED_MODEL, "")
),
CONF_TRANSITION: entry.data.get(CONF_TRANSITION, DEFAULT_TRANSITION),
CONF_MODE_MUSIC: entry.data.get(CONF_MODE_MUSIC, DEFAULT_MODE_MUSIC),
CONF_SAVE_ON_CHANGE: entry.data.get(
CONF_SAVE_ON_CHANGE, DEFAULT_SAVE_ON_CHANGE
),
CONF_NIGHTLIGHT_SWITCH: entry.data.get(
CONF_NIGHTLIGHT_SWITCH, DEFAULT_NIGHTLIGHT_SWITCH
),
},
unique_id=entry.unique_id or entry.data.get(CONF_ID),
)
elif entry.unique_id and not entry.data.get(CONF_ID):
hass.config_entries.async_update_entry(
entry,
data={CONF_HOST: entry.data.get(CONF_HOST), CONF_ID: entry.unique_id},
)
elif entry.data.get(CONF_ID) and not entry.unique_id:
hass.config_entries.async_update_entry(
entry,
unique_id=entry.data[CONF_ID],
) |
Set up the Yeelight Sunflower Light platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Yeelight Sunflower Light platform."""
host = config.get(CONF_HOST)
hub = yeelightsunflower.Hub(host)
if not hub.available:
_LOGGER.error("Could not connect to Yeelight Sunflower hub")
return
add_entities(SunflowerBulb(light) for light in hub.get_lights()) |
Get volume option. | def get_volume_value(state: dict[str, Any]) -> int | None:
"""Get volume option."""
if (options := state.get("options")) is not None:
return options.get("volume")
return None |
Convert battery to percentage. | def cvt_battery(val: int | None) -> int | None:
"""Convert battery to percentage."""
if val is None:
return None
if val > 0:
return percentage.ordered_list_item_to_percentage([1, 2, 3, 4], val)
return 0 |
Convert volume to string. | def cvt_volume(val: int | None) -> str | None:
"""Convert volume to string."""
if val is None:
return None
volume_level = {1: "low", 2: "medium", 3: "high"}
return volume_level.get(val) |
Register services for YoLink integration. | def async_register_services(hass: HomeAssistant) -> None:
"""Register services for YoLink integration."""
async def handle_speaker_hub_play_call(service_call: ServiceCall) -> None:
"""Handle Speaker Hub audio play call."""
service_data = service_call.data
device_registry = dr.async_get(hass)
device_entry = device_registry.async_get(service_data[ATTR_TARGET_DEVICE])
if device_entry is not None:
for entry_id in device_entry.config_entries:
if (entry := hass.config_entries.async_get_entry(entry_id)) is None:
continue
if entry.domain == DOMAIN:
break
if entry is None or entry.state == ConfigEntryState.NOT_LOADED:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_config_entry",
)
home_store = hass.data[DOMAIN][entry.entry_id]
for identifier in device_entry.identifiers:
if (
device_coordinator := home_store.device_coordinators.get(
identifier[1]
)
) is not None:
tone_param = service_data[ATTR_TONE].capitalize()
play_request = ClientRequest(
"playAudio",
{
ATTR_TONE: tone_param,
ATTR_TEXT_MESSAGE: service_data[ATTR_TEXT_MESSAGE],
ATTR_VOLUME: service_data[ATTR_VOLUME],
ATTR_REPEAT: service_data[ATTR_REPEAT],
},
)
await device_coordinator.device.call_device(play_request)
hass.services.async_register(
domain=DOMAIN,
service=SERVICE_PLAY_ON_SPEAKER_HUB,
schema=vol.Schema(
{
vol.Required(ATTR_TARGET_DEVICE): cv.string,
vol.Required(ATTR_TONE): cv.string,
vol.Required(ATTR_TEXT_MESSAGE): cv.string,
vol.Required(ATTR_VOLUME): vol.All(
vol.Coerce(int), vol.Range(min=0, max=15)
),
vol.Optional(ATTR_REPEAT, default=0): vol.All(
vol.Coerce(int), vol.Range(min=0, max=10)
),
},
),
service_func=handle_speaker_hub_play_call,
) |
Set up the Zabbix sensor platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Zabbix sensor platform."""
sensors: list[ZabbixTriggerCountSensor] = []
if not (zapi := hass.data[zabbix.DOMAIN]):
_LOGGER.error("Zabbix integration hasn't been loaded? zapi is None")
return
_LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version())
# The following code seems overly complex. Need to think about this...
if trigger_conf := config.get(_CONF_TRIGGERS):
hostids = trigger_conf.get(_CONF_HOSTIDS)
individual = trigger_conf.get(_CONF_INDIVIDUAL)
name = trigger_conf.get(CONF_NAME)
if individual:
# Individual sensor per host
if not hostids:
# We need hostids
_LOGGER.error("If using 'individual', must specify hostids")
return
for hostid in hostids:
_LOGGER.debug("Creating Zabbix Sensor: %s", str(hostid))
sensors.append(ZabbixSingleHostTriggerCountSensor(zapi, [hostid], name))
elif not hostids:
# Single sensor that provides the total count of triggers.
_LOGGER.debug("Creating Zabbix Sensor")
sensors.append(ZabbixTriggerCountSensor(zapi, name))
else:
# Single sensor that sums total issues for all hosts
_LOGGER.debug("Creating Zabbix Sensor group: %s", str(hostids))
sensors.append(ZabbixMultipleHostTriggerCountSensor(zapi, hostids, name))
else:
# Single sensor that provides the total count of triggers.
_LOGGER.debug("Creating Zabbix Sensor")
sensors.append(ZabbixTriggerCountSensor(zapi))
add_entities(sensors) |
Set up the Zabbix component. | def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Zabbix component."""
conf = config[DOMAIN]
protocol = "https" if conf[CONF_SSL] else "http"
url = urljoin(f"{protocol}://{conf[CONF_HOST]}", conf[CONF_PATH])
username = conf.get(CONF_USERNAME)
password = conf.get(CONF_PASSWORD)
publish_states_host = conf.get(CONF_PUBLISH_STATES_HOST)
entities_filter = convert_include_exclude_filter(conf)
try:
zapi = ZabbixAPI(url=url, user=username, password=password)
_LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version())
except ZabbixAPIException as login_exception:
_LOGGER.error("Unable to login to the Zabbix API: %s", login_exception)
return False
except HTTPError as http_error:
_LOGGER.error("HTTPError when connecting to Zabbix API: %s", http_error)
zapi = None
_LOGGER.error(RETRY_MESSAGE, http_error)
event_helper.call_later(
hass,
RETRY_INTERVAL,
lambda _: setup(hass, config), # type: ignore[arg-type,return-value]
)
return True
hass.data[DOMAIN] = zapi
def event_to_metrics(event, float_keys, string_keys):
"""Add an event to the outgoing Zabbix list."""
state = event.data.get("new_state")
if state is None or state.state in (STATE_UNKNOWN, "", STATE_UNAVAILABLE):
return
entity_id = state.entity_id
if not entities_filter(entity_id):
return
floats = {}
strings = {}
try:
_state_as_value = float(state.state)
floats[entity_id] = _state_as_value
except ValueError:
try:
_state_as_value = float(state_helper.state_as_number(state))
floats[entity_id] = _state_as_value
except ValueError:
strings[entity_id] = state.state
for key, value in state.attributes.items():
# For each value we try to cast it as float
# But if we cannot do it we store the value
# as string
attribute_id = f"{entity_id}/{key}"
try:
float_value = float(value)
except (ValueError, TypeError):
float_value = None
if float_value is None or not math.isfinite(float_value):
strings[attribute_id] = str(value)
else:
floats[attribute_id] = float_value
metrics = []
float_keys_count = len(float_keys)
float_keys.update(floats)
if len(float_keys) != float_keys_count:
floats_discovery = [{"{#KEY}": float_key} for float_key in float_keys]
metric = ZabbixMetric(
publish_states_host,
"homeassistant.floats_discovery",
json.dumps(floats_discovery),
)
metrics.append(metric)
for key, value in floats.items():
metric = ZabbixMetric(
publish_states_host, f"homeassistant.float[{key}]", value
)
metrics.append(metric)
string_keys.update(strings)
return metrics
if publish_states_host:
zabbix_sender = ZabbixSender(zabbix_server=conf[CONF_HOST])
instance = ZabbixThread(hass, zabbix_sender, event_to_metrics)
instance.setup(hass)
return True |
Set up the Zengge platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Zengge platform."""
lights = []
for address, device_config in config[CONF_DEVICES].items():
device = {}
device["name"] = device_config[CONF_NAME]
device["address"] = address
light = ZenggeLight(device)
if light.is_valid:
lights.append(light)
add_entities(lights, True) |
Wrap the Zeroconf class to return the shared instance.
Only if if multiple instances are detected. | def install_multiple_zeroconf_catcher(hass_zc: HaZeroconf) -> None:
"""Wrap the Zeroconf class to return the shared instance.
Only if if multiple instances are detected.
"""
def new_zeroconf_new(self: zeroconf.Zeroconf, *k: Any, **kw: Any) -> HaZeroconf:
report(
(
"attempted to create another Zeroconf instance. Please use the shared"
" Zeroconf via await"
" homeassistant.components.zeroconf.async_get_instance(hass)"
),
exclude_integrations={"zeroconf"},
error_if_core=False,
)
return hass_zc
def new_zeroconf_init(self: zeroconf.Zeroconf, *k: Any, **kw: Any) -> None:
return
zeroconf.Zeroconf.__new__ = new_zeroconf_new # type: ignore[assignment]
zeroconf.Zeroconf.__init__ = new_zeroconf_init |
Return true for platforms not supporting IP_ADD_MEMBERSHIP on an AF_INET6 socket.
Zeroconf only supports a single listen socket at this time. | def _async_zc_has_functional_dual_stack() -> bool:
"""Return true for platforms not supporting IP_ADD_MEMBERSHIP on an AF_INET6 socket.
Zeroconf only supports a single listen socket at this time.
"""
return not sys.platform.startswith("freebsd") and not sys.platform.startswith(
"darwin"
) |
Build lookups for homekit models. | def _build_homekit_model_lookups(
homekit_models: dict[str, HomeKitDiscoveredIntegration],
) -> tuple[
dict[str, HomeKitDiscoveredIntegration],
dict[re.Pattern, HomeKitDiscoveredIntegration],
]:
"""Build lookups for homekit models."""
homekit_model_lookup: dict[str, HomeKitDiscoveredIntegration] = {}
homekit_model_matchers: dict[re.Pattern, HomeKitDiscoveredIntegration] = {}
for model, discovery in homekit_models.items():
if "*" in model or "?" in model or "[" in model:
homekit_model_matchers[_compile_fnmatch(model)] = discovery
else:
homekit_model_lookup[model] = discovery
return homekit_model_lookup, homekit_model_matchers |
Filter disallowed characters from a string.
. is a reversed character for zeroconf. | def _filter_disallowed_characters(name: str) -> str:
"""Filter disallowed characters from a string.
. is a reversed character for zeroconf.
"""
return name.replace(".", " ") |
Check a matcher to ensure all values in props. | def _match_against_props(matcher: dict[str, str], props: dict[str, str | None]) -> bool:
"""Check a matcher to ensure all values in props."""
for key, value in matcher.items():
prop_val = props.get(key)
if prop_val is None or not _memorized_fnmatch(prop_val.lower(), value):
return False
return True |
Check properties to see if a device is homekit paired. | def is_homekit_paired(props: dict[str, Any]) -> bool:
"""Check properties to see if a device is homekit paired."""
if HOMEKIT_PAIRED_STATUS_FLAG not in props:
return False
with contextlib.suppress(ValueError):
# 0 means paired and not discoverable by iOS clients)
return int(props[HOMEKIT_PAIRED_STATUS_FLAG]) == 0
# If we cannot tell, we assume its not paired
return False |
Handle a HomeKit discovery.
Return the domain to forward the discovery data to | def async_get_homekit_discovery(
homekit_model_lookups: dict[str, HomeKitDiscoveredIntegration],
homekit_model_matchers: dict[re.Pattern, HomeKitDiscoveredIntegration],
props: dict[str, Any],
) -> HomeKitDiscoveredIntegration | None:
"""Handle a HomeKit discovery.
Return the domain to forward the discovery data to
"""
if not (
model := props.get(HOMEKIT_MODEL_LOWER) or props.get(HOMEKIT_MODEL_UPPER)
) or not isinstance(model, str):
return None
for split_str in _HOMEKIT_MODEL_SPLITS:
key = (model.split(split_str))[0] if split_str else model
if discovery := homekit_model_lookups.get(key):
return discovery
for pattern, discovery in homekit_model_matchers.items():
if pattern.match(model):
return discovery
return None |
Return prepared info from mDNS entries. | def info_from_service(service: AsyncServiceInfo) -> ZeroconfServiceInfo | None:
"""Return prepared info from mDNS entries."""
# See https://ietf.org/rfc/rfc6763.html#section-6.4 and
# https://ietf.org/rfc/rfc6763.html#section-6.5 for expected encodings
# for property keys and values
if not (maybe_ip_addresses := service.ip_addresses_by_version(IPVersion.All)):
return None
if TYPE_CHECKING:
ip_addresses = cast(list[IPv4Address | IPv6Address], maybe_ip_addresses)
else:
ip_addresses = maybe_ip_addresses
ip_address: IPv4Address | IPv6Address | None = None
for ip_addr in ip_addresses:
if not ip_addr.is_link_local and not ip_addr.is_unspecified:
ip_address = ip_addr
break
if not ip_address:
return None
if TYPE_CHECKING:
assert (
service.server is not None
), "server cannot be none if there are addresses"
return ZeroconfServiceInfo(
ip_address=ip_address,
ip_addresses=ip_addresses,
port=service.port,
hostname=service.server,
type=service.type,
name=service.name,
properties=service.decoded_properties,
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.