response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Return if MQTT client is connected. | def is_connected(hass: HomeAssistant) -> bool:
"""Return if MQTT client is connected."""
mqtt_data = get_mqtt_data(hass)
return mqtt_data.client.connected |
Test color_mode is not combined with deprecated config. | def valid_color_configuration(
setup_from_yaml: bool,
) -> Callable[[dict[str, Any]], dict[str, Any]]:
"""Test color_mode is not combined with deprecated config."""
def _valid_color_configuration(config: ConfigType) -> ConfigType:
deprecated = {CONF_COLOR_TEMP, CONF_HS, CONF_RGB, CONF_XY}
deprecated_flags_used = any(config.get(key) for key in deprecated)
if config.get(CONF_SUPPORTED_COLOR_MODES):
if deprecated_flags_used:
raise vol.Invalid(
"supported_color_modes must not "
f"be combined with any of {deprecated}"
)
elif deprecated_flags_used:
deprecated_flags = ", ".join(key for key in deprecated if key in config)
_LOGGER.warning(
"Deprecated flags [%s] used in MQTT JSON light config "
"for handling color mode, please use `supported_color_modes` instead. "
"Got: %s. This will stop working in Home Assistant Core 2025.3",
deprecated_flags,
config,
)
if not setup_from_yaml:
return config
issue_id = hex(hash(frozenset(config)))
yaml_config_str = yaml_dump(config)
learn_more_url = (
"https://www.home-assistant.io/integrations/"
f"{LIGHT_DOMAIN}.mqtt/#json-schema"
)
hass = async_get_hass()
async_create_issue(
hass,
MQTT_DOMAIN,
issue_id,
issue_domain=LIGHT_DOMAIN,
is_fixable=False,
severity=IssueSeverity.WARNING,
learn_more_url=learn_more_url,
translation_placeholders={
"deprecated_flags": deprecated_flags,
"config": yaml_config_str,
},
translation_key="deprecated_color_handling",
)
if CONF_COLOR_MODE in config:
_LOGGER.warning(
"Deprecated flag `color_mode` used in MQTT JSON light config "
", the `color_mode` flag is not used anymore and should be removed. "
"Got: %s. This will stop working in Home Assistant Core 2025.3",
config,
)
if not setup_from_yaml:
return config
issue_id = hex(hash(frozenset(config)))
yaml_config_str = yaml_dump(config)
learn_more_url = (
"https://www.home-assistant.io/integrations/"
f"{LIGHT_DOMAIN}.mqtt/#json-schema"
)
hass = async_get_hass()
async_create_issue(
hass,
MQTT_DOMAIN,
issue_id,
breaks_in_ha_version="2025.3.0",
issue_domain=LIGHT_DOMAIN,
is_fixable=False,
severity=IssueSeverity.WARNING,
learn_more_url=learn_more_url,
translation_placeholders={
"config": yaml_config_str,
},
translation_key="deprecated_color_mode_flag",
)
return config
return _valid_color_configuration |
Validate MQTT light schema for discovery. | def validate_mqtt_light_discovery(config_value: dict[str, Any]) -> ConfigType:
"""Validate MQTT light schema for discovery."""
schemas = {
"basic": DISCOVERY_SCHEMA_BASIC,
"json": DISCOVERY_SCHEMA_JSON,
"template": DISCOVERY_SCHEMA_TEMPLATE,
}
config: ConfigType = schemas[config_value[CONF_SCHEMA]](config_value)
return config |
Validate MQTT light schema for setup from configuration.yaml. | def validate_mqtt_light_modern(config_value: dict[str, Any]) -> ConfigType:
"""Validate MQTT light schema for setup from configuration.yaml."""
schemas = {
"basic": PLATFORM_SCHEMA_MODERN_BASIC,
"json": PLATFORM_SCHEMA_MODERN_JSON,
"template": PLATFORM_SCHEMA_MODERN_TEMPLATE,
}
config: ConfigType = schemas[config_value[CONF_SCHEMA]](config_value)
return config |
Parse the payload location parameters, into the format see expects. | def _parse_see_args(dev_id, data):
"""Parse the payload location parameters, into the format see expects."""
kwargs = {"gps": (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), "dev_id": dev_id}
if ATTR_GPS_ACCURACY in data:
kwargs[ATTR_GPS_ACCURACY] = data[ATTR_GPS_ACCURACY]
if ATTR_BATTERY_LEVEL in data:
kwargs["battery"] = data[ATTR_BATTERY_LEVEL]
return kwargs |
Return a slugified version of string, uppercased. | def _slugify_upper(string: str) -> str:
"""Return a slugified version of string, uppercased."""
return slugify(string).upper() |
Parse the room presence update. | def _parse_update_data(topic: str, data: dict[str, Any]) -> dict[str, Any]:
"""Parse the room presence update."""
parts = topic.split("/")
room = parts[-1]
device_id = _slugify_upper(data.get(ATTR_ID))
distance = data.get("distance")
return {ATTR_DEVICE_ID: device_id, ATTR_ROOM: room, ATTR_DISTANCE: distance} |
Get the Microsoft Teams notification service. | def get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> MSTeamsNotificationService | None:
"""Get the Microsoft Teams notification service."""
webhook_url = config.get(CONF_URL)
try:
return MSTeamsNotificationService(webhook_url)
except RuntimeError:
_LOGGER.exception("Error in creating a new Microsoft Teams message")
return None |
Set up the MVGLive sensor. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the MVGLive sensor."""
add_entities(
(
MVGLiveSensor(
nextdeparture.get(CONF_STATION),
nextdeparture.get(CONF_DESTINATIONS),
nextdeparture.get(CONF_DIRECTIONS),
nextdeparture.get(CONF_LINES),
nextdeparture.get(CONF_PRODUCTS),
nextdeparture.get(CONF_TIMEOFFSET),
nextdeparture.get(CONF_NUMBER),
nextdeparture.get(CONF_NAME),
)
for nextdeparture in config[CONF_NEXT_DEPARTURE]
),
True,
) |
Get the Mycroft notification service. | def get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> MycroftNotificationService:
"""Get the Mycroft notification service."""
return MycroftNotificationService(hass.data["mycroft"]) |
Set up the Mycroft component. | def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Mycroft component."""
hass.data[DOMAIN] = config[DOMAIN][CONF_HOST]
discovery.load_platform(hass, Platform.NOTIFY, DOMAIN, {}, config)
return True |
Validate that persistence file path ends in either .pickle or .json. | def is_persistence_file(value: str) -> str:
"""Validate that persistence file path ends in either .pickle or .json."""
if value.endswith((".json", ".pickle")):
return value
raise vol.Invalid(f"{value} does not end in either `.json` or `.pickle`") |
Create a schema with options common to all gateway types. | def _get_schema_common(user_input: dict[str, str]) -> dict:
"""Create a schema with options common to all gateway types."""
return {
vol.Required(
CONF_VERSION,
description={
"suggested_value": user_input.get(CONF_VERSION, DEFAULT_VERSION)
},
): str,
vol.Optional(CONF_PERSISTENCE_FILE): str,
} |
Validate a version string from the user. | def _validate_version(version: str) -> dict[str, str]:
"""Validate a version string from the user."""
version_okay = True
try:
AwesomeVersion(
version,
ensure_strategy=[
AwesomeVersionStrategy.SIMPLEVER,
AwesomeVersionStrategy.SEMVER,
],
)
except AwesomeVersionStrategyException:
version_okay = False
if version_okay:
return {}
return {CONF_VERSION: "invalid_version"} |
Check if another ConfigDevice is actually the same as user_input.
This function only compares addresses and tcp ports, so it is possible to fool it with tricks like port forwarding. | def _is_same_device(
gw_type: ConfGatewayType, user_input: dict[str, Any], entry: ConfigEntry
) -> bool:
"""Check if another ConfigDevice is actually the same as user_input.
This function only compares addresses and tcp ports, so it is possible to fool it with tricks like port forwarding.
"""
if entry.data[CONF_DEVICE] != user_input[CONF_DEVICE]:
return False
if gw_type == CONF_GATEWAY_TYPE_TCP:
entry_tcp_port: int = entry.data[CONF_TCP_PORT]
input_tcp_port: int = user_input[CONF_TCP_PORT]
return entry_tcp_port == input_tcp_port
if gw_type == CONF_GATEWAY_TYPE_MQTT:
entry_topics = {
entry.data[CONF_TOPIC_IN_PREFIX],
entry.data[CONF_TOPIC_OUT_PREFIX],
}
return (
user_input.get(CONF_TOPIC_IN_PREFIX) in entry_topics
or user_input.get(CONF_TOPIC_OUT_PREFIX) in entry_topics
)
return True |
Return MySensors devices for a hass platform name. | def get_mysensors_devices(
hass: HomeAssistant, domain: Platform
) -> dict[DevId, MySensorsChildEntity]:
"""Return MySensors devices for a hass platform name."""
if MYSENSORS_PLATFORM_DEVICES.format(domain) not in hass.data[DOMAIN]:
hass.data[DOMAIN][MYSENSORS_PLATFORM_DEVICES.format(domain)] = {}
devices: dict[DevId, MySensorsChildEntity] = hass.data[DOMAIN][
MYSENSORS_PLATFORM_DEVICES.format(domain)
]
return devices |
Validate that value is a windows serial port or a unix device. | def is_serial_port(value: str) -> str:
"""Validate that value is a windows serial port or a unix device."""
if sys.platform.startswith("win"):
ports = (f"COM{idx + 1}" for idx in range(256))
if value in ports:
return value
raise vol.Invalid(f"{value} is not a serial port")
return cv.isdevice(value) |
Validate that value is a valid address. | def is_socket_address(value: str) -> str:
"""Validate that value is a valid address."""
try:
socket.getaddrinfo(value, None)
except OSError as err:
raise vol.Invalid("Device is not a valid domain name or ip address") from err
return value |
Return a new callback for the gateway. | def _gw_callback_factory(
hass: HomeAssistant, gateway_id: GatewayId
) -> Callable[[Message], None]:
"""Return a new callback for the gateway."""
@callback
def mysensors_callback(msg: Message) -> None:
"""Handle messages from a MySensors gateway.
All MySenors messages are received here.
The messages are passed to handler functions depending on their type.
"""
_LOGGER.debug("Node update: node %s child %s", msg.node_id, msg.child_id)
msg_type = msg.gateway.const.MessageType(msg.type)
msg_handler = HANDLERS.get(msg_type.name)
if msg_handler is None:
return
msg_handler(hass, gateway_id, msg)
return mysensors_callback |
Handle a mysensors set message. | def handle_set(hass: HomeAssistant, gateway_id: GatewayId, msg: Message) -> None:
"""Handle a mysensors set message."""
validated = validate_set_msg(gateway_id, msg)
_handle_child_update(hass, gateway_id, validated) |
Handle a mysensors internal message. | def handle_internal(hass: HomeAssistant, gateway_id: GatewayId, msg: Message) -> None:
"""Handle a mysensors internal message."""
internal = msg.gateway.const.Internal(msg.sub_type)
if (handler := HANDLERS.get(internal.name)) is None:
return
handler(hass, gateway_id, msg) |
Handle an internal battery level message. | def handle_battery_level(
hass: HomeAssistant, gateway_id: GatewayId, msg: Message
) -> None:
"""Handle an internal battery level message."""
_handle_node_update(hass, gateway_id, msg) |
Handle an heartbeat. | def handle_heartbeat(hass: HomeAssistant, gateway_id: GatewayId, msg: Message) -> None:
"""Handle an heartbeat."""
_handle_node_update(hass, gateway_id, msg) |
Handle an internal sketch name message. | def handle_sketch_name(
hass: HomeAssistant, gateway_id: GatewayId, msg: Message
) -> None:
"""Handle an internal sketch name message."""
_handle_node_update(hass, gateway_id, msg) |
Handle an internal sketch version message. | def handle_sketch_version(
hass: HomeAssistant, gateway_id: GatewayId, msg: Message
) -> None:
"""Handle an internal sketch version message."""
_handle_node_update(hass, gateway_id, msg) |
Handle an internal presentation message. | def handle_presentation(
hass: HomeAssistant, gateway_id: GatewayId, msg: Message
) -> None:
"""Handle an internal presentation message."""
if msg.child_id == SYSTEM_CHILD_ID:
discover_mysensors_node(hass, gateway_id, msg.node_id) |
Handle a child update. | def _handle_child_update(
hass: HomeAssistant, gateway_id: GatewayId, validated: dict[Platform, list[DevId]]
) -> None:
"""Handle a child update."""
signals: list[str] = []
# Update all platforms for the device via dispatcher.
# Add/update entity for validated children.
for platform, dev_ids in validated.items():
devices = get_mysensors_devices(hass, platform)
new_dev_ids: list[DevId] = []
for dev_id in dev_ids:
if dev_id in devices:
signals.append(CHILD_CALLBACK.format(*dev_id))
else:
new_dev_ids.append(dev_id)
if new_dev_ids:
discover_mysensors_platform(hass, gateway_id, platform, new_dev_ids)
for signal in set(signals):
# Only one signal per device is needed.
# A device can have multiple platforms, ie multiple schemas.
async_dispatcher_send(hass, signal) |
Handle a node update. | def _handle_node_update(
hass: HomeAssistant, gateway_id: GatewayId, msg: Message
) -> None:
"""Handle a node update."""
signal = NODE_CALLBACK.format(gateway_id, msg.node_id)
async_dispatcher_send(hass, signal) |
Register a callback to be called when entry is unloaded.
This function is used by platforms to cleanup after themselves. | def on_unload(hass: HomeAssistant, gateway_id: GatewayId, fnct: Callable) -> None:
"""Register a callback to be called when entry is unloaded.
This function is used by platforms to cleanup after themselves.
"""
key = MYSENSORS_ON_UNLOAD.format(gateway_id)
if key not in hass.data[DOMAIN]:
hass.data[DOMAIN][key] = []
hass.data[DOMAIN][key].append(fnct) |
Discover a MySensors platform. | def discover_mysensors_platform(
hass: HomeAssistant, gateway_id: GatewayId, platform: str, new_devices: list[DevId]
) -> None:
"""Discover a MySensors platform."""
_LOGGER.debug("Discovering platform %s with devIds: %s", platform, new_devices)
async_dispatcher_send(
hass,
MYSENSORS_DISCOVERY.format(gateway_id, platform),
{
ATTR_DEVICES: new_devices,
CONF_NAME: DOMAIN,
ATTR_GATEWAY_ID: gateway_id,
},
) |
Discover a MySensors node. | def discover_mysensors_node(
hass: HomeAssistant, gateway_id: GatewayId, node_id: int
) -> None:
"""Discover a MySensors node."""
discovered_nodes = hass.data[DOMAIN].setdefault(
MYSENSORS_DISCOVERED_NODES.format(gateway_id), set()
)
if node_id not in discovered_nodes:
discovered_nodes.add(node_id)
async_dispatcher_send(
hass,
MYSENSORS_NODE_DISCOVERY,
{
ATTR_GATEWAY_ID: gateway_id,
ATTR_NODE_ID: node_id,
},
) |
Return a default validation schema for value types. | def default_schema(
gateway: BaseAsyncGateway, child: ChildSensor, value_type_name: ValueType
) -> vol.Schema:
"""Return a default validation schema for value types."""
schema = {value_type_name: cv.string}
return get_child_schema(gateway, child, value_type_name, schema) |
Return a validation schema for V_DIMMER. | def light_dimmer_schema(
gateway: BaseAsyncGateway, child: ChildSensor, value_type_name: ValueType
) -> vol.Schema:
"""Return a validation schema for V_DIMMER."""
schema = {"V_DIMMER": cv.string, "V_LIGHT": cv.string}
return get_child_schema(gateway, child, value_type_name, schema) |
Return a validation schema for V_PERCENTAGE. | def light_percentage_schema(
gateway: BaseAsyncGateway, child: ChildSensor, value_type_name: ValueType
) -> vol.Schema:
"""Return a validation schema for V_PERCENTAGE."""
schema = {"V_PERCENTAGE": cv.string, "V_STATUS": cv.string}
return get_child_schema(gateway, child, value_type_name, schema) |
Return a validation schema for V_RGB. | def light_rgb_schema(
gateway: BaseAsyncGateway, child: ChildSensor, value_type_name: ValueType
) -> vol.Schema:
"""Return a validation schema for V_RGB."""
schema = {"V_RGB": cv.string, "V_STATUS": cv.string}
return get_child_schema(gateway, child, value_type_name, schema) |
Return a validation schema for V_RGBW. | def light_rgbw_schema(
gateway: BaseAsyncGateway, child: ChildSensor, value_type_name: ValueType
) -> vol.Schema:
"""Return a validation schema for V_RGBW."""
schema = {"V_RGBW": cv.string, "V_STATUS": cv.string}
return get_child_schema(gateway, child, value_type_name, schema) |
Return a validation schema for V_IR_SEND. | def switch_ir_send_schema(
gateway: BaseAsyncGateway, child: ChildSensor, value_type_name: ValueType
) -> vol.Schema:
"""Return a validation schema for V_IR_SEND."""
schema = {"V_IR_SEND": cv.string, "V_LIGHT": cv.string}
return get_child_schema(gateway, child, value_type_name, schema) |
Return a child schema. | def get_child_schema(
gateway: BaseAsyncGateway,
child: ChildSensor,
value_type_name: ValueType,
schema: dict,
) -> vol.Schema:
"""Return a child schema."""
set_req = gateway.const.SetReq
child_schema = child.get_schema(gateway.protocol_version)
return child_schema.extend(
{
vol.Required(
set_req[name].value, msg=invalid_msg(gateway, child, name)
): child_schema.schema.get(set_req[name].value, valid)
for name, valid in schema.items()
},
extra=vol.ALLOW_EXTRA,
) |
Return a message for an invalid child during schema validation. | def invalid_msg(
gateway: BaseAsyncGateway, child: ChildSensor, value_type_name: ValueType
) -> str:
"""Return a message for an invalid child during schema validation."""
pres = gateway.const.Presentation
set_req = gateway.const.SetReq
return (
f"{pres(child.type).name} requires value_type {set_req[value_type_name].name}"
) |
Validate a set message. | def validate_set_msg(
gateway_id: GatewayId, msg: Message
) -> dict[Platform, list[DevId]]:
"""Validate a set message."""
if not validate_node(msg.gateway, msg.node_id):
return {}
child = msg.gateway.sensors[msg.node_id].children[msg.child_id]
return validate_child(gateway_id, msg.gateway, msg.node_id, child, msg.sub_type) |
Validate a node. | def validate_node(gateway: BaseAsyncGateway, node_id: int) -> bool:
"""Validate a node."""
if gateway.sensors[node_id].sketch_name is None:
_LOGGER.debug("Node %s is missing sketch name", node_id)
return False
return True |
Validate a child. Returns a dict mapping hass platform names to list of DevId. | def validate_child(
gateway_id: GatewayId,
gateway: BaseAsyncGateway,
node_id: int,
child: ChildSensor,
value_type: int | None = None,
) -> defaultdict[Platform, list[DevId]]:
"""Validate a child. Returns a dict mapping hass platform names to list of DevId."""
validated: defaultdict[Platform, list[DevId]] = defaultdict(list)
pres: type[IntEnum] = gateway.const.Presentation
set_req: type[IntEnum] = gateway.const.SetReq
child_type_name: SensorType | None = next(
(member.name for member in pres if member.value == child.type), None
)
if not child_type_name:
_LOGGER.warning("Child type %s is not supported", child.type)
return validated
value_types: set[int] = {value_type} if value_type else {*child.values}
value_type_names: set[ValueType] = {
member.name for member in set_req if member.value in value_types
}
platforms: list[Platform] = TYPE_TO_PLATFORMS.get(child_type_name, [])
if not platforms:
_LOGGER.warning("Child type %s is not supported", child.type)
return validated
for platform in platforms:
platform_v_names: set[ValueType] = FLAT_PLATFORM_TYPES[
platform, child_type_name
]
v_names: set[ValueType] = platform_v_names & value_type_names
if not v_names:
child_value_names: set[ValueType] = {
member.name for member in set_req if member.value in child.values
}
v_names = platform_v_names & child_value_names
for v_name in v_names:
child_schema_gen = SCHEMAS.get((platform, v_name), default_schema)
child_schema = child_schema_gen(gateway, child, v_name)
try:
child_schema(child.values)
except vol.Invalid as exc:
_LOGGER.warning(
"Invalid %s on node %s, %s platform: %s",
child,
node_id,
platform,
exc,
)
continue
dev_id: DevId = (
gateway_id,
node_id,
child.id,
set_req[v_name].value,
)
validated[platform].append(dev_id)
return validated |
Set up a MySensors platform.
Sets up a bunch of instances of a single platform that is supported by this
integration.
The function is given a list of device ids, each one describing an instance
to set up. The function is also given a class.
A new instance of the class is created for every device id, and the device
id is given to the constructor of the class. | def setup_mysensors_platform(
hass: HomeAssistant,
domain: Platform, # hass platform name
discovery_info: DiscoveryInfo,
device_class: type[MySensorsChildEntity]
| Mapping[SensorType, type[MySensorsChildEntity]],
device_args: (
None | tuple
) = None, # extra arguments that will be given to the entity constructor
async_add_entities: Callable | None = None,
) -> list[MySensorsChildEntity] | None:
"""Set up a MySensors platform.
Sets up a bunch of instances of a single platform that is supported by this
integration.
The function is given a list of device ids, each one describing an instance
to set up. The function is also given a class.
A new instance of the class is created for every device id, and the device
id is given to the constructor of the class.
"""
if device_args is None:
device_args = ()
new_devices: list[MySensorsChildEntity] = []
new_dev_ids: list[DevId] = discovery_info[ATTR_DEVICES]
for dev_id in new_dev_ids:
devices: dict[DevId, MySensorsChildEntity] = get_mysensors_devices(hass, domain)
if dev_id in devices:
_LOGGER.debug(
"Skipping setup of %s for platform %s as it already exists",
dev_id,
domain,
)
continue
gateway_id, node_id, child_id, value_type = dev_id
gateway: BaseAsyncGateway = hass.data[DOMAIN][MYSENSORS_GATEWAYS][gateway_id]
if isinstance(device_class, dict):
child = gateway.sensors[node_id].children[child_id]
s_type = gateway.const.Presentation(child.type).name
device_class_copy = device_class[s_type]
else:
device_class_copy = device_class
args_copy = (*device_args, gateway_id, gateway, node_id, child_id, value_type)
devices[dev_id] = device_class_copy(*args_copy)
new_devices.append(devices[dev_id])
if new_devices:
_LOGGER.info("Adding new devices: %s", new_devices)
if async_add_entities is not None:
async_add_entities(new_devices)
return new_devices |
Get description for a device point.
Priorities:
1. Category specific prefix e.g "NIBEF"
2. Default to None | def get_description(device_point: DevicePoint) -> BinarySensorEntityDescription | None:
"""Get description for a device point.
Priorities:
1. Category specific prefix e.g "NIBEF"
2. Default to None
"""
prefix, _, _ = device_point.category.partition(" ")
return CATEGORY_BASED_DESCRIPTIONS.get(prefix, {}).get(device_point.parameter_id) |
Find entity platform for a DevicePoint. | def find_matching_platform(
device_point: DevicePoint,
description: SensorEntityDescription | NumberEntityDescription | None = None,
) -> Platform:
"""Find entity platform for a DevicePoint."""
if (
len(device_point.enum_values) == 2
and device_point.enum_values[0]["value"] == "0"
and device_point.enum_values[1]["value"] == "1"
):
if device_point.writable:
return Platform.SWITCH
return Platform.BINARY_SENSOR
if (
description
and description.native_unit_of_measurement == "DM"
or (device_point.raw["maxValue"] and device_point.raw["minValue"])
):
if device_point.writable:
return Platform.NUMBER
return Platform.SENSOR
return Platform.SENSOR |
Check if entity should be skipped for this device model. | def skip_entity(model: str, device_point: DevicePoint) -> bool:
"""Check if entity should be skipped for this device model."""
if model == "SMO 20":
if len(device_point.smart_home_categories) > 0 or device_point.parameter_id in (
"40940",
"47011",
"47015",
"47028",
"47032",
"50004",
):
return False
return True
return False |
Get description for a device point.
Priorities:
1. Category specific prefix e.g "NIBEF"
2. Global parameter_unit e.g. "DM"
3. Default to None | def get_description(device_point: DevicePoint) -> NumberEntityDescription | None:
"""Get description for a device point.
Priorities:
1. Category specific prefix e.g "NIBEF"
2. Global parameter_unit e.g. "DM"
3. Default to None
"""
prefix, _, _ = device_point.category.partition(" ")
description = CATEGORY_BASED_DESCRIPTIONS.get(prefix, {}).get(
device_point.parameter_id
)
if description is None:
description = DEVICE_POINT_UNIT_DESCRIPTIONS.get(device_point.parameter_unit)
return description |
Get description for a device point.
Priorities:
1. Category specific prefix e.g "NIBEF"
2. Global parameter_unit e.g. "°C"
3. Default to None | def get_description(device_point: DevicePoint) -> SensorEntityDescription | None:
"""Get description for a device point.
Priorities:
1. Category specific prefix e.g "NIBEF"
2. Global parameter_unit e.g. "°C"
3. Default to None
"""
description = None
prefix, _, _ = device_point.category.partition(" ")
description = CATEGORY_BASED_DESCRIPTIONS.get(prefix, {}).get(
device_point.parameter_id
)
if description is None:
description = DEVICE_POINT_UNIT_DESCRIPTIONS.get(device_point.parameter_unit)
return description |
Get description for a device point.
Priorities:
1. Category specific prefix e.g "NIBEF"
2. Default to None | def get_description(device_point: DevicePoint) -> SwitchEntityDescription | None:
"""Get description for a device point.
Priorities:
1. Category specific prefix e.g "NIBEF"
2. Default to None
"""
prefix, _, _ = device_point.category.partition(" ")
return CATEGORY_BASED_DESCRIPTIONS.get(prefix, {}).get(device_point.parameter_id) |
Update all devices. | def create_devices(
hass: HomeAssistant, config_entry: ConfigEntry, coordinator: MyUplinkDataCoordinator
) -> None:
"""Update all devices."""
device_registry = dr.async_get(hass)
for system in coordinator.data.systems:
devices_in_system = [x.id for x in system.devices]
for device_id, device in coordinator.data.devices.items():
if device_id in devices_in_system:
device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
identifiers={(DOMAIN, device_id)},
name=get_system_name(system),
manufacturer=get_manufacturer(device),
model=get_model(device),
sw_version=device.firmwareCurrent,
serial_number=device.product_serial_number,
) |
Set up the NAD platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the NAD platform."""
if config.get(CONF_TYPE) in ("RS232", "Telnet"):
add_entities(
[NAD(config)],
True,
)
else:
add_entities(
[NADtcp(config)],
True,
) |
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."""
nsapi = ns_api.NSAPI(config[CONF_API_KEY])
try:
stations = nsapi.get_stations()
except (
requests.exceptions.ConnectionError,
requests.exceptions.HTTPError,
) as error:
_LOGGER.error("Could not connect to the internet: %s", error)
raise PlatformNotReady from error
except RequestParametersError as error:
_LOGGER.error("Could not fetch stations, please check configuration: %s", error)
return
sensors = []
for departure in config.get(CONF_ROUTES, {}):
if not valid_stations(
stations,
[departure.get(CONF_FROM), departure.get(CONF_VIA), departure.get(CONF_TO)],
):
continue
sensors.append(
NSDepartureSensor(
nsapi,
departure.get(CONF_NAME),
departure.get(CONF_FROM),
departure.get(CONF_TO),
departure.get(CONF_VIA),
departure.get(CONF_TIME),
)
)
add_entities(sensors, True) |
Verify the existence of the given station codes. | def valid_stations(stations, given_stations):
"""Verify the existence of the given station codes."""
for station in given_stations:
if station is None:
continue
if not any(s.code == station.upper() for s in stations):
_LOGGER.warning("Station '%s' is not a valid station", station)
return False
return True |
Create a GoogleNestSubscriber with an access token. | def new_subscriber_with_token(
hass: HomeAssistant,
access_token: str,
project_id: str,
subscriber_id: str,
) -> GoogleNestSubscriber:
"""Create a GoogleNestSubscriber with an access token."""
return GoogleNestSubscriber(
AccessTokenAuthImpl(
aiohttp_client.async_get_clientsession(hass),
access_token,
),
project_id,
subscriber_id,
) |
Create a new subscription id. | def _generate_subscription_id(cloud_project_id: str) -> str:
"""Create a new subscription id."""
rnd = get_random_string(SUBSCRIPTION_RAND_LENGTH)
return SUBSCRIPTION_FORMAT.format(cloud_project_id=cloud_project_id, rnd=rnd) |
Pick a user friendly config title based on the Google Home name(s). | def generate_config_title(structures: Iterable[Structure]) -> str | None:
"""Pick a user friendly config title based on the Google Home name(s)."""
names: list[str] = [
trait.custom_name
for structure in structures
if (trait := structure.traits.get(InfoTrait.NAME)) and trait.custom_name
]
if not names:
return None
return ", ".join(names) |
Return a mapping of all nest devices for all config entries. | def async_nest_devices(hass: HomeAssistant) -> Mapping[str, Device]:
"""Return a mapping of all nest devices for all config entries."""
devices = {}
for entry_id in hass.data[DOMAIN]:
if not (device_manager := hass.data[DOMAIN][entry_id].get(DATA_DEVICE_MANAGER)):
continue
devices.update(
{device.name: device for device in device_manager.devices.values()}
)
return devices |
Return a mapping of all nest devices by home assistant device id, for all config entries. | def async_nest_devices_by_device_id(hass: HomeAssistant) -> Mapping[str, Device]:
"""Return a mapping of all nest devices by home assistant device id, for all config entries."""
device_registry = dr.async_get(hass)
devices = {}
for nest_device_id, device in async_nest_devices(hass).items():
if device_entry := device_registry.async_get_device(
identifiers={(DOMAIN, nest_device_id)}
):
devices[device_entry.id] = device
return devices |
Return dict of available devices. | def _async_get_nest_devices(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict[str, Device]:
"""Return dict of available devices."""
if DATA_SDM not in config_entry.data:
return {}
if (
config_entry.entry_id not in hass.data[DOMAIN]
or DATA_DEVICE_MANAGER not in hass.data[DOMAIN][config_entry.entry_id]
):
return {}
device_manager: DeviceManager = hass.data[DOMAIN][config_entry.entry_id][
DATA_DEVICE_MANAGER
]
return device_manager.devices |
Return a mapping of device id to eligible Nest event media devices. | def async_get_media_source_devices(hass: HomeAssistant) -> Mapping[str, Device]:
"""Return a mapping of device id to eligible Nest event media devices."""
devices = async_nest_devices_by_device_id(hass)
return {
device_id: device
for device_id, device in devices.items()
if CameraEventImageTrait.NAME in device.traits
or CameraClipPreviewTrait.NAME in device.traits
} |
Parse the identifier path string into a MediaId. | def parse_media_id(identifier: str | None = None) -> MediaId | None:
"""Parse the identifier path string into a MediaId."""
if identifier is None or identifier == "":
return None
parts = identifier.split("/")
if len(parts) > 1:
return MediaId(parts[0], parts[1])
return MediaId(parts[0]) |
Return devices in the root. | def _browse_root() -> BrowseMediaSource:
"""Return devices in the root."""
return BrowseMediaSource(
domain=DOMAIN,
identifier="",
media_class=MediaClass.DIRECTORY,
media_content_type=MediaType.VIDEO,
children_media_class=MediaClass.VIDEO,
title=MEDIA_SOURCE_TITLE,
can_play=False,
can_expand=True,
thumbnail=None,
children=[],
) |
Return details for the specified device. | def _browse_device(device_id: MediaId, device: Device) -> BrowseMediaSource:
"""Return details for the specified device."""
device_info = NestDeviceInfo(device)
return BrowseMediaSource(
domain=DOMAIN,
identifier=device_id.identifier,
media_class=MediaClass.DIRECTORY,
media_content_type=MediaType.VIDEO,
children_media_class=MediaClass.VIDEO,
title=DEVICE_TITLE_FORMAT.format(device_name=device_info.device_name),
can_play=False,
can_expand=True,
thumbnail=None,
children=[],
) |
Build a BrowseMediaSource for a specific clip preview event. | def _browse_clip_preview(
event_id: MediaId, device: Device, event: ClipPreviewSession
) -> BrowseMediaSource:
"""Build a BrowseMediaSource for a specific clip preview event."""
types = [
MEDIA_SOURCE_EVENT_TITLE_MAP.get(event_type, "Event")
for event_type in event.event_types
]
return BrowseMediaSource(
domain=DOMAIN,
identifier=event_id.identifier,
media_class=MediaClass.IMAGE,
media_content_type=MediaType.IMAGE,
title=CLIP_TITLE_FORMAT.format(
event_name=", ".join(types),
event_time=dt_util.as_local(event.timestamp).strftime(DATE_STR_FORMAT),
),
can_play=True,
can_expand=False,
thumbnail=EVENT_THUMBNAIL_URL_FORMAT.format(
device_id=event_id.device_id, event_token=event_id.event_token
),
children=[],
) |
Build a BrowseMediaSource for a specific image event. | def _browse_image_event(
event_id: MediaId, device: Device, event: ImageSession
) -> BrowseMediaSource:
"""Build a BrowseMediaSource for a specific image event."""
return BrowseMediaSource(
domain=DOMAIN,
identifier=event_id.identifier,
media_class=MediaClass.IMAGE,
media_content_type=MediaType.IMAGE,
title=CLIP_TITLE_FORMAT.format(
event_name=MEDIA_SOURCE_EVENT_TITLE_MAP.get(event.event_type, "Event"),
event_time=dt_util.as_local(event.timestamp).strftime(DATE_STR_FORMAT),
),
can_play=False,
can_expand=False,
thumbnail=EVENT_THUMBNAIL_URL_FORMAT.format(
device_id=event_id.device_id, event_token=event_id.event_token
),
children=[],
) |
Return the Netatmo API scopes based on the auth implementation. | def get_api_scopes(auth_implementation: str) -> Iterable[str]:
"""Return the Netatmo API scopes based on the auth implementation."""
if auth_implementation == cloud.DOMAIN:
return set(
{
scope
for scope in pyatmo.const.ALL_SCOPES
if scope not in API_SCOPES_EXCLUDED_FROM_CLOUD
}
)
return sorted(pyatmo.const.ALL_SCOPES) |
Fix coordinates if they don't comply with the Netatmo API. | def fix_coordinates(user_input: dict) -> dict:
"""Fix coordinates if they don't comply with the Netatmo API."""
# Ensure coordinates have acceptable length for the Netatmo API
for coordinate in (CONF_LAT_NE, CONF_LAT_SW, CONF_LON_NE, CONF_LON_SW):
if len(str(user_input[coordinate]).split(".")[1]) < 7:
user_input[coordinate] = user_input[coordinate] + 0.0000001
# Swap coordinates if entered in wrong order
if user_input[CONF_LAT_NE] < user_input[CONF_LAT_SW]:
user_input[CONF_LAT_NE], user_input[CONF_LAT_SW] = (
user_input[CONF_LAT_SW],
user_input[CONF_LAT_NE],
)
if user_input[CONF_LON_NE] < user_input[CONF_LON_SW]:
user_input[CONF_LON_NE], user_input[CONF_LON_SW] = (
user_input[CONF_LON_SW],
user_input[CONF_LON_NE],
)
return user_input |
Remove html tags from string. | def remove_html_tags(text: str) -> str:
"""Remove html tags from string."""
clean = re.compile("<.*?>")
return re.sub(clean, "", text) |
Parse identifier. | def async_parse_identifier(
item: MediaSourceItem,
) -> tuple[str, str, int | None]:
"""Parse identifier."""
if not item.identifier or "/" not in item.identifier:
return "events", "", None
source, path = item.identifier.lstrip("/").split("/", 1)
if source != "events":
raise Unresolvable("Unknown source directory.")
if "/" in path:
camera_id, event_id = path.split("/", 1)
return source, camera_id, int(event_id)
return source, path, None |
Process health index and return string for display. | def process_health(health: StateType) -> str | None:
"""Process health index and return string for display."""
if not isinstance(health, int):
return None
return {
0: "healthy",
1: "fine",
2: "fair",
3: "poor",
}.get(health, "unhealthy") |
Process wifi signal strength and return string for display. | def process_rf(strength: StateType) -> str | None:
"""Process wifi signal strength and return string for display."""
if not isinstance(strength, int):
return None
if strength >= 90:
return "Low"
if strength >= 76:
return "Medium"
if strength >= 60:
return "High"
return "Full" |
Process wifi signal strength and return string for display. | def process_wifi(strength: StateType) -> str | None:
"""Process wifi signal strength and return string for display."""
if not isinstance(strength, int):
return None
if strength >= 86:
return "Low"
if strength >= 71:
return "Medium"
if strength >= 56:
return "High"
return "Full" |
Evaluate events from webhook. | def async_evaluate_event(hass: HomeAssistant, event_data: dict) -> None:
"""Evaluate events from webhook."""
event_type = event_data.get(ATTR_EVENT_TYPE, "None")
if event_type == "person":
for person in event_data.get(ATTR_PERSONS, {}):
person_event_data = dict(event_data)
person_event_data[ATTR_ID] = person.get(ATTR_ID)
person_event_data[ATTR_NAME] = hass.data[DOMAIN][DATA_PERSONS][
event_data[ATTR_HOME_ID]
].get(person_event_data[ATTR_ID], DEFAULT_PERSON)
person_event_data[ATTR_IS_KNOWN] = person.get(ATTR_IS_KNOWN)
person_event_data[ATTR_FACE_URL] = person.get(ATTR_FACE_URL)
async_send_event(hass, event_type, person_event_data)
else:
async_send_event(hass, event_type, event_data) |
Send events. | def async_send_event(hass: HomeAssistant, event_type: str, data: dict) -> None:
"""Send events."""
_LOGGER.debug("%s: %s", event_type, data)
async_dispatcher_send(
hass,
f"signal-{DOMAIN}-webhook-{event_type}",
{"type": event_type, "data": data},
)
event_data = {
"type": event_type,
"data": data,
}
if event_type in EVENT_ID_MAP:
data_device_id = data[EVENT_ID_MAP[event_type]]
event_data[ATTR_DEVICE_ID] = hass.data[DOMAIN][DATA_DEVICE_IDS].get(
data_device_id
)
hass.bus.async_fire(
event_type=NETATMO_EVENT,
event_data=event_data,
) |
Get the Netgear API and login to it. | def get_api(
password: str,
host: str | None = None,
username: str | None = None,
port: int | None = None,
ssl: bool = False,
) -> Netgear:
"""Get the Netgear API and login to it."""
api: Netgear = Netgear(password, host, username, port, ssl)
if not api.login_try_port():
raise CannotLoginException
return api |
Create notify service and add a repair issue when appropriate. | def _legacy_task(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Create notify service and add a repair issue when appropriate."""
# Discovery can happen up to 2 times for notify depending on existing yaml config
# One for the name of the config entry, allows the user to customize the name
# One for each notify described in the yaml config which goes away with config flow
# One for the default if the user never specified one
hass.async_create_task(
discovery.async_load_platform(
hass,
Platform.NOTIFY,
DOMAIN,
{CONF_HOST: entry.data[CONF_HOST], CONF_NAME: entry.title},
hass.data[DATA_HASS_CONFIG],
)
)
if not (lte_configs := hass.data[DATA_HASS_CONFIG].get(DOMAIN, [])):
return
async_create_issue(
hass,
DOMAIN,
"deprecated_notify",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
severity=IssueSeverity.WARNING,
translation_key="deprecated_notify",
translation_placeholders={
"name": f"{Platform.NOTIFY}.{entry.title.lower().replace(' ', '_')}"
},
)
for lte_config in lte_configs:
if lte_config[CONF_HOST] == entry.data[CONF_HOST]:
if not lte_config[CONF_NOTIFY]:
hass.async_create_task(
discovery.async_load_platform(
hass,
Platform.NOTIFY,
DOMAIN,
{CONF_HOST: entry.data[CONF_HOST], CONF_NAME: DOMAIN},
hass.data[DATA_HASS_CONFIG],
)
)
break
for notify_conf in lte_config[CONF_NOTIFY]:
discovery_info = {
CONF_HOST: lte_config[CONF_HOST],
CONF_NAME: notify_conf.get(CONF_NAME),
CONF_NOTIFY: notify_conf,
}
hass.async_create_task(
discovery.async_load_platform(
hass,
Platform.NOTIFY,
DOMAIN,
discovery_info,
hass.data[DATA_HASS_CONFIG],
)
)
break |
Set up the Netio platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Netio platform."""
host = config[CONF_HOST]
username = config[CONF_USERNAME]
password = config[CONF_PASSWORD]
port = config[CONF_PORT]
if not DEVICES:
hass.http.register_view(NetioApiView)
dev = Netio(host, port, username, password)
DEVICES[host] = Device(dev, [])
# Throttle the update for all Netio switches of one Netio
dev.update = util.Throttle(MIN_TIME_BETWEEN_SCANS)(dev.update)
for key in config[CONF_OUTLETS]:
switch = NetioSwitch(DEVICES[host].netio, key, config[CONF_OUTLETS][key])
DEVICES[host].entities.append(switch)
add_entities(DEVICES[host].entities)
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, dispose) |
Close connections to Netio Devices. | def dispose(event):
"""Close connections to Netio Devices."""
for value in DEVICES.values():
value.netio.stop() |
Enable configured adapters. | def enable_adapters(adapters: list[Adapter], enabled_interfaces: list[str]) -> bool:
"""Enable configured adapters."""
_reset_enabled_adapters(adapters)
if not enabled_interfaces:
return False
found_adapter = False
for adapter in adapters:
if adapter["name"] in enabled_interfaces:
adapter["enabled"] = True
found_adapter = True
return found_adapter |
Enable auto detected adapters. | def enable_auto_detected_adapters(adapters: list[Adapter]) -> None:
"""Enable auto detected adapters."""
enable_adapters(
adapters, [adapter["name"] for adapter in adapters if adapter["auto"]]
) |
Adapter has a non-loopback and non-link-local address. | def _adapter_has_external_address(adapter: Adapter) -> bool:
"""Adapter has a non-loopback and non-link-local address."""
return any(
_has_external_address(v4_config["address"]) for v4_config in adapter["ipv4"]
) or any(
_has_external_address(v6_config["address"]) for v6_config in adapter["ipv6"]
) |
Convert an ifaddr adapter to ha. | def _ifaddr_adapter_to_ha(
adapter: ifaddr.Adapter, next_hop_address: None | IPv4Address | IPv6Address
) -> Adapter:
"""Convert an ifaddr adapter to ha."""
ip_v4s: list[IPv4ConfiguredAddress] = []
ip_v6s: list[IPv6ConfiguredAddress] = []
default = False
auto = False
for ip_config in adapter.ips:
if ip_config.is_IPv6:
ip_addr = ip_address(ip_config.ip[0])
ip_v6s.append(_ip_v6_from_adapter(ip_config))
else:
assert not isinstance(ip_config.ip, tuple)
ip_addr = ip_address(ip_config.ip)
ip_v4s.append(_ip_v4_from_adapter(ip_config))
if ip_addr == next_hop_address:
default = True
if _ip_address_is_external(ip_addr):
auto = True
return {
"name": adapter.nice_name,
"index": adapter.index,
"enabled": False,
"auto": auto,
"default": default,
"ipv4": ip_v4s,
"ipv6": ip_v6s,
} |
Return the source ip that will reach target_ip. | def async_get_source_ip(target_ip: str) -> str | None:
"""Return the source ip that will reach target_ip."""
test_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
test_sock.setblocking(False) # must be non-blocking for async
try:
test_sock.connect((target_ip, 1))
return cast(str, test_sock.getsockname()[0])
except Exception: # pylint: disable=broad-except
_LOGGER.debug(
(
"The system could not auto detect the source ip for %s on your"
" operating system"
),
target_ip,
)
return None
finally:
test_sock.close() |
Register network websocket commands. | def async_register_websocket_commands(hass: HomeAssistant) -> None:
"""Register network websocket commands."""
websocket_api.async_register_command(hass, websocket_network_adapters)
websocket_api.async_register_command(hass, websocket_network_adapters_configure) |
Check to see if any non-default adapter is enabled. | def async_only_default_interface_enabled(adapters: list[Adapter]) -> bool:
"""Check to see if any non-default adapter is enabled."""
return not any(
adapter["enabled"] and not adapter["default"] for adapter in adapters
) |
Set up the Neurio sensor. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Neurio sensor."""
api_key = config.get(CONF_API_KEY)
api_secret = config.get(CONF_API_SECRET)
sensor_id = config.get(CONF_SENSOR_ID)
data = NeurioData(api_key, api_secret, sensor_id)
@Throttle(MIN_TIME_BETWEEN_DAILY_UPDATES)
def update_daily():
"""Update the daily power usage."""
data.get_daily_usage()
@Throttle(MIN_TIME_BETWEEN_ACTIVE_UPDATES)
def update_active():
"""Update the active power usage."""
data.get_active_power()
update_daily()
update_active()
# Active power sensor
add_entities([NeurioEnergy(data, ACTIVE_NAME, ACTIVE_TYPE, update_active)])
# Daily power sensor
add_entities([NeurioEnergy(data, DAILY_NAME, DAILY_TYPE, update_daily)]) |
HTTP status codes that mean invalid auth. | def is_invalid_auth_code(http_status_code):
"""HTTP status codes that mean invalid auth."""
if http_status_code in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN):
return True
return False |
Convert an actual percentage (0.0-1.0) to 0-100 scale. | def percent_conv(val):
"""Convert an actual percentage (0.0-1.0) to 0-100 scale."""
if val is None:
return None
return round(val * 100.0, 1) |
Return list version of whatever value is passed in.
This is used to provide a consistent way of interacting with the JSON
results from the API. There are several attributes that will either missing
if there are no values, a single dictionary if there is only one value, and
a list if there are multiple. | def listify(maybe_list: Any) -> list[Any]:
"""Return list version of whatever value is passed in.
This is used to provide a consistent way of interacting with the JSON
results from the API. There are several attributes that will either missing
if there are no values, a single dictionary if there is only one value, and
a list if there are multiple.
"""
if maybe_list is None:
return []
if isinstance(maybe_list, list):
return maybe_list
return [maybe_list] |
Return the first item out of a list or returns back the input. | def maybe_first(maybe_list: list[Any] | None) -> Any:
"""Return the first item out of a list or returns back the input."""
if isinstance(maybe_list, list) and maybe_list:
return maybe_list[0]
return maybe_list |
Register system health callbacks. | def async_register(
hass: HomeAssistant, register: system_health.SystemHealthRegistration
) -> None:
"""Register system health callbacks."""
register.async_register_info(system_health_info) |
Calculate the integer limits of a signed or unsigned integer value. | def _get_numeric_limits(size: str):
"""Calculate the integer limits of a signed or unsigned integer value."""
if size[0] == "u":
return (0, pow(2, int(size[1:])) - 1)
if size[0] == "s":
return (-pow(2, int(size[1:]) - 1), pow(2, int(size[1:]) - 1) - 1)
raise ValueError(f"Invalid size type specified {size}") |
Hash url to create a unique ID. | def hash_from_url(url: str) -> str:
"""Hash url to create a unique ID."""
return hashlib.sha256(url.encode("utf-8")).hexdigest() |
Set up the NILU air quality sensor. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the NILU air quality sensor."""
name: str = config[CONF_NAME]
area: str | None = config.get(CONF_AREA)
stations: list[str] | None = config.get(CONF_STATION)
show_on_map: bool = config[CONF_SHOW_ON_MAP]
sensors = []
if area:
stations = lookup_stations_in_area(area)
elif not stations:
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
location_client = create_location_client(latitude, longitude)
stations = location_client.station_names
assert stations is not None
for station in stations:
client = NiluData(create_station_client(station))
client.update()
if client.data.sensors:
sensors.append(NiluSensor(client, name, show_on_map))
else:
_LOGGER.warning("%s didn't give any sensors results", station)
add_entities(sensors, True) |
Swap keys and values in dict. | def swap_key_value(dict_to_sort: dict[str, str]) -> dict[str, str]:
"""Swap keys and values in dict."""
all_region_codes_swaped: dict[str, str] = {}
for key, value in dict_to_sort.items():
if value not in all_region_codes_swaped:
all_region_codes_swaped[value] = key
else:
for i in range(len(dict_to_sort)):
tmp_value: str = f"{value}_{i}"
if tmp_value not in all_region_codes_swaped:
all_region_codes_swaped[tmp_value] = key
break
return dict(sorted(all_region_codes_swaped.items(), key=lambda ele: ele[1])) |
Split regions alphabetical. | def split_regions(
_all_region_codes_sorted: dict[str, str], regions: dict[str, dict[str, Any]]
) -> dict[str, dict[str, Any]]:
"""Split regions alphabetical."""
for index, name in _all_region_codes_sorted.items():
for region_name, grouping_letters in CONST_REGION_MAPPING.items():
if name[0] in grouping_letters:
regions[region_name][index] = name
break
return regions |
Prepare the user inputs. | def prepare_user_input(
user_input: dict[str, Any], _all_region_codes_sorted: dict[str, str]
) -> dict[str, Any]:
"""Prepare the user inputs."""
tmp: dict[str, Any] = {}
for reg in user_input[CONF_REGIONS]:
tmp[_all_region_codes_sorted[reg]] = reg.split("_", 1)[0]
compact: dict[str, Any] = {}
for key, val in tmp.items():
if val in compact:
# Abenberg, St + Abenberger Wald
compact[val] = f"{compact[val]} + {key}"
break
compact[val] = key
user_input[CONF_REGIONS] = compact
return user_input |
Set up of a Nissan Leaf binary sensor. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up of a Nissan Leaf binary sensor."""
if discovery_info is None:
return
entities: list[LeafEntity] = []
for vin, datastore in hass.data[DATA_LEAF].items():
_LOGGER.debug("Adding binary_sensors for vin=%s", vin)
entities.append(LeafPluggedInSensor(datastore))
entities.append(LeafChargingSensor(datastore))
add_entities(entities, True) |
Set up of a Nissan Leaf button. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up of a Nissan Leaf button."""
if discovery_info is None:
return
entities: list[LeafEntity] = []
for vin, datastore in hass.data[DATA_LEAF].items():
_LOGGER.debug("Adding button for vin=%s", vin)
entities.append(LeafChargingButton(datastore))
add_entities(entities, True) |
Sensors setup. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Sensors setup."""
if discovery_info is None:
return
entities: list[LeafEntity] = []
for vin, datastore in hass.data[DATA_LEAF].items():
_LOGGER.debug("Adding sensors for vin=%s", vin)
entities.append(LeafBatterySensor(datastore))
entities.append(LeafRangeSensor(datastore, True))
entities.append(LeafRangeSensor(datastore, False))
add_entities(entities, True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.