response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Decorate WS function to ensure user owns the webhook ID. | def _ensure_webhook_access(func):
"""Decorate WS function to ensure user owns the webhook ID."""
@callback
@wraps(func)
def with_webhook_access(hass, connection, msg):
# Validate that the webhook ID is registered to the user of the websocket connection
config_entry = hass.data[DOMAIN][DATA_CONFIG_ENTRIES].get(msg["webhook_id"])
if config_entry is None:
connection.send_error(
msg["id"], websocket_api.ERR_NOT_FOUND, "Webhook ID not found"
)
return
if config_entry.data[CONF_USER_ID] != connection.user.id:
connection.send_error(
msg["id"],
websocket_api.ERR_UNAUTHORIZED,
"User not linked to this webhook ID",
)
return
func(hass, connection, msg)
return with_webhook_access |
Confirm receipt of a push notification. | def handle_push_notification_confirm(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Confirm receipt of a push notification."""
channel: PushChannel | None = hass.data[DOMAIN][DATA_PUSH_CHANNEL].get(
msg["webhook_id"]
)
if channel is None:
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
"Push notification channel not found",
)
return
if channel.async_confirm_notification(msg["confirm_id"]):
connection.send_result(msg["id"])
else:
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
"Push notification channel not found",
) |
Set up X10 dimmers over a mochad controller. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up X10 dimmers over a mochad controller."""
mochad_controller: MochadCtrl = hass.data[DOMAIN]
devs: list[dict[str, Any]] = config[CONF_DEVICES]
add_entities([MochadLight(hass, mochad_controller.ctrl, dev) for dev in devs]) |
Set up X10 switches over a mochad controller. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up X10 switches over a mochad controller."""
mochad_controller: MochadCtrl = hass.data[DOMAIN]
devs: list[dict[str, str]] = config[CONF_DEVICES]
add_entities([MochadSwitch(hass, mochad_controller.ctrl, dev) for dev in devs]) |
Set up the mochad component. | def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the mochad component."""
conf = config[DOMAIN]
host = conf.get(CONF_HOST)
port = conf.get(CONF_PORT)
try:
mochad_controller = MochadCtrl(host, port)
except exceptions.ConfigurationError:
_LOGGER.exception("Unexpected exception")
return False
def stop_mochad(event):
"""Stop the Mochad service."""
mochad_controller.disconnect()
def start_mochad(event):
"""Start the Mochad service."""
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_mochad)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_mochad)
hass.data[DOMAIN] = mochad_controller
return True |
Create issue modbus style. | def modbus_create_issue(
hass: HomeAssistant, key: str, subs: list[str], err: str
) -> None:
"""Create issue modbus style."""
async_create_issue(
hass,
DOMAIN,
key,
is_fixable=False,
severity=IssueSeverity.WARNING,
translation_key=key,
translation_placeholders={
"sub_1": subs[0],
"sub_2": subs[1],
"sub_3": subs[2],
"integration": DOMAIN,
},
issue_domain=DOMAIN,
learn_more_url="https://www.home-assistant.io/integrations/modbus",
)
_LOGGER.warning(err) |
Sensor schema validator. | def struct_validator(config: dict[str, Any]) -> dict[str, Any]:
"""Sensor schema validator."""
name = config[CONF_NAME]
data_type = config[CONF_DATA_TYPE]
if data_type == "int":
data_type = config[CONF_DATA_TYPE] = DataType.INT16
count = config.get(CONF_COUNT)
structure = config.get(CONF_STRUCTURE)
slave_count = config.get(CONF_SLAVE_COUNT, config.get(CONF_VIRTUAL_COUNT))
validator = DEFAULT_STRUCT_FORMAT[data_type].validate_parm
swap_type = config.get(CONF_SWAP)
swap_dict = {
CONF_SWAP_BYTE: validator.swap_byte,
CONF_SWAP_WORD: validator.swap_word,
CONF_SWAP_WORD_BYTE: validator.swap_word,
}
swap_type_validator = swap_dict[swap_type] if swap_type else OPTIONAL
for entry in (
(count, validator.count, CONF_COUNT),
(structure, validator.structure, CONF_STRUCTURE),
(
slave_count,
validator.slave_count,
f"{CONF_VIRTUAL_COUNT} / {CONF_SLAVE_COUNT}:",
),
(swap_type, swap_type_validator, f"{CONF_SWAP}:{swap_type}"),
):
if entry[0] is None:
if entry[1] == DEMANDED:
error = f"{name}: `{entry[2]}` missing, demanded with `{CONF_DATA_TYPE}: {data_type}`"
raise vol.Invalid(error)
elif entry[1] == ILLEGAL:
error = f"{name}: `{entry[2]}` illegal with `{CONF_DATA_TYPE}: {data_type}`"
raise vol.Invalid(error)
if config[CONF_DATA_TYPE] == DataType.CUSTOM:
assert isinstance(structure, str)
assert isinstance(count, int)
try:
size = struct.calcsize(structure)
except struct.error as err:
raise vol.Invalid(
f"{name}: error in structure format --> {str(err)}"
) from err
bytecount = count * 2
if bytecount != size:
raise vol.Invalid(
f"{name}: Size of structure is {size} bytes but `{CONF_COUNT}: {count}` is {bytecount} bytes"
)
else:
if data_type != DataType.STRING:
config[CONF_COUNT] = DEFAULT_STRUCT_FORMAT[data_type].register_count
if slave_count:
structure = (
f">{slave_count + 1}{DEFAULT_STRUCT_FORMAT[data_type].struct_id}"
)
else:
structure = f">{DEFAULT_STRUCT_FORMAT[data_type].struct_id}"
return {
**config,
CONF_STRUCTURE: structure,
CONF_SWAP: swap_type,
} |
Check the number of registers for target temp. and coerce it to a list, if valid. | def hvac_fixedsize_reglist_validator(value: Any) -> list:
"""Check the number of registers for target temp. and coerce it to a list, if valid."""
if isinstance(value, int):
value = [value] * len(HVACMode)
return list(value)
if len(value) == len(HVACMode):
_rv = True
for svalue in value:
if isinstance(svalue, int) is False:
_rv = False
break
if _rv is True:
return list(value)
raise vol.Invalid(
f"Invalid target temp register. Required type: integer, allowed 1 or list of {len(HVACMode)} registers"
) |
Convert nan string to number (can be hex string or int). | def nan_validator(value: Any) -> int:
"""Convert nan string to number (can be hex string or int)."""
if isinstance(value, int):
return value
try:
return int(value)
except (TypeError, ValueError):
pass
try:
return int(value, 16)
except (TypeError, ValueError) as err:
raise vol.Invalid(f"invalid number {value}") from err |
Control modbus climate fan mode values for duplicates. | def duplicate_fan_mode_validator(config: dict[str, Any]) -> dict:
"""Control modbus climate fan mode values for duplicates."""
fan_modes: set[int] = set()
errors = []
for key, value in config[CONF_FAN_MODE_VALUES].items():
if value in fan_modes:
warn = f"Modbus fan mode {key} has a duplicate value {value}, not loaded, values must be unique!"
_LOGGER.warning(warn)
errors.append(key)
else:
fan_modes.add(value)
for key in reversed(errors):
del config[CONF_FAN_MODE_VALUES][key]
return config |
Control modbus climate swing mode values for duplicates. | def duplicate_swing_mode_validator(config: dict[str, Any]) -> dict:
"""Control modbus climate swing mode values for duplicates."""
swing_modes: set[int] = set()
errors = []
for key, value in config[CONF_SWING_MODE_VALUES].items():
if value in swing_modes:
warn = f"Modbus swing mode {key} has a duplicate value {value}, not loaded, values must be unique!"
_LOGGER.warning(warn)
errors.append(key)
else:
swing_modes.add(value)
for key in reversed(errors):
del config[CONF_SWING_MODE_VALUES][key]
return config |
Check conflicts among HVAC target temperature registers and HVAC ON/OFF, HVAC register, Fan Modes, Swing Modes. | def check_hvac_target_temp_registers(config: dict) -> dict:
"""Check conflicts among HVAC target temperature registers and HVAC ON/OFF, HVAC register, Fan Modes, Swing Modes."""
if (
CONF_HVAC_MODE_REGISTER in config
and config[CONF_HVAC_MODE_REGISTER][CONF_ADDRESS] in config[CONF_TARGET_TEMP]
):
wrn = f"{CONF_HVAC_MODE_REGISTER} overlaps CONF_TARGET_TEMP register(s). {CONF_HVAC_MODE_REGISTER} is not loaded!"
_LOGGER.warning(wrn)
del config[CONF_HVAC_MODE_REGISTER]
if (
CONF_HVAC_ONOFF_REGISTER in config
and config[CONF_HVAC_ONOFF_REGISTER] in config[CONF_TARGET_TEMP]
):
wrn = f"{CONF_HVAC_ONOFF_REGISTER} overlaps CONF_TARGET_TEMP register(s). {CONF_HVAC_ONOFF_REGISTER} is not loaded!"
_LOGGER.warning(wrn)
del config[CONF_HVAC_ONOFF_REGISTER]
if (
CONF_FAN_MODE_REGISTER in config
and config[CONF_FAN_MODE_REGISTER][CONF_ADDRESS] in config[CONF_TARGET_TEMP]
):
wrn = f"{CONF_FAN_MODE_REGISTER} overlaps CONF_TARGET_TEMP register(s). {CONF_FAN_MODE_REGISTER} is not loaded!"
_LOGGER.warning(wrn)
del config[CONF_FAN_MODE_REGISTER]
if CONF_SWING_MODE_REGISTER in config:
regToTest = (
config[CONF_SWING_MODE_REGISTER][CONF_ADDRESS]
if isinstance(config[CONF_SWING_MODE_REGISTER][CONF_ADDRESS], int)
else config[CONF_SWING_MODE_REGISTER][CONF_ADDRESS][0]
)
if regToTest in config[CONF_TARGET_TEMP]:
wrn = f"{CONF_SWING_MODE_REGISTER} overlaps CONF_TARGET_TEMP register(s). {CONF_SWING_MODE_REGISTER} is not loaded!"
_LOGGER.warning(wrn)
del config[CONF_SWING_MODE_REGISTER]
return config |
Check if a register (CONF_ADRESS) is an int or a list having only 1 register. | def register_int_list_validator(value: Any) -> Any:
"""Check if a register (CONF_ADRESS) is an int or a list having only 1 register."""
if isinstance(value, int) and value >= 0:
return value
if isinstance(value, list):
if (len(value) == 1) and isinstance(value[0], int) and value[0] >= 0:
return value
raise vol.Invalid(
f"Invalid {CONF_ADDRESS} register for fan/swing mode. Required type: positive integer, allowed 1 or list of 1 register."
) |
Validate modbus entries. | def validate_modbus(
hass: HomeAssistant,
hosts: set[str],
hub_names: set[str],
hub: dict,
hub_name_inx: int,
) -> bool:
"""Validate modbus entries."""
if CONF_RETRIES in hub:
async_create_issue(
hass,
DOMAIN,
"deprecated_retries",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
severity=IssueSeverity.WARNING,
translation_key="deprecated_retries",
translation_placeholders={
"config_key": "retries",
"integration": DOMAIN,
"url": "https://www.home-assistant.io/integrations/modbus",
},
)
_LOGGER.warning(
"`retries`: is deprecated and will be removed in version 2024.7"
)
else:
hub[CONF_RETRIES] = 3
host: str = (
hub[CONF_PORT]
if hub[CONF_TYPE] == SERIAL
else f"{hub[CONF_HOST]}_{hub[CONF_PORT]}"
)
if CONF_NAME not in hub:
hub[CONF_NAME] = (
DEFAULT_HUB if not hub_name_inx else f"{DEFAULT_HUB}_{hub_name_inx}"
)
hub_name_inx += 1
modbus_create_issue(
hass,
"missing_modbus_name",
[
"name",
host,
hub[CONF_NAME],
],
f"Modbus host/port {host} is missing name, added {hub[CONF_NAME]}!",
)
name = hub[CONF_NAME]
if host in hosts or name in hub_names:
modbus_create_issue(
hass,
"duplicate_modbus_entry",
[
host,
hub[CONF_NAME],
"",
],
f"Modbus {name} host/port {host} is duplicate, not loaded!",
)
return False
hosts.add(host)
hub_names.add(name)
return True |
Validate entity. | def validate_entity(
hass: HomeAssistant,
hub_name: str,
component: str,
entity: dict,
minimum_scan_interval: int,
ent_names: set[str],
ent_addr: set[str],
) -> bool:
"""Validate entity."""
if CONF_LAZY_ERROR in entity:
async_create_issue(
hass,
DOMAIN,
"removed_lazy_error_count",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
severity=IssueSeverity.WARNING,
translation_key="removed_lazy_error_count",
translation_placeholders={
"config_key": "lazy_error_count",
"integration": DOMAIN,
"url": "https://www.home-assistant.io/integrations/modbus",
},
)
_LOGGER.warning(
"`lazy_error_count`: is deprecated and will be removed in version 2024.7"
)
name = f"{component}.{entity[CONF_NAME]}"
addr = f"{hub_name}{entity[CONF_ADDRESS]}"
scan_interval = entity.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
if 0 < scan_interval < 5:
err = (
f"{hub_name} {name} scan_interval is lower than 5 seconds, "
"which may cause Home Assistant stability issues"
)
_LOGGER.warning(err)
entity[CONF_SCAN_INTERVAL] = scan_interval
minimum_scan_interval = min(scan_interval, minimum_scan_interval)
for conf_type in (
CONF_INPUT_TYPE,
CONF_WRITE_TYPE,
CONF_COMMAND_ON,
CONF_COMMAND_OFF,
):
if conf_type in entity:
addr += f"_{entity[conf_type]}"
inx = entity.get(CONF_SLAVE) or entity.get(CONF_DEVICE_ADDRESS, 0)
addr += f"_{inx}"
loc_addr: set[str] = {addr}
if CONF_TARGET_TEMP in entity:
loc_addr.add(f"{hub_name}{entity[CONF_TARGET_TEMP]}_{inx}")
if CONF_HVAC_MODE_REGISTER in entity:
loc_addr.add(f"{hub_name}{entity[CONF_HVAC_MODE_REGISTER][CONF_ADDRESS]}_{inx}")
if CONF_FAN_MODE_REGISTER in entity:
loc_addr.add(f"{hub_name}{entity[CONF_FAN_MODE_REGISTER][CONF_ADDRESS]}_{inx}")
if CONF_SWING_MODE_REGISTER in entity:
loc_addr.add(
f"{hub_name}{entity[CONF_SWING_MODE_REGISTER][CONF_ADDRESS]
if isinstance(entity[CONF_SWING_MODE_REGISTER][CONF_ADDRESS],int)
else entity[CONF_SWING_MODE_REGISTER][CONF_ADDRESS][0]}_{inx}"
)
dup_addrs = ent_addr.intersection(loc_addr)
if len(dup_addrs) > 0:
for addr in dup_addrs:
modbus_create_issue(
hass,
"duplicate_entity_entry",
[
f"{hub_name}/{name}",
addr,
"",
],
f"Modbus {hub_name}/{name} address {addr} is duplicate, second entry not loaded!",
)
return False
if name in ent_names:
modbus_create_issue(
hass,
"duplicate_entity_name",
[
f"{hub_name}/{name}",
"",
"",
],
f"Modbus {hub_name}/{name} is duplicate, second entry not loaded!",
)
return False
ent_names.add(name)
ent_addr.update(loc_addr)
return True |
Do final config check. | def check_config(hass: HomeAssistant, config: dict) -> dict:
"""Do final config check."""
hosts: set[str] = set()
hub_names: set[str] = set()
hub_name_inx = 0
minimum_scan_interval = 0
ent_names: set[str] = set()
ent_addr: set[str] = set()
hub_inx = 0
while hub_inx < len(config):
hub = config[hub_inx]
if not validate_modbus(hass, hosts, hub_names, hub, hub_name_inx):
del config[hub_inx]
continue
minimum_scan_interval = 9999
no_entities = True
for component, conf_key in PLATFORMS:
if conf_key not in hub:
continue
no_entities = False
entity_inx = 0
entities = hub[conf_key]
while entity_inx < len(entities):
if not validate_entity(
hass,
hub[CONF_NAME],
component,
entities[entity_inx],
minimum_scan_interval,
ent_names,
ent_addr,
):
del entities[entity_inx]
else:
entity_inx += 1
if no_entities:
modbus_create_issue(
hass,
"no_entities",
[
hub[CONF_NAME],
"",
"",
],
f"Modbus {hub[CONF_NAME]} contain no entities, causing instability, entry not loaded",
)
del config[hub_inx]
continue
if hub[CONF_TIMEOUT] >= minimum_scan_interval:
hub[CONF_TIMEOUT] = minimum_scan_interval - 1
_LOGGER.warning(
"Modbus %s timeout is adjusted(%d) due to scan_interval",
hub[CONF_NAME],
hub[CONF_TIMEOUT],
)
hub_inx += 1
return config |
Return modbus hub with name. | def get_hub(hass: HomeAssistant, name: str) -> ModbusHub:
"""Return modbus hub with name."""
return cast(ModbusHub, hass.data[DOMAIN][name]) |
Generate unique id from usb attributes. | def _generate_unique_id(port: ListPortInfo) -> str:
"""Generate unique id from usb attributes."""
return f"{port.vid}:{port.pid}_{port.serial_number}_{port.manufacturer}_{port.description}" |
Decorate Modern Forms calls to handle Modern Forms exceptions.
A decorator that wraps the passed in function, catches Modern Forms errors,
and handles the availability of the device in the data coordinator. | def modernforms_exception_handler(
func: Callable[Concatenate[_ModernFormsDeviceEntityT, _P], Any],
) -> Callable[Concatenate[_ModernFormsDeviceEntityT, _P], Coroutine[Any, Any, None]]:
"""Decorate Modern Forms calls to handle Modern Forms exceptions.
A decorator that wraps the passed in function, catches Modern Forms errors,
and handles the availability of the device in the data coordinator.
"""
async def handler(
self: _ModernFormsDeviceEntityT, *args: _P.args, **kwargs: _P.kwargs
) -> None:
try:
await func(self, *args, **kwargs)
self.coordinator.async_update_listeners()
except ModernFormsConnectionError as error:
_LOGGER.error("Error communicating with API: %s", error)
self.coordinator.last_update_success = False
self.coordinator.async_update_listeners()
except ModernFormsError as error:
_LOGGER.error("Invalid response from API: %s", error)
return handler |
Convert a device key to an entity key. | def device_key_to_bluetooth_entity_key(
device_key: DeviceKey,
) -> PassiveBluetoothEntityKey:
"""Convert a device key to an entity key."""
return PassiveBluetoothEntityKey(device_key.key, device_key.device_id) |
Convert a sensor update to a bluetooth data update. | def sensor_update_to_bluetooth_data_update(
sensor_update: SensorUpdate,
) -> PassiveBluetoothDataUpdate:
"""Convert a sensor update to a bluetooth data update."""
return PassiveBluetoothDataUpdate(
devices={
device_id: sensor_device_info_to_hass_device_info(device_info)
for device_id, device_info in sensor_update.devices.items()
},
entity_descriptions={
device_key_to_bluetooth_entity_key(device_key): SENSOR_DESCRIPTIONS[
device_key.key
]
for device_key in sensor_update.entity_descriptions
if device_key.key in SENSOR_DESCRIPTIONS
},
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()
},
) |
Validate the provided MAC address. | def is_valid_mac(data: str) -> bool:
"""Validate the provided MAC address."""
mac_regex = r"^[0-9A-Fa-f]{4}$"
return bool(re.match(mac_regex, data)) |
Get the MAC address from the bluetooth local name. | def get_mac_from_local_name(data: str) -> str | None:
"""Get the MAC address from the bluetooth local name."""
mac_regex = r"^MOTION_([0-9A-Fa-f]{4})$"
match = re.search(mac_regex, data)
return str(match.group(1)) if match else None |
Create a MotionEyeClient. | def create_motioneye_client(
*args: Any,
**kwargs: Any,
) -> MotionEyeClient:
"""Create a MotionEyeClient."""
return MotionEyeClient(*args, **kwargs) |
Get the identifiers for a motionEye device. | def get_motioneye_device_identifier(
config_entry_id: str, camera_id: int
) -> tuple[str, str]:
"""Get the identifiers for a motionEye device."""
return (DOMAIN, f"{config_entry_id}_{camera_id}") |
Get the identifiers for a motionEye device. | def split_motioneye_device_identifier(
identifier: tuple[str, str],
) -> tuple[str, str, int] | None:
"""Get the identifiers for a motionEye device."""
if len(identifier) != 2 or identifier[0] != DOMAIN or "_" not in identifier[1]:
return None
config_id, camera_id_str = identifier[1].split("_", 1)
try:
camera_id = int(camera_id_str)
except ValueError:
return None
return (DOMAIN, config_id, camera_id) |
Get the unique_id for a motionEye entity. | def get_motioneye_entity_unique_id(
config_entry_id: str, camera_id: int, entity_type: str
) -> str:
"""Get the unique_id for a motionEye entity."""
return f"{config_entry_id}_{camera_id}_{entity_type}" |
Get an individual camera dict from a multiple cameras data response. | def get_camera_from_cameras(
camera_id: int, data: dict[str, Any] | None
) -> dict[str, Any] | None:
"""Get an individual camera dict from a multiple cameras data response."""
for camera in data.get(KEY_CAMERAS, []) if data else []:
if camera.get(KEY_ID) == camera_id:
val: dict[str, Any] = camera
return val
return None |
Determine if a camera dict is acceptable. | def is_acceptable_camera(camera: dict[str, Any] | None) -> bool:
"""Determine if a camera dict is acceptable."""
return bool(camera and KEY_ID in camera and KEY_NAME in camera) |
Listen for new cameras. | def listen_for_new_cameras(
hass: HomeAssistant,
entry: ConfigEntry,
add_func: Callable,
) -> None:
"""Listen for new cameras."""
entry.async_on_unload(
async_dispatcher_connect(
hass,
SIGNAL_CAMERA_ADD.format(entry.entry_id),
add_func,
)
) |
Generate the full local URL for a webhook_id. | def async_generate_motioneye_webhook(
hass: HomeAssistant, webhook_id: str
) -> str | None:
"""Generate the full local URL for a webhook_id."""
try:
return f"{get_url(hass, allow_cloud=False)}{async_generate_path(webhook_id)}"
except NoURLAvailableError:
_LOGGER.warning(
"Unable to get Home Assistant URL. Have you set the internal and/or "
"external URLs in Settings -> System -> Network?"
)
return None |
Add a motionEye camera to hass. | def _add_camera(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
client: MotionEyeClient,
entry: ConfigEntry,
camera_id: int,
camera: dict[str, Any],
device_identifier: tuple[str, str],
) -> None:
"""Add a motionEye camera to hass."""
def _is_recognized_web_hook(url: str) -> bool:
"""Determine whether this integration set a web hook."""
return f"{WEB_HOOK_SENTINEL_KEY}={WEB_HOOK_SENTINEL_VALUE}" in url
def _set_webhook(
url: str,
key_url: str,
key_method: str,
key_enabled: str,
camera: dict[str, Any],
) -> bool:
"""Set a web hook."""
if (
entry.options.get(
CONF_WEBHOOK_SET_OVERWRITE,
DEFAULT_WEBHOOK_SET_OVERWRITE,
)
or not camera.get(key_url)
or _is_recognized_web_hook(camera[key_url])
) and (
not camera.get(key_enabled, False)
or camera.get(key_method) != KEY_HTTP_METHOD_POST_JSON
or camera.get(key_url) != url
):
camera[key_enabled] = True
camera[key_method] = KEY_HTTP_METHOD_POST_JSON
camera[key_url] = url
return True
return False
def _build_url(
device: dr.DeviceEntry, base: str, event_type: str, keys: list[str]
) -> str:
"""Build a motionEye webhook URL."""
# This URL-surgery cannot use YARL because the output must NOT be
# url-encoded. This is because motionEye will do further string
# manipulation/substitution on this value before ultimately fetching it,
# and it cannot deal with URL-encoded input to that string manipulation.
return urljoin(
base,
"?"
+ urlencode(
{
**{k: KEY_WEB_HOOK_CONVERSION_SPECIFIERS[k] for k in sorted(keys)},
WEB_HOOK_SENTINEL_KEY: WEB_HOOK_SENTINEL_VALUE,
ATTR_EVENT_TYPE: event_type,
ATTR_DEVICE_ID: device.id,
},
safe="%{}",
),
)
device = device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={device_identifier},
manufacturer=MOTIONEYE_MANUFACTURER,
model=MOTIONEYE_MANUFACTURER,
name=camera[KEY_NAME],
)
if entry.options.get(CONF_WEBHOOK_SET, DEFAULT_WEBHOOK_SET):
url = async_generate_motioneye_webhook(hass, entry.data[CONF_WEBHOOK_ID])
if url:
set_motion_event = _set_webhook(
_build_url(
device,
url,
EVENT_MOTION_DETECTED,
EVENT_MOTION_DETECTED_KEYS,
),
KEY_WEB_HOOK_NOTIFICATIONS_URL,
KEY_WEB_HOOK_NOTIFICATIONS_HTTP_METHOD,
KEY_WEB_HOOK_NOTIFICATIONS_ENABLED,
camera,
)
set_storage_event = _set_webhook(
_build_url(
device,
url,
EVENT_FILE_STORED,
EVENT_FILE_STORED_KEYS,
),
KEY_WEB_HOOK_STORAGE_URL,
KEY_WEB_HOOK_STORAGE_HTTP_METHOD,
KEY_WEB_HOOK_STORAGE_ENABLED,
camera,
)
if set_motion_event or set_storage_event:
hass.async_create_task(client.async_set_camera(camera_id, camera))
async_dispatcher_send(
hass,
SIGNAL_CAMERA_ADD.format(entry.entry_id),
camera,
) |
Get the URL for a motionEye media item. | def get_media_url(
client: MotionEyeClient, camera_id: int, path: str, image: bool
) -> str | None:
"""Get the URL for a motionEye media item."""
with contextlib.suppress(MotionEyeClientPathError):
if image:
return client.get_image_url(camera_id, path)
return client.get_movie_url(camera_id, path)
return None |
Construct common name part of a device. | def device_name(blind):
"""Construct common name part of a device."""
if blind.device_type in DEVICE_TYPES_WIFI:
return blind.blind_type
return f"{blind.blind_type} {blind.mac[12:]}" |
Publish message to a MQTT topic. | def publish(
hass: HomeAssistant,
topic: str,
payload: PublishPayloadType,
qos: int | None = 0,
retain: bool | None = False,
encoding: str | None = DEFAULT_ENCODING,
) -> None:
"""Publish message to a MQTT topic."""
hass.create_task(async_publish(hass, topic, payload, qos, retain, encoding)) |
Subscribe to an MQTT topic. | def subscribe(
hass: HomeAssistant,
topic: str,
msg_callback: MessageCallbackType,
qos: int = DEFAULT_QOS,
encoding: str = "utf-8",
) -> Callable[[], None]:
"""Subscribe to an MQTT topic."""
async_remove = asyncio.run_coroutine_threadsafe(
async_subscribe(hass, topic, msg_callback, qos, encoding), hass.loop
).result()
def remove() -> None:
"""Remove listener convert."""
# MQTT messages tend to be high volume,
# and since they come in via a thread and need to be processed in the event loop,
# we want to avoid hass.add_job since most of the time is spent calling
# inspect to figure out how to run the callback.
hass.loop.call_soon_threadsafe(async_remove)
return remove |
Return if a topic is a simple match. | def _is_simple_match(topic: str) -> bool:
"""Return if a topic is a simple match."""
return not ("+" in topic or "#" in topic) |
Raise error if error result. | def _raise_on_error(result_code: int) -> None:
"""Raise error if error result."""
# pylint: disable-next=import-outside-toplevel
import paho.mqtt.client as mqtt
if result_code and (message := mqtt.error_string(result_code)):
raise HomeAssistantError(f"Error talking to MQTT: {message}") |
Validate that the preset mode reset payload is not one of the preset modes. | def valid_preset_mode_configuration(config: ConfigType) -> ConfigType:
"""Validate that the preset mode reset payload is not one of the preset modes."""
if PRESET_NONE in config[CONF_PRESET_MODES_LIST]:
raise vol.Invalid("preset_modes must not include preset mode 'none'")
return config |
Validate a target_humidity range configuration, throws otherwise. | def valid_humidity_range_configuration(config: ConfigType) -> ConfigType:
"""Validate a target_humidity range configuration, throws otherwise."""
if config[CONF_HUMIDITY_MIN] >= config[CONF_HUMIDITY_MAX]:
raise vol.Invalid("target_humidity_max must be > target_humidity_min")
if config[CONF_HUMIDITY_MAX] > 100:
raise vol.Invalid("max_humidity must be <= 100")
return config |
Validate humidity state.
Ensure that if CONF_HUMIDITY_STATE_TOPIC is set then
CONF_HUMIDITY_COMMAND_TOPIC is also set. | def valid_humidity_state_configuration(config: ConfigType) -> ConfigType:
"""Validate humidity state.
Ensure that if CONF_HUMIDITY_STATE_TOPIC is set then
CONF_HUMIDITY_COMMAND_TOPIC is also set.
"""
if (
CONF_HUMIDITY_STATE_TOPIC in config
and CONF_HUMIDITY_COMMAND_TOPIC not in config
):
raise vol.Invalid(
f"{CONF_HUMIDITY_STATE_TOPIC} cannot be used without"
f" {CONF_HUMIDITY_COMMAND_TOPIC}"
)
return config |
Update the password if the entry has been updated.
As we want to avoid reflecting the stored password in the UI,
we replace the suggested value in the UI with a sentitel,
and we change it back here if it was changed. | def update_password_from_user_input(
entry_password: str | None, user_input: dict[str, Any]
) -> dict[str, Any]:
"""Update the password if the entry has been updated.
As we want to avoid reflecting the stored password in the UI,
we replace the suggested value in the UI with a sentitel,
and we change it back here if it was changed.
"""
substituted_used_data = dict(user_input)
# Take out the password submitted
user_password: str | None = substituted_used_data.pop(CONF_PASSWORD, None)
# Only add the password if it has changed.
# If the sentinel password is submitted, we replace that with our current
# password from the config entry data.
password_changed = user_password is not None and user_password != PWD_NOT_CHANGED
password = user_password if password_changed else entry_password
if password is not None:
substituted_used_data[CONF_PASSWORD] = password
return substituted_used_data |
Test if we can connect to an MQTT broker. | def try_connection(
user_input: dict[str, Any],
) -> bool:
"""Test if we can connect to an MQTT broker."""
# We don't import on the top because some integrations
# should be able to optionally rely on MQTT.
import paho.mqtt.client as mqtt # pylint: disable=import-outside-toplevel
client = MqttClientSetup(user_input).client
result: queue.Queue[bool] = queue.Queue(maxsize=1)
def on_connect(
client_: mqtt.Client,
userdata: None,
flags: dict[str, Any],
result_code: int,
properties: mqtt.Properties | None = None,
) -> None:
"""Handle connection result."""
result.put(result_code == mqtt.CONNACK_ACCEPTED)
client.on_connect = on_connect
client.connect_async(user_input[CONF_BROKER], user_input[CONF_PORT])
client.loop_start()
try:
return result.get(timeout=MQTT_TIMEOUT)
except queue.Empty:
return False
finally:
client.disconnect()
client.loop_stop() |
Check the MQTT certificates. | def check_certicate_chain() -> str | None:
"""Check the MQTT certificates."""
if client_certificate := get_file_path(CONF_CLIENT_CERT):
try:
with open(client_certificate, "rb") as client_certificate_file:
load_pem_x509_certificate(client_certificate_file.read())
except ValueError:
return "bad_client_cert"
# Check we can serialize the private key file
if private_key := get_file_path(CONF_CLIENT_KEY):
try:
with open(private_key, "rb") as client_key_file:
load_pem_private_key(client_key_file.read(), password=None)
except (TypeError, ValueError):
return "bad_client_key"
# Check the certificate chain
context = SSLContext(PROTOCOL_TLS_CLIENT)
if client_certificate and private_key:
try:
context.load_cert_chain(client_certificate, private_key)
except SSLError:
return "bad_client_cert_key"
# try to load the custom CA file
if (ca_cert := get_file_path(CONF_CERTIFICATE)) is None:
return None
try:
context.load_verify_locations(ca_cert)
except SSLError:
return "bad_certificate"
return None |
Validate options.
If set position topic is set then get position topic is set as well. | def validate_options(config: ConfigType) -> ConfigType:
"""Validate options.
If set position topic is set then get position topic is set as well.
"""
if CONF_SET_POSITION_TOPIC in config and CONF_GET_POSITION_TOPIC not in config:
raise vol.Invalid(
f"'{CONF_SET_POSITION_TOPIC}' must be set together with"
f" '{CONF_GET_POSITION_TOPIC}'."
)
# if templates are set make sure the topic for the template is also set
if CONF_VALUE_TEMPLATE in config and CONF_STATE_TOPIC not in config:
raise vol.Invalid(
f"'{CONF_VALUE_TEMPLATE}' must be set together with '{CONF_STATE_TOPIC}'."
)
if CONF_GET_POSITION_TEMPLATE in config and CONF_GET_POSITION_TOPIC not in config:
raise vol.Invalid(
f"'{CONF_GET_POSITION_TEMPLATE}' must be set together with"
f" '{CONF_GET_POSITION_TOPIC}'."
)
if CONF_SET_POSITION_TEMPLATE in config and CONF_SET_POSITION_TOPIC not in config:
raise vol.Invalid(
f"'{CONF_SET_POSITION_TEMPLATE}' must be set together with"
f" '{CONF_SET_POSITION_TOPIC}'."
)
if CONF_TILT_COMMAND_TEMPLATE in config and CONF_TILT_COMMAND_TOPIC not in config:
raise vol.Invalid(
f"'{CONF_TILT_COMMAND_TEMPLATE}' must be set together with"
f" '{CONF_TILT_COMMAND_TOPIC}'."
)
if CONF_TILT_STATUS_TEMPLATE in config and CONF_TILT_STATUS_TOPIC not in config:
raise vol.Invalid(
f"'{CONF_TILT_STATUS_TEMPLATE}' must be set together with"
f" '{CONF_TILT_STATUS_TOPIC}'."
)
return config |
Wrap an MQTT message callback to support message logging. | def log_messages(
hass: HomeAssistant, entity_id: str
) -> Callable[[MessageCallbackType], MessageCallbackType]:
"""Wrap an MQTT message callback to support message logging."""
debug_info_entities = get_mqtt_data(hass).debug_info_entities
def _log_message(msg: Any) -> None:
"""Log message."""
messages = debug_info_entities[entity_id]["subscriptions"][
msg.subscribed_topic
]["messages"]
if msg not in messages:
messages.append(msg)
def _decorator(msg_callback: MessageCallbackType) -> MessageCallbackType:
@wraps(msg_callback)
def wrapper(msg: Any) -> None:
"""Log message."""
_log_message(msg)
msg_callback(msg)
setattr(wrapper, "__entity_id", entity_id)
return wrapper
return _decorator |
Log an outgoing MQTT message. | def log_message(
hass: HomeAssistant,
entity_id: str,
topic: str,
payload: PublishPayloadType,
qos: int,
retain: bool,
) -> None:
"""Log an outgoing MQTT message."""
entity_info = get_mqtt_data(hass).debug_info_entities.setdefault(
entity_id, {"subscriptions": {}, "discovery_data": {}, "transmitted": {}}
)
if topic not in entity_info["transmitted"]:
entity_info["transmitted"][topic] = {
"messages": deque([], STORED_MESSAGES),
}
msg = TimestampedPublishMessage(
topic, payload, qos, retain, timestamp=time.monotonic()
)
entity_info["transmitted"][topic]["messages"].append(msg) |
Prepare debug data for subscription. | def add_subscription(
hass: HomeAssistant,
message_callback: MessageCallbackType,
subscription: str,
) -> None:
"""Prepare debug data for subscription."""
if entity_id := getattr(message_callback, "__entity_id", None):
entity_info = get_mqtt_data(hass).debug_info_entities.setdefault(
entity_id, {"subscriptions": {}, "discovery_data": {}, "transmitted": {}}
)
if subscription not in entity_info["subscriptions"]:
entity_info["subscriptions"][subscription] = {
"count": 0,
"messages": deque([], STORED_MESSAGES),
}
entity_info["subscriptions"][subscription]["count"] += 1 |
Remove debug data for subscription if it exists. | def remove_subscription(
hass: HomeAssistant,
message_callback: MessageCallbackType,
subscription: str,
) -> None:
"""Remove debug data for subscription if it exists."""
if (entity_id := getattr(message_callback, "__entity_id", None)) and entity_id in (
debug_info_entities := get_mqtt_data(hass).debug_info_entities
):
debug_info_entities[entity_id]["subscriptions"][subscription]["count"] -= 1
if not debug_info_entities[entity_id]["subscriptions"][subscription]["count"]:
debug_info_entities[entity_id]["subscriptions"].pop(subscription) |
Add discovery data. | def add_entity_discovery_data(
hass: HomeAssistant, discovery_data: DiscoveryInfoType, entity_id: str
) -> None:
"""Add discovery data."""
entity_info = get_mqtt_data(hass).debug_info_entities.setdefault(
entity_id, {"subscriptions": {}, "discovery_data": {}, "transmitted": {}}
)
entity_info["discovery_data"] = discovery_data |
Update discovery data. | def update_entity_discovery_data(
hass: HomeAssistant, discovery_payload: DiscoveryInfoType, entity_id: str
) -> None:
"""Update discovery data."""
discovery_data = get_mqtt_data(hass).debug_info_entities[entity_id][
"discovery_data"
]
if TYPE_CHECKING:
assert discovery_data is not None
discovery_data[ATTR_DISCOVERY_PAYLOAD] = discovery_payload |
Remove discovery data. | def remove_entity_data(hass: HomeAssistant, entity_id: str) -> None:
"""Remove discovery data."""
if entity_id in (debug_info_entities := get_mqtt_data(hass).debug_info_entities):
debug_info_entities.pop(entity_id) |
Add discovery data. | def add_trigger_discovery_data(
hass: HomeAssistant,
discovery_hash: tuple[str, str],
discovery_data: DiscoveryInfoType,
device_id: str,
) -> None:
"""Add discovery data."""
get_mqtt_data(hass).debug_info_triggers[discovery_hash] = {
"device_id": device_id,
"discovery_data": discovery_data,
} |
Update discovery data. | def update_trigger_discovery_data(
hass: HomeAssistant,
discovery_hash: tuple[str, str],
discovery_payload: DiscoveryInfoType,
) -> None:
"""Update discovery data."""
get_mqtt_data(hass).debug_info_triggers[discovery_hash]["discovery_data"][
ATTR_DISCOVERY_PAYLOAD
] = discovery_payload |
Remove discovery data. | def remove_trigger_discovery_data(
hass: HomeAssistant, discovery_hash: tuple[str, str]
) -> None:
"""Remove discovery data."""
get_mqtt_data(hass).debug_info_triggers.pop(discovery_hash) |
Get debug info for all entities and triggers. | def info_for_config_entry(hass: HomeAssistant) -> dict[str, list[Any]]:
"""Get debug info for all entities and triggers."""
mqtt_data = get_mqtt_data(hass)
mqtt_info: dict[str, list[Any]] = {"entities": [], "triggers": []}
mqtt_info["entities"].extend(
_info_for_entity(hass, entity_id) for entity_id in mqtt_data.debug_info_entities
)
mqtt_info["triggers"].extend(
_info_for_trigger(hass, trigger_key)
for trigger_key in mqtt_data.debug_info_triggers
)
return mqtt_info |
Get debug info for a device. | def info_for_device(hass: HomeAssistant, device_id: str) -> dict[str, list[Any]]:
"""Get debug info for a device."""
mqtt_data = get_mqtt_data(hass)
mqtt_info: dict[str, list[Any]] = {"entities": [], "triggers": []}
entity_registry = er.async_get(hass)
entries = er.async_entries_for_device(
entity_registry, device_id, include_disabled_entities=True
)
mqtt_info["entities"].extend(
_info_for_entity(hass, entry.entity_id)
for entry in entries
if entry.entity_id in mqtt_data.debug_info_entities
)
mqtt_info["triggers"].extend(
_info_for_trigger(hass, trigger_key)
for trigger_key, trigger in mqtt_data.debug_info_triggers.items()
if trigger["device_id"] == device_id
)
return mqtt_info |
Check if there is a state topic or json_attributes_topic. | def valid_config(config: ConfigType) -> ConfigType:
"""Check if there is a state topic or json_attributes_topic."""
if CONF_STATE_TOPIC not in config and CONF_JSON_ATTRS_TOPIC not in config:
raise vol.Invalid(
f"Invalid device tracker config, missing {CONF_STATE_TOPIC} or {CONF_JSON_ATTRS_TOPIC}, got: {config}"
)
return config |
Return diagnostics for a config entry. | def _async_get_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
device: DeviceEntry | None = None,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
mqtt_instance = get_mqtt_data(hass).client
if TYPE_CHECKING:
assert mqtt_instance is not None
redacted_config = async_redact_data(mqtt_instance.conf, REDACT_CONFIG)
data = {
"connected": is_connected(hass),
"mqtt_config": redacted_config,
}
if device:
data["device"] = _async_device_as_dict(hass, device)
data["mqtt_debug_info"] = debug_info.info_for_device(hass, device.id)
else:
device_registry = dr.async_get(hass)
data.update(
devices=[
_async_device_as_dict(hass, device)
for device in dr.async_entries_for_config_entry(
device_registry, entry.entry_id
)
],
mqtt_debug_info=debug_info.info_for_config_entry(hass),
)
return data |
Represent an MQTT device as a dictionary. | def _async_device_as_dict(hass: HomeAssistant, device: DeviceEntry) -> dict[str, Any]:
"""Represent an MQTT device as a dictionary."""
# Gather information how this MQTT device is represented in Home Assistant
entity_registry = er.async_get(hass)
data: dict[str, Any] = {
"id": device.id,
"name": device.name,
"name_by_user": device.name_by_user,
"disabled": device.disabled,
"disabled_by": device.disabled_by,
"entities": [],
}
entities = er.async_entries_for_device(
entity_registry,
device_id=device.id,
include_disabled_entities=True,
)
def _state_dict(entity_entry: er.RegistryEntry) -> dict[str, Any] | None:
state = hass.states.get(entity_entry.entity_id)
if not state:
return None
state_dict = dict(state.as_dict())
# The context doesn't provide useful information in this case.
state_dict.pop("context", None)
entity_domain = split_entity_id(state.entity_id)[0]
# Retract some sensitive state attributes
if entity_domain == device_tracker.DOMAIN:
state_dict["attributes"] = async_redact_data(
state_dict["attributes"], REDACT_STATE_DEVICE_TRACKER
)
return state_dict
data["entities"].extend(
{
"device_class": entity_entry.device_class,
"disabled_by": entity_entry.disabled_by,
"disabled": entity_entry.disabled,
"entity_category": entity_entry.entity_category,
"entity_id": entity_entry.entity_id,
"icon": entity_entry.icon,
"original_device_class": entity_entry.original_device_class,
"original_icon": entity_entry.original_icon,
"state": state_dict,
"unit_of_measurement": entity_entry.unit_of_measurement,
}
for entity_entry in entities
if (state_dict := _state_dict(entity_entry)) is not None
)
return data |
Clear entry from already discovered list. | def clear_discovery_hash(hass: HomeAssistant, discovery_hash: tuple[str, str]) -> None:
"""Clear entry from already discovered list."""
get_mqtt_data(hass).discovery_already_discovered.remove(discovery_hash) |
Add entry to already discovered list. | def set_discovery_hash(hass: HomeAssistant, discovery_hash: tuple[str, str]) -> None:
"""Add entry to already discovered list."""
get_mqtt_data(hass).discovery_already_discovered.add(discovery_hash) |
Log information about the discovery and origin. | def async_log_discovery_origin_info(
message: str, discovery_payload: MQTTDiscoveryPayload
) -> None:
"""Log information about the discovery and origin."""
if CONF_ORIGIN not in discovery_payload:
_LOGGER.info(message)
return
origin_info: MqttOriginInfo = discovery_payload[CONF_ORIGIN]
sw_version_log = ""
if sw_version := origin_info.get("sw_version"):
sw_version_log = f", version: {sw_version}"
support_url_log = ""
if support_url := origin_info.get("support_url"):
support_url_log = f", support URL: {support_url}"
_LOGGER.info(
"%s from external application %s%s%s",
message,
origin_info["name"],
sw_version_log,
support_url_log,
) |
Validate that the fan speed_range configuration is valid, throws if it isn't. | def valid_speed_range_configuration(config: ConfigType) -> ConfigType:
"""Validate that the fan speed_range configuration is valid, throws if it isn't."""
if config[CONF_SPEED_RANGE_MIN] == 0:
raise vol.Invalid("speed_range_min must be > 0")
if config[CONF_SPEED_RANGE_MIN] >= config[CONF_SPEED_RANGE_MAX]:
raise vol.Invalid("speed_range_max must be > speed_range_min")
return config |
Validate that the preset mode reset payload is not one of the preset modes. | def valid_preset_mode_configuration(config: ConfigType) -> ConfigType:
"""Validate that the preset mode reset payload is not one of the preset modes."""
if config[CONF_PAYLOAD_RESET_PRESET_MODE] in config[CONF_PRESET_MODES_LIST]:
raise vol.Invalid("preset_modes must not contain payload_reset_preset_mode")
return config |
Validate that the mode reset payload is not one of the available modes. | def valid_mode_configuration(config: ConfigType) -> ConfigType:
"""Validate that the mode reset payload is not one of the available modes."""
if config[CONF_PAYLOAD_RESET_MODE] in config[CONF_AVAILABLE_MODES_LIST]:
raise vol.Invalid("modes must not contain payload_reset_mode")
return config |
Validate humidity range.
Ensures that the target_humidity range configuration is valid,
throws if it isn't. | def valid_humidity_range_configuration(config: ConfigType) -> ConfigType:
"""Validate humidity range.
Ensures that the target_humidity range configuration is valid,
throws if it isn't.
"""
if config[CONF_TARGET_HUMIDITY_MIN] >= config[CONF_TARGET_HUMIDITY_MAX]:
raise vol.Invalid("target_humidity_max must be > target_humidity_min")
if config[CONF_TARGET_HUMIDITY_MAX] > 100:
raise vol.Invalid("max_humidity must be <= 100")
return config |
Ensure at least one subscribe topic is configured. | def validate_topic_required(config: ConfigType) -> ConfigType:
"""Ensure at least one subscribe topic is configured."""
if CONF_IMAGE_TOPIC not in config and CONF_URL_TOPIC not in config:
raise vol.Invalid("Expected one of [`image_topic`, `url_topic`], got none")
if CONF_CONTENT_TYPE in config and CONF_URL_TOPIC in config:
raise vol.Invalid(
"Option `content_type` can not be used together with `url_topic`"
)
return config |
Validate that a device info entry has at least one identifying value. | def validate_device_has_at_least_one_identifier(value: ConfigType) -> ConfigType:
"""Validate that a device info entry has at least one identifying value."""
if value.get(CONF_IDENTIFIERS) or value.get(CONF_CONNECTIONS):
return value
raise vol.Invalid(
"Device must have at least one identifying value in "
"'identifiers' and/or 'connections'"
) |
Help handling schema errors on MQTT discovery messages. | def async_handle_schema_error(
discovery_payload: MQTTDiscoveryPayload, err: vol.MultipleInvalid
) -> None:
"""Help handling schema errors on MQTT discovery messages."""
discovery_topic: str = discovery_payload.discovery_data[ATTR_DISCOVERY_TOPIC]
_LOGGER.error(
"Error '%s' when processing MQTT discovery message topic: '%s', message: '%s'",
err,
discovery_topic,
discovery_payload,
) |
Set entity_id from object_id if defined in config. | def init_entity_id_from_config(
hass: HomeAssistant, entity: Entity, config: ConfigType, entity_id_format: str
) -> None:
"""Set entity_id from object_id if defined in config."""
if CONF_OBJECT_ID in config:
entity.entity_id = async_generate_entity_id(
entity_id_format, config[CONF_OBJECT_ID], None, hass
) |
Wrap an MQTT message callback to track state attribute changes. | def write_state_on_attr_change(
entity: Entity, attributes: set[str]
) -> Callable[[MessageCallbackType], MessageCallbackType]:
"""Wrap an MQTT message callback to track state attribute changes."""
def _attrs_have_changed(tracked_attrs: dict[str, Any]) -> bool:
"""Return True if attributes on entity changed or if update is forced."""
if not (write_state := (getattr(entity, "_attr_force_update", False))):
for attribute, last_value in tracked_attrs.items():
if getattr(entity, attribute, UNDEFINED) != last_value:
write_state = True
break
return write_state
def _decorator(msg_callback: MessageCallbackType) -> MessageCallbackType:
@wraps(msg_callback)
def wrapper(msg: ReceiveMessage) -> None:
"""Track attributes for write state requests."""
tracked_attrs: dict[str, Any] = {
attribute: getattr(entity, attribute, UNDEFINED)
for attribute in attributes
}
try:
msg_callback(msg)
except MqttValueTemplateException as exc:
_LOGGER.warning(exc)
return
if not _attrs_have_changed(tracked_attrs):
return
mqtt_data = get_mqtt_data(entity.hass)
mqtt_data.state_write_requests.write_state_request(entity)
return wrapper
return _decorator |
Get the discovery hash from the discovery data. | def get_discovery_hash(discovery_data: DiscoveryInfoType) -> tuple[str, str]:
"""Get the discovery hash from the discovery data."""
discovery_hash: tuple[str, str] = discovery_data[ATTR_DISCOVERY_HASH]
return discovery_hash |
Acknowledge a discovery message has been handled. | def send_discovery_done(hass: HomeAssistant, discovery_data: DiscoveryInfoType) -> None:
"""Acknowledge a discovery message has been handled."""
discovery_hash = get_discovery_hash(discovery_data)
async_dispatcher_send(hass, MQTT_DISCOVERY_DONE.format(discovery_hash), None) |
Stop discovery updates of being sent. | def stop_discovery_updates(
hass: HomeAssistant,
discovery_data: DiscoveryInfoType,
remove_discovery_updated: Callable[[], None] | None = None,
) -> None:
"""Stop discovery updates of being sent."""
if remove_discovery_updated:
remove_discovery_updated()
remove_discovery_updated = None
discovery_hash = get_discovery_hash(discovery_data)
clear_discovery_hash(hass, discovery_hash) |
Return a device description for device registry. | def device_info_from_specifications(
specifications: dict[str, Any] | None,
) -> DeviceInfo | None:
"""Return a device description for device registry."""
if not specifications:
return None
info = DeviceInfo(
identifiers={(DOMAIN, id_) for id_ in specifications[CONF_IDENTIFIERS]},
connections={
(conn_[0], conn_[1]) for conn_ in specifications[CONF_CONNECTIONS]
},
)
if CONF_MANUFACTURER in specifications:
info[ATTR_MANUFACTURER] = specifications[CONF_MANUFACTURER]
if CONF_MODEL in specifications:
info[ATTR_MODEL] = specifications[CONF_MODEL]
if CONF_NAME in specifications:
info[ATTR_NAME] = specifications[CONF_NAME]
if CONF_HW_VERSION in specifications:
info[ATTR_HW_VERSION] = specifications[CONF_HW_VERSION]
if CONF_SERIAL_NUMBER in specifications:
info[ATTR_SERIAL_NUMBER] = specifications[CONF_SERIAL_NUMBER]
if CONF_SW_VERSION in specifications:
info[ATTR_SW_VERSION] = specifications[CONF_SW_VERSION]
if CONF_VIA_DEVICE in specifications:
info[ATTR_VIA_DEVICE] = (DOMAIN, specifications[CONF_VIA_DEVICE])
if CONF_SUGGESTED_AREA in specifications:
info[ATTR_SUGGESTED_AREA] = specifications[CONF_SUGGESTED_AREA]
if CONF_CONFIGURATION_URL in specifications:
info[ATTR_CONFIGURATION_URL] = specifications[CONF_CONFIGURATION_URL]
return info |
Update device registry. | def update_device(
hass: HomeAssistant,
config_entry: ConfigEntry,
config: ConfigType,
) -> str | None:
"""Update device registry."""
if CONF_DEVICE not in config:
return None
device: DeviceEntry | None = None
device_registry = dr.async_get(hass)
config_entry_id = config_entry.entry_id
device_info = device_info_from_specifications(config[CONF_DEVICE])
if config_entry_id is not None and device_info is not None:
update_device_info = cast(dict[str, Any], device_info)
update_device_info["config_entry_id"] = config_entry_id
device = device_registry.async_get_or_create(**update_device_info)
return device.id if device else None |
Check if the passed event indicates MQTT was removed from a device. | def async_removed_from_device(
hass: HomeAssistant,
event: Event[EventDeviceRegistryUpdatedData],
mqtt_device_id: str,
config_entry_id: str,
) -> bool:
"""Check if the passed event indicates MQTT was removed from a device."""
if event.data["action"] == "update":
if "config_entries" not in event.data["changes"]:
return False
device_registry = dr.async_get(hass)
if (
device_entry := device_registry.async_get(mqtt_device_id)
) and config_entry_id in device_entry.config_entries:
# Not removed from device
return False
return True |
Validate that the configuration is valid, throws if it isn't. | def validate_config(config: ConfigType) -> ConfigType:
"""Validate that the configuration is valid, throws if it isn't."""
if config[CONF_MIN] >= config[CONF_MAX]:
raise vol.Invalid(f"'{CONF_MAX}' must be > '{CONF_MIN}'")
return config |
Validate the sensor state class config. | def validate_sensor_state_class_config(config: ConfigType) -> ConfigType:
"""Validate the sensor state class config."""
if (
CONF_LAST_RESET_VALUE_TEMPLATE in config
and (state_class := config.get(CONF_STATE_CLASS)) != SensorStateClass.TOTAL
):
raise vol.Invalid(
f"The option `{CONF_LAST_RESET_VALUE_TEMPLATE}` cannot be used "
f"together with state class `{state_class}`"
)
return config |
Prepare (re)subscribe to a set of MQTT topics.
State is kept in sub_state and a dictionary mapping from the subscription
key to the subscription state.
After this function has been called, async_subscribe_topics must be called to
finalize any new subscriptions.
Please note that the sub state must not be shared between multiple
sets of topics. Every call to async_subscribe_topics must always
contain _all_ the topics the subscription state should manage. | def async_prepare_subscribe_topics(
hass: HomeAssistant,
new_state: dict[str, EntitySubscription] | None,
topics: dict[str, Any],
) -> dict[str, EntitySubscription]:
"""Prepare (re)subscribe to a set of MQTT topics.
State is kept in sub_state and a dictionary mapping from the subscription
key to the subscription state.
After this function has been called, async_subscribe_topics must be called to
finalize any new subscriptions.
Please note that the sub state must not be shared between multiple
sets of topics. Every call to async_subscribe_topics must always
contain _all_ the topics the subscription state should manage.
"""
current_subscriptions = new_state if new_state is not None else {}
new_state = {}
for key, value in topics.items():
# Extract the new requested subscription
requested = EntitySubscription(
topic=value.get("topic", None),
message_callback=value.get("msg_callback", None),
unsubscribe_callback=None,
qos=value.get("qos", DEFAULT_QOS),
encoding=value.get("encoding", "utf-8"),
hass=hass,
subscribe_task=None,
)
# Get the current subscription state
current = current_subscriptions.pop(key, None)
requested.resubscribe_if_necessary(hass, current)
new_state[key] = requested
# Go through all remaining subscriptions and unsubscribe them
for remaining in current_subscriptions.values():
if remaining.unsubscribe_callback is not None:
remaining.unsubscribe_callback()
# Clear debug data if it exists
debug_info.remove_subscription(
hass, remaining.message_callback, str(remaining.topic)
)
return new_state |
Unsubscribe from all MQTT topics managed by async_subscribe_topics. | def async_unsubscribe_topics(
hass: HomeAssistant, sub_state: dict[str, EntitySubscription] | None
) -> dict[str, EntitySubscription]:
"""Unsubscribe from all MQTT topics managed by async_subscribe_topics."""
return async_prepare_subscribe_topics(hass, sub_state, {}) |
Device has tag scanners. | def async_has_tags(hass: HomeAssistant, device_id: str) -> bool:
"""Device has tag scanners."""
if device_id not in (tags := get_mqtt_data(hass).tags):
return False
return tags[device_id] != {} |
Validate that the text length configuration is valid, throws if it isn't. | def valid_text_size_configuration(config: ConfigType) -> ConfigType:
"""Validate that the text length configuration is valid, throws if it isn't."""
if config[CONF_MIN] > config[CONF_MAX]:
raise vol.Invalid("text length min must be <= max")
if config[CONF_MAX] > MAX_LENGTH_STATE_STATE:
raise vol.Invalid(f"max text length must be <= {MAX_LENGTH_STATE_STATE}")
return config |
Return the platforms to be set up. | def platforms_from_config(config: list[ConfigType]) -> set[Platform | str]:
"""Return the platforms to be set up."""
return {key for platform in config for key in platform} |
Return true when the MQTT config entry is enabled. | def mqtt_config_entry_enabled(hass: HomeAssistant) -> bool | None:
"""Return true when the MQTT config entry is enabled."""
if not bool(hass.config_entries.async_entries(DOMAIN)):
return None
return not bool(hass.config_entries.async_entries(DOMAIN)[0].disabled_by) |
Validate that this is a valid topic name/filter. | def valid_topic(topic: Any) -> str:
"""Validate that this is a valid topic name/filter."""
validated_topic = cv.string(topic)
try:
raw_validated_topic = validated_topic.encode("utf-8")
except UnicodeError as err:
raise vol.Invalid("MQTT topic name/filter must be valid UTF-8 string.") from err
if not raw_validated_topic:
raise vol.Invalid("MQTT topic name/filter must not be empty.")
if len(raw_validated_topic) > 65535:
raise vol.Invalid(
"MQTT topic name/filter must not be longer than 65535 encoded bytes."
)
if "\0" in validated_topic:
raise vol.Invalid("MQTT topic name/filter must not contain null character.")
if any(char <= "\u001f" for char in validated_topic):
raise vol.Invalid("MQTT topic name/filter must not contain control characters.")
if any("\u007f" <= char <= "\u009f" for char in validated_topic):
raise vol.Invalid("MQTT topic name/filter must not contain control characters.")
if any("\ufdd0" <= char <= "\ufdef" for char in validated_topic):
raise vol.Invalid("MQTT topic name/filter must not contain non-characters.")
if any((ord(char) & 0xFFFF) in (0xFFFE, 0xFFFF) for char in validated_topic):
raise vol.Invalid("MQTT topic name/filter must not contain noncharacters.")
return validated_topic |
Validate that we can subscribe using this MQTT topic. | def valid_subscribe_topic(topic: Any) -> str:
"""Validate that we can subscribe using this MQTT topic."""
validated_topic = valid_topic(topic)
for i in (i for i, c in enumerate(validated_topic) if c == "+"):
if (i > 0 and validated_topic[i - 1] != "/") or (
i < len(validated_topic) - 1 and validated_topic[i + 1] != "/"
):
raise vol.Invalid(
"Single-level wildcard must occupy an entire level of the filter"
)
index = validated_topic.find("#")
if index != -1:
if index != len(validated_topic) - 1:
# If there are multiple wildcards, this will also trigger
raise vol.Invalid(
"Multi-level wildcard must be the last character in the topic filter."
)
if len(validated_topic) > 1 and validated_topic[index - 1] != "/":
raise vol.Invalid(
"Multi-level wildcard must be after a topic level separator."
)
return validated_topic |
Validate either a jinja2 template or a valid MQTT subscription topic. | def valid_subscribe_topic_template(value: Any) -> template.Template:
"""Validate either a jinja2 template or a valid MQTT subscription topic."""
tpl = cv.template(value)
if tpl.is_static:
valid_subscribe_topic(value)
return tpl |
Validate that we can publish using this MQTT topic. | def valid_publish_topic(topic: Any) -> str:
"""Validate that we can publish using this MQTT topic."""
validated_topic = valid_topic(topic)
if "+" in validated_topic or "#" in validated_topic:
raise vol.Invalid("Wildcards cannot be used in topic names")
return validated_topic |
Validate that QOS value is valid. | def valid_qos_schema(qos: Any) -> int:
"""Validate that QOS value is valid."""
validated_qos: int = _VALID_QOS_SCHEMA(qos)
return validated_qos |
Validate a birth or will configuration and required topic/payload. | def valid_birth_will(config: ConfigType) -> ConfigType:
"""Validate a birth or will configuration and required topic/payload."""
if config:
config = _MQTT_WILL_BIRTH_SCHEMA(config)
return config |
Return typed MqttData from hass.data[DATA_MQTT]. | def get_mqtt_data(hass: HomeAssistant) -> MqttData:
"""Return typed MqttData from hass.data[DATA_MQTT]."""
mqtt_data: MqttData = hass.data[DATA_MQTT]
return mqtt_data |
Get file path of a certificate file. | def get_file_path(option: str, default: str | None = None) -> str | None:
"""Get file path of a certificate file."""
temp_dir = Path(tempfile.gettempdir()) / TEMP_DIR_NAME
if not temp_dir.exists():
return default
file_path: Path = temp_dir / option
if not file_path.exists():
return default
return str(temp_dir / option) |
Convert certificate file or setting to config entry setting. | def migrate_certificate_file_to_content(file_name_or_auto: str) -> str | None:
"""Convert certificate file or setting to config entry setting."""
if file_name_or_auto == "auto":
return "auto"
try:
with open(file_name_or_auto, encoding=DEFAULT_ENCODING) as certificate_file:
return certificate_file.read()
except OSError:
return None |
Convert SUPPORT_* service bitmask to list of service strings. | def services_to_strings(
services: VacuumEntityFeature,
service_to_string: dict[VacuumEntityFeature, str],
) -> list[str]:
"""Convert SUPPORT_* service bitmask to list of service strings."""
return [
service_to_string[service]
for service in service_to_string
if service & services
] |
Validate config options and set defaults. | def _validate_and_add_defaults(config: ConfigType) -> ConfigType:
"""Validate config options and set defaults."""
if config[CONF_REPORTS_POSITION] and any(key in config for key in NO_POSITION_KEYS):
raise vol.Invalid(
"Options `payload_open`, `payload_close`, `state_open` and "
"`state_closed` are not allowed if the valve reports a position."
)
return {**DEFAULTS, **config} |
Unregister open config issues. | def _async_remove_mqtt_issues(hass: HomeAssistant, mqtt_data: MqttData) -> None:
"""Unregister open config issues."""
issue_registry = async_get_issue_registry(hass)
open_issues = [
issue_id
for (domain, issue_id), issue_entry in issue_registry.issues.items()
if domain == DOMAIN and issue_entry.translation_key == "invalid_platform_config"
]
for issue in open_issues:
async_delete_issue(hass, DOMAIN, issue) |
Get MQTT debug info for device. | def websocket_mqtt_info(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Get MQTT debug info for device."""
device_id = msg["device_id"]
mqtt_info = debug_info.info_for_device(hass, device_id)
connection.send_result(msg["id"], mqtt_info) |
Subscribe to MQTT connection changes. | def async_subscribe_connection_status(
hass: HomeAssistant, connection_status_callback: ConnectionStatusCallback
) -> Callable[[], None]:
"""Subscribe to MQTT connection changes."""
connection_status_callback_job = HassJob(connection_status_callback)
async def connected() -> None:
task = hass.async_run_hass_job(connection_status_callback_job, True)
if task:
await task
async def disconnected() -> None:
task = hass.async_run_hass_job(connection_status_callback_job, False)
if task:
await task
subscriptions = {
"connect": async_dispatcher_connect(hass, MQTT_CONNECTED, connected),
"disconnect": async_dispatcher_connect(hass, MQTT_DISCONNECTED, disconnected),
}
@callback
def unsubscribe() -> None:
subscriptions["connect"]()
subscriptions["disconnect"]()
return unsubscribe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.