sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:tests/components/tuya/test_alarm_control_panel.py | """Test Tuya Alarm Control Panel platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.alarm_control_panel import (
DOMAIN as ALARM_DOMAIN,
SERVICE_ALARM_ARM_AWAY,
SERVICE_ALARM_ARM_HOME,
SERVICE_ALARM_DISARM,
SERVICE_ALARM_TRIGGER,
AlarmControlPanelState,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.ALARM_CONTROL_PANEL])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.ALARM_CONTROL_PANEL])
@pytest.mark.parametrize(
"mock_device_code",
["mal_gyitctrjj1kefxp2"],
)
@pytest.mark.parametrize(
("service", "command"),
[
(SERVICE_ALARM_ARM_AWAY, {"code": "master_mode", "value": "arm"}),
(SERVICE_ALARM_ARM_HOME, {"code": "master_mode", "value": "home"}),
(SERVICE_ALARM_DISARM, {"code": "master_mode", "value": "disarmed"}),
(SERVICE_ALARM_TRIGGER, {"code": "master_mode", "value": "sos"}),
],
)
async def test_service(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service: str,
command: dict[str, Any],
) -> None:
"""Test service."""
entity_id = "alarm_control_panel.multifunction_alarm"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
ALARM_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(mock_device.id, [command])
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.ALARM_CONTROL_PANEL])
@pytest.mark.parametrize(
"mock_device_code",
["mal_gyitctrjj1kefxp2"],
)
@pytest.mark.parametrize(
("status_updates", "expected_state"),
[
(
{"master_mode": "disarmed"},
AlarmControlPanelState.DISARMED,
),
(
{"master_mode": "arm"},
AlarmControlPanelState.ARMED_AWAY,
),
(
{"master_mode": "home"},
AlarmControlPanelState.ARMED_HOME,
),
(
{"master_mode": "sos"},
AlarmControlPanelState.TRIGGERED,
),
(
{
"master_mode": "home",
"master_state": "alarm",
# "Test Sensor" in UTF-16BE
"alarm_msg": "AFQAZQBzAHQAIABTAGUAbgBzAG8Acg==",
},
AlarmControlPanelState.TRIGGERED,
),
(
{
"master_mode": "home",
"master_state": "alarm",
# "Sensor Low Battery Test Sensor" in UTF-16BE
"alarm_msg": "AFMAZQBuAHMAbwByACAATABvAHcAIABCAGEAdAB0AGUAcgB5ACAAVABlAHMAdAAgAFMAZQBuAHMAbwBy",
},
AlarmControlPanelState.ARMED_HOME,
),
],
)
async def test_state(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
status_updates: dict[str, Any],
expected_state: str,
) -> None:
"""Test state."""
entity_id = "alarm_control_panel.multifunction_alarm"
mock_device.status.update(status_updates)
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
assert state.state == expected_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_alarm_control_panel.py",
"license": "Apache License 2.0",
"lines": 127,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_binary_sensor.py | """Test Tuya binary sensor platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import MockDeviceListener, check_selective_state_update, initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.BINARY_SENSOR])
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["mcs_oxslv1c9"],
)
@pytest.mark.parametrize(
("updates", "expected_state", "last_reported"),
[
# Update without dpcode - state should not change, last_reported stays
# at available_reported
({"battery_percentage": 80}, "off", "2024-01-01T00:00:20+00:00"),
# Update with dpcode - state should change, last_reported advances
({"doorcontact_state": True}, "on", "2024-01-01T00:01:00+00:00"),
# Update with multiple properties including dpcode - state should change
(
{"battery_percentage": 50, "doorcontact_state": True},
"on",
"2024-01-01T00:01:00+00:00",
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.BINARY_SENSOR])
@pytest.mark.freeze_time("2024-01-01")
async def test_selective_state_update(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
freezer: FrozenDateTimeFactory,
updates: dict[str, Any],
expected_state: str,
last_reported: str,
) -> None:
"""Test skip_update/last_reported."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
await check_selective_state_update(
hass,
mock_device,
mock_listener,
freezer,
entity_id="binary_sensor.window_downstairs_door",
dpcode="doorcontact_state",
initial_state="off",
updates=updates,
expected_state=expected_state,
last_reported=last_reported,
)
@pytest.mark.parametrize(
"mock_device_code",
["cs_zibqa9dutqyaxym2"],
)
@pytest.mark.parametrize(
("fault_value", "tankfull", "defrost", "wet"),
[
(0, "off", "off", "off"),
(0x1, "on", "off", "off"),
(0x2, "off", "on", "off"),
(0x80, "off", "off", "on"),
(0x83, "on", "on", "on"),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.BINARY_SENSOR])
async def test_bitmap(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
fault_value: int,
tankfull: str,
defrost: str,
wet: str,
) -> None:
"""Test BITMAP fault sensor on cs_zibqa9dutqyaxym2."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
assert hass.states.get("binary_sensor.dehumidifier_tank_full").state == "off"
assert hass.states.get("binary_sensor.dehumidifier_defrost").state == "off"
assert hass.states.get("binary_sensor.dehumidifier_wet").state == "off"
await mock_listener.async_send_device_update(
hass, mock_device, {"fault": fault_value}
)
assert hass.states.get("binary_sensor.dehumidifier_tank_full").state == tankfull
assert hass.states.get("binary_sensor.dehumidifier_defrost").state == defrost
assert hass.states.get("binary_sensor.dehumidifier_wet").state == wet
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_climate.py | """Test Tuya climate platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.climate import (
ATTR_CURRENT_TEMPERATURE,
ATTR_FAN_MODE,
ATTR_HUMIDITY,
ATTR_HVAC_MODE,
ATTR_MAX_TEMP,
ATTR_MIN_TEMP,
ATTR_PRESET_MODE,
ATTR_TARGET_TEMP_STEP,
ATTR_TEMPERATURE,
DOMAIN as CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
SERVICE_SET_HUMIDITY,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_PRESET_MODE,
SERVICE_SET_TEMPERATURE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
HVACMode,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceNotSupported
from homeassistant.helpers import entity_registry as er
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
from . import initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.CLIMATE])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.CLIMATE])
async def test_us_customary_system(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
hass.config.units = US_CUSTOMARY_SYSTEM
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
for entity in entity_registry.entities.values():
state = hass.states.get(entity.entity_id)
assert state.attributes == snapshot(
name=entity.entity_id,
include=props(
ATTR_CURRENT_TEMPERATURE,
ATTR_MAX_TEMP,
ATTR_MIN_TEMP,
ATTR_TARGET_TEMP_STEP,
ATTR_TEMPERATURE,
),
)
@pytest.mark.parametrize(
("mock_device_code", "entity_id", "service", "service_data", "expected_commands"),
[
(
"kt_5wnlzekkstwcdsvm",
"climate.air_conditioner",
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: 22.7},
[{"code": "temp_set", "value": 23}],
),
(
"kt_5wnlzekkstwcdsvm",
"climate.air_conditioner",
SERVICE_SET_FAN_MODE,
{ATTR_FAN_MODE: 2},
[{"code": "windspeed", "value": "2"}],
),
(
"kt_5wnlzekkstwcdsvm",
"climate.air_conditioner",
SERVICE_TURN_ON,
{},
[{"code": "switch", "value": True}],
),
(
"kt_5wnlzekkstwcdsvm",
"climate.air_conditioner",
SERVICE_TURN_OFF,
{},
[{"code": "switch", "value": False}],
),
(
"kt_ibmmirhhq62mmf1g",
"climate.master_bedroom_ac",
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.COOL},
[{"code": "switch", "value": True}, {"code": "mode", "value": "cold"}],
),
(
"wk_gc1bxoq2hafxpa35",
"climate.polotentsosushitel",
SERVICE_SET_PRESET_MODE,
{ATTR_PRESET_MODE: "holiday"},
[{"code": "mode", "value": "holiday"}],
),
],
)
async def test_action(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
entity_id: str,
service: str,
service_data: dict[str, Any],
expected_commands: list[dict[str, Any]],
) -> None:
"""Test climate action."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
CLIMATE_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
**service_data,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id, expected_commands
)
@pytest.mark.parametrize(
"mock_device_code",
["kt_5wnlzekkstwcdsvm"],
)
@pytest.mark.parametrize(
("service", "service_data"),
[
(
SERVICE_SET_FAN_MODE,
{ATTR_FAN_MODE: 2},
),
(
SERVICE_SET_HUMIDITY,
{ATTR_HUMIDITY: 50},
),
],
)
async def test_action_not_supported(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service: str,
service_data: dict[str, Any],
) -> None:
"""Test service action not supported."""
# Remove windspeed DPCode to simulate a device with no valid fan mode
mock_device.function.pop("windspeed", None)
mock_device.status_range.pop("windspeed", None)
mock_device.status.pop("windspeed", None)
entity_id = "climate.air_conditioner"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
assert state.attributes.get(ATTR_FAN_MODE) is None
with pytest.raises(ServiceNotSupported):
await hass.services.async_call(
CLIMATE_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
**service_data,
},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_climate.py",
"license": "Apache License 2.0",
"lines": 189,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_cover.py | """Test Tuya cover platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.cover import (
ATTR_CURRENT_POSITION,
ATTR_POSITION,
ATTR_TILT_POSITION,
DOMAIN as COVER_DOMAIN,
SERVICE_CLOSE_COVER,
SERVICE_OPEN_COVER,
SERVICE_SET_COVER_POSITION,
SERVICE_SET_COVER_TILT_POSITION,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_CLOSED,
STATE_OPEN,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceNotSupported
from homeassistant.helpers import entity_registry as er
from . import initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["cl_zah67ekd"],
)
@pytest.mark.parametrize(
("service", "service_data", "expected_commands"),
[
(
SERVICE_OPEN_COVER,
{},
[
{"code": "percent_control", "value": 0},
],
),
(
SERVICE_CLOSE_COVER,
{},
[
{"code": "percent_control", "value": 100},
],
),
(
SERVICE_SET_COVER_POSITION,
{
ATTR_POSITION: 25,
},
[
{"code": "percent_control", "value": 75},
],
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER])
async def test_action(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service: str,
service_data: dict[str, Any],
expected_commands: list[dict[str, Any]],
) -> None:
"""Test cover action."""
entity_id = "cover.kitchen_blinds_curtain"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
COVER_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
**service_data,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id, expected_commands
)
@pytest.mark.parametrize(
"mock_device_code",
["cl_zah67ekd"],
)
@pytest.mark.parametrize(
("percent_control", "percent_state"),
[
(100, 52),
(0, 100),
(50, 25),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER])
async def test_percent_state_on_cover(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
percent_control: int,
percent_state: int,
) -> None:
"""Test percent_state attribute on the cover entity."""
mock_device.status["percent_control"] = percent_control
# 100 is closed and 0 is open for Tuya covers
mock_device.status["percent_state"] = 100 - percent_state
entity_id = "cover.kitchen_blinds_curtain"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
assert state.attributes[ATTR_CURRENT_POSITION] == percent_state
@pytest.mark.parametrize(
"mock_device_code",
["cl_zah67ekd"],
)
async def test_set_tilt_position_not_supported(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
) -> None:
"""Test set tilt position service (not available on this device)."""
entity_id = "cover.kitchen_blinds_curtain"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
with pytest.raises(ServiceNotSupported):
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_TILT_POSITION: 50,
},
blocking=True,
)
@pytest.mark.parametrize(
"mock_device_code",
["clkg_wltqkykhni0papzj"],
)
@pytest.mark.parametrize(
("initial_percent_control", "expected_state", "expected_position"),
[
(0, "closed", 0),
(25, "open", 25),
(50, "open", 50),
(75, "open", 75),
(100, "open", 100),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER])
async def test_clkg_wltqkykhni0papzj_state(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
initial_percent_control: int,
expected_state: str,
expected_position: int,
) -> None:
"""Test cover position for wltqkykhni0papzj device.
See https://github.com/home-assistant/core/issues/151635
percent_control == 0 is when my roller shutter is completely open (meaning up)
percent_control == 100 is when my roller shutter is completely closed (meaning down)
"""
entity_id = "cover.roller_shutter_living_room_curtain"
mock_device.status["percent_control"] = initial_percent_control
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
assert state.state == expected_state
assert state.attributes[ATTR_CURRENT_POSITION] == expected_position
@pytest.mark.parametrize(
"mock_device_code",
["clkg_wltqkykhni0papzj"],
)
@pytest.mark.parametrize(
("service_name", "service_kwargs", "expected_commands"),
[
(
SERVICE_OPEN_COVER,
{},
[
{"code": "percent_control", "value": 100},
],
),
(
SERVICE_SET_COVER_POSITION,
{ATTR_POSITION: 25},
[
{"code": "percent_control", "value": 25},
],
),
(
SERVICE_CLOSE_COVER,
{},
[
{"code": "percent_control", "value": 0},
],
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER])
async def test_clkg_wltqkykhni0papzj_action(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service_name: str,
service_kwargs: dict,
expected_commands: list[dict],
) -> None:
"""Test cover position for wltqkykhni0papzj device.
See https://github.com/home-assistant/core/issues/151635
percent_control == 0 is when my roller shutter is completely open (meaning up)
percent_control == 100 is when my roller shutter is completely closed (meaning down)
"""
entity_id = "cover.roller_shutter_living_room_curtain"
mock_device.status["percent_control"] = 50
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
await hass.services.async_call(
COVER_DOMAIN,
service_name,
{ATTR_ENTITY_ID: entity_id, **service_kwargs},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id,
expected_commands,
)
@pytest.mark.parametrize(
"mock_device_code",
["cl_n3xgr5pdmpinictg"],
)
@pytest.mark.parametrize(
("initial_control", "expected_state"),
[
("open", STATE_OPEN),
("stop", STATE_UNKNOWN),
("close", STATE_CLOSED),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER])
async def test_cl_n3xgr5pdmpinictg_state(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
initial_control: str,
expected_state: str,
) -> None:
"""Test cover position for n3xgr5pdmpinictg device.
See https://github.com/home-assistant/core/issues/153537
"""
entity_id = "cover.estore_sala_curtain"
mock_device.status["control"] = initial_control
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
assert state.state == expected_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_cover.py",
"license": "Apache License 2.0",
"lines": 279,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_diagnostics.py | """Test Tuya diagnostics platform."""
from __future__ import annotations
import pytest
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.tuya.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import initialize_entry
from tests.common import MockConfigEntry
from tests.components.diagnostics import (
get_diagnostics_for_config_entry,
get_diagnostics_for_device,
)
from tests.typing import ClientSessionGenerator
@pytest.mark.parametrize("mock_device_code", ["rqbj_4iqe2hsfyd86kwwc"])
async def test_entry_diagnostics(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
result = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
assert result == snapshot(
exclude=props("last_changed", "last_reported", "last_updated")
)
@pytest.mark.parametrize(
"mock_device_code",
[
"rqbj_4iqe2hsfyd86kwwc",
"mal_gyitctrjj1kefxp2", # with redacted dpcodes
"tdq_9htyiowaf5rtdhrv", # with bad enum warnings
],
)
async def test_device_diagnostics(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
hass_client: ClientSessionGenerator,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test device diagnostics."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
device = device_registry.async_get_device(identifiers={(DOMAIN, mock_device.id)})
assert device, repr(device_registry.devices)
result = await get_diagnostics_for_device(
hass, hass_client, mock_config_entry, device
)
assert result == snapshot(
exclude=props("last_changed", "last_reported", "last_updated")
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 60,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_event.py | """Test Tuya event platform."""
from __future__ import annotations
import base64
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import MockDeviceListener, initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.freeze_time("2023-11-01 13:14:15+01:00")
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.EVENT])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
mock_listener: MockDeviceListener,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
for mock_device in mock_devices:
# Simulate an initial device update to generate events
await mock_listener.async_send_device_update(
hass, mock_device, mock_device.status
)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["sp_csr2fqitalj5o0tq"],
)
@pytest.mark.parametrize(
("entity_id", "dpcode", "value"),
[
(
"event.intercom_doorbell_picture",
"doorbell_pic",
base64.b64encode(b"https://some-picture-url.com/image.jpg"),
),
(
"event.intercom_doorbell_message",
"alarm_message",
base64.b64encode(b'{"some": "json", "random": "data"}'),
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.EVENT])
async def test_alarm_message_event(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
snapshot: SnapshotAssertion,
entity_id: str,
dpcode: str,
value: str,
) -> None:
"""Test alarm message event."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
mock_device.status[dpcode] = value
await mock_listener.async_send_device_update(hass, mock_device, mock_device.status)
# Verify event was triggered with correct type and decoded URL
state = hass.states.get(entity_id)
assert state.attributes == snapshot
assert state.attributes["message"]
@pytest.mark.parametrize(
"mock_device_code",
["wxkg_l8yaz4um5b3pwyvf"],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.EVENT])
@pytest.mark.freeze_time("2024-01-01")
async def test_selective_state_update(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
freezer: FrozenDateTimeFactory,
) -> None:
"""Ensure event is only triggered when device reports actual data."""
entity_id = "event.bathroom_smart_switch_button_1"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
# Initial state is unknown
assert hass.states.get(entity_id).state == STATE_UNKNOWN
# Device receives a data update - event gets triggered and state gets updated
freezer.tick(10)
await mock_listener.async_send_device_update(
hass, mock_device, {"switch_mode1": "click"}
)
assert hass.states.get(entity_id).state == "2024-01-01T00:00:10.000+00:00"
# Device goes offline
freezer.tick(10)
mock_device.online = False
await mock_listener.async_send_device_update(hass, mock_device, None)
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
# Device comes back online - state should go back to last known value,
# not new datetime since no new data update has come in
freezer.tick(10)
mock_device.online = True
await mock_listener.async_send_device_update(hass, mock_device, None)
assert hass.states.get(entity_id).state == "2024-01-01T00:00:10.000+00:00"
# Device receives a new data update - event gets triggered and state gets updated
freezer.tick(10)
await mock_listener.async_send_device_update(
hass, mock_device, {"switch_mode1": "click"}
)
assert hass.states.get(entity_id).state == "2024-01-01T00:00:40.000+00:00"
# Device receives a data update on a different datapoint - event doesn't
# get triggered and state doesn't get updated
freezer.tick(10)
await mock_listener.async_send_device_update(
hass, mock_device, {"switch_mode2": "click"}
)
assert hass.states.get(entity_id).state == "2024-01-01T00:00:40.000+00:00"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_event.py",
"license": "Apache License 2.0",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_fan.py | """Test Tuya fan platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.fan import (
DOMAIN as FAN_DOMAIN,
SERVICE_OSCILLATE,
SERVICE_SET_DIRECTION,
SERVICE_SET_PRESET_MODE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.FAN])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.FAN])
@pytest.mark.parametrize(
("mock_device_code", "entity_id", "service", "service_data", "expected_commands"),
[
(
"ks_j9fa8ahzac8uvlfl",
"fan.tower_fan_ca_407g_smart",
SERVICE_OSCILLATE,
{"oscillating": False},
[{"code": "switch_horizontal", "value": False}],
),
(
"ks_j9fa8ahzac8uvlfl",
"fan.tower_fan_ca_407g_smart",
SERVICE_OSCILLATE,
{"oscillating": True},
[{"code": "switch_horizontal", "value": True}],
),
(
"fs_g0ewlb1vmwqljzji",
"fan.ceiling_fan_with_light",
SERVICE_SET_DIRECTION,
{"direction": "forward"},
[{"code": "fan_direction", "value": "forward"}],
),
(
"ks_j9fa8ahzac8uvlfl",
"fan.tower_fan_ca_407g_smart",
SERVICE_SET_PRESET_MODE,
{"preset_mode": "sleep"},
[{"code": "mode", "value": "sleep"}],
),
(
"fs_g0ewlb1vmwqljzji",
"fan.ceiling_fan_with_light",
SERVICE_TURN_OFF,
{},
[{"code": "switch", "value": False}],
),
(
"fs_g0ewlb1vmwqljzji",
"fan.ceiling_fan_with_light",
SERVICE_TURN_ON,
{"preset_mode": "sleep"},
[{"code": "switch", "value": True}, {"code": "mode", "value": "sleep"}],
),
],
)
async def test_action(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
entity_id: str,
service: str,
service_data: dict[str, Any],
expected_commands: list[dict[str, Any]],
) -> None:
"""Test fan action."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
FAN_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
**service_data,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id, expected_commands
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_fan.py",
"license": "Apache License 2.0",
"lines": 106,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_humidifier.py | """Test Tuya humidifier platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.humidifier import (
ATTR_HUMIDITY,
DOMAIN as HUMIDIFIER_DOMAIN,
SERVICE_SET_HUMIDITY,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.HUMIDIFIER])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["cs_zibqa9dutqyaxym2"],
)
@pytest.mark.parametrize(
("service", "service_data", "expected_command"),
[
(SERVICE_TURN_ON, {}, {"code": "switch", "value": True}),
(SERVICE_TURN_OFF, {}, {"code": "switch", "value": False}),
(
SERVICE_SET_HUMIDITY,
{ATTR_HUMIDITY: 50},
{"code": "dehumidify_set_value", "value": 50},
),
],
)
async def test_action(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service: str,
service_data: dict[str, Any],
expected_command: dict[str, Any],
) -> None:
"""Test humidifier action."""
entity_id = "humidifier.dehumidifier"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
HUMIDIFIER_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
**service_data,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id, [expected_command]
)
@pytest.mark.parametrize(
"mock_device_code",
["cs_zibqa9dutqyaxym2"],
)
@pytest.mark.parametrize(
("service", "service_data", "translation_placeholders"),
[
(
SERVICE_TURN_ON,
{},
{
"expected": "['switch', 'switch_spray']",
"available": ("['child_lock', 'countdown_set']"),
},
),
(
SERVICE_TURN_OFF,
{},
{
"expected": "['switch', 'switch_spray']",
"available": ("['child_lock', 'countdown_set']"),
},
),
(
SERVICE_SET_HUMIDITY,
{ATTR_HUMIDITY: 50},
{
"expected": "['dehumidify_set_value']",
"available": ("['child_lock', 'countdown_set']"),
},
),
],
)
async def test_action_unsupported(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service: str,
service_data: dict[str, Any],
translation_placeholders: dict[str, Any],
) -> None:
"""Test service actions when not supported by the device."""
# Remove switch control and dehumidify_set_value - but keep other functionality
mock_device.status.pop("switch")
mock_device.function.pop("switch")
mock_device.status_range.pop("switch")
mock_device.status.pop("dehumidify_set_value")
mock_device.function.pop("dehumidify_set_value")
mock_device.status_range.pop("dehumidify_set_value")
entity_id = "humidifier.dehumidifier"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
HUMIDIFIER_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
**service_data,
},
blocking=True,
)
assert err.value.translation_key == "action_dpcode_not_found"
assert err.value.translation_placeholders == translation_placeholders
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_humidifier.py",
"license": "Apache License 2.0",
"lines": 140,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_init.py | """Test Tuya initialization."""
from __future__ import annotations
from unittest.mock import patch
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.tuya.const import (
CONF_ENDPOINT,
CONF_TERMINAL_ID,
CONF_TOKEN_INFO,
CONF_USER_CODE,
DOMAIN,
)
from homeassistant.components.tuya.diagnostics import _REDACTED_DPCODES
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import DEVICE_MOCKS, create_device, create_manager, initialize_entry
from tests.common import MockConfigEntry, async_load_json_object_fixture
async def test_registry_cleanup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Ensure no-longer-present devices are removed from the device registry."""
# Initialize with two devices
main_manager = create_manager()
main_device = await create_device(hass, "mcs_8yhypbo7")
second_device = await create_device(hass, "clkg_y7j64p60glp8qpx7")
await initialize_entry(
hass, main_manager, mock_config_entry, [main_device, second_device]
)
# Initialize should have two devices
all_entries = dr.async_entries_for_config_entry(
device_registry, mock_config_entry.entry_id
)
assert len(all_entries) == 2
# Now remove the second device from the manager and re-initialize
del main_manager.device_map[second_device.id]
with patch("homeassistant.components.tuya.Manager", return_value=main_manager):
await hass.config_entries.async_reload(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Only the main device should remain
all_entries = dr.async_entries_for_config_entry(
device_registry, mock_config_entry.entry_id
)
assert len(all_entries) == 1
assert all_entries[0].identifiers == {(DOMAIN, main_device.id)}
async def test_registry_cleanup_multiple_entries(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Ensure multiple config entries do not remove items from other entries."""
main_entity_id = "sensor.boite_aux_lettres_arriere_battery"
second_entity_id = "binary_sensor.window_downstairs_door"
main_manager = create_manager()
main_device = await create_device(hass, "mcs_8yhypbo7")
await initialize_entry(hass, main_manager, mock_config_entry, main_device)
# Ensure initial setup is correct (main present, second absent)
assert hass.states.get(main_entity_id)
assert entity_registry.async_get(main_entity_id)
assert not hass.states.get(second_entity_id)
assert not entity_registry.async_get(second_entity_id)
# Create a second config entry
second_config_entry = MockConfigEntry(
title="Test Tuya entry",
domain=DOMAIN,
data={
CONF_ENDPOINT: "test_endpoint",
CONF_TERMINAL_ID: "test_terminal",
CONF_TOKEN_INFO: "test_token",
CONF_USER_CODE: "test_user_code",
},
unique_id="56789",
)
second_manager = create_manager()
second_device = await create_device(hass, "mcs_oxslv1c9")
await initialize_entry(hass, second_manager, second_config_entry, second_device)
# Ensure setup is correct (both present)
assert hass.states.get(main_entity_id)
assert entity_registry.async_get(main_entity_id)
assert hass.states.get(second_entity_id)
assert entity_registry.async_get(second_entity_id)
async def test_device_registry(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Validate device registry snapshots for all devices, including unsupported ones."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
device_registry_entries = dr.async_entries_for_config_entry(
device_registry, mock_config_entry.entry_id
)
# Ensure the device registry contains same amount as DEVICE_MOCKS
assert len(device_registry_entries) == len(DEVICE_MOCKS)
for device_registry_entry in device_registry_entries:
assert device_registry_entry == snapshot(
name=list(device_registry_entry.identifiers)[0][1]
)
# Ensure model is suffixed with "(unsupported)" when no entities are generated
assert (" (unsupported)" in device_registry_entry.model) == (
not er.async_entries_for_device(
entity_registry,
device_registry_entry.id,
include_disabled_entities=True,
)
)
async def test_fixtures_valid(hass: HomeAssistant) -> None:
"""Ensure Tuya fixture files are valid."""
# We want to ensure that the fixture files do not contain
# `home_assistant`, `id`, or `terminal_id` keys.
# These are provided by the Tuya diagnostics and should be removed
# from the fixture.
EXCLUDE_KEYS = ("home_assistant", "id", "terminal_id")
for device_code in DEVICE_MOCKS:
details = await async_load_json_object_fixture(
hass, f"{device_code}.json", DOMAIN
)
for key in EXCLUDE_KEYS:
assert key not in details, (
f"Please remove data[`'{key}']` from {device_code}.json"
)
if "status" in details:
statuses = details["status"]
for key in statuses:
if key in _REDACTED_DPCODES:
assert statuses[key] == "**REDACTED**", (
f"Please mark `data['status']['{key}']` as `**REDACTED**`"
f" in {device_code}.json"
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_init.py",
"license": "Apache License 2.0",
"lines": 133,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_light.py | """Test Tuya light platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
ATTR_WHITE,
DOMAIN as LIGHT_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.LIGHT])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["dj_mki13ie507rlry4r"],
)
@pytest.mark.parametrize(
("service", "service_data", "expected_commands"),
[
(
SERVICE_TURN_ON,
{
ATTR_WHITE: True,
},
[
{"code": "switch_led", "value": True},
{"code": "work_mode", "value": "white"},
{"code": "bright_value_v2", "value": 546},
],
),
(
SERVICE_TURN_ON,
{
ATTR_BRIGHTNESS: 150,
},
[
{"code": "switch_led", "value": True},
{"code": "bright_value_v2", "value": 592},
],
),
(
SERVICE_TURN_ON,
{
ATTR_WHITE: True,
ATTR_BRIGHTNESS: 150,
},
[
{"code": "switch_led", "value": True},
{"code": "work_mode", "value": "white"},
{"code": "bright_value_v2", "value": 592},
],
),
(
SERVICE_TURN_ON,
{
ATTR_WHITE: 150,
},
[
{"code": "switch_led", "value": True},
{"code": "work_mode", "value": "white"},
{"code": "bright_value_v2", "value": 592},
],
),
(
SERVICE_TURN_ON,
{
ATTR_BRIGHTNESS: 255,
ATTR_HS_COLOR: (10.1, 20.2),
},
[
{"code": "switch_led", "value": True},
{"code": "work_mode", "value": "colour"},
{"code": "colour_data_v2", "value": '{"h": 10, "s": 202, "v": 1000}'},
],
),
(
SERVICE_TURN_OFF,
{},
[{"code": "switch_led", "value": False}],
),
],
)
async def test_action(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service: str,
service_data: dict[str, Any],
expected_commands: list[dict[str, Any]],
) -> None:
"""Test light action."""
entity_id = "light.garage_light"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
LIGHT_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
**service_data,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id,
expected_commands,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_light.py",
"license": "Apache License 2.0",
"lines": 129,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_number.py | """Test Tuya number platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import MockDeviceListener, check_selective_state_update, initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.NUMBER])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["mal_gyitctrjj1kefxp2"],
)
@pytest.mark.parametrize(
("updates", "expected_state", "last_reported"),
[
# Update without dpcode - state should not change, last_reported stays
# at available_reported
({"switch_alarm_sound": True}, "15.0", "2024-01-01T00:00:20+00:00"),
# Update with dpcode - state should change, last_reported advances
({"delay_set": 17}, "17.0", "2024-01-01T00:01:00+00:00"),
# Update with multiple properties including dpcode - state should change
(
{"switch_alarm_sound": True, "delay_set": 17},
"17.0",
"2024-01-01T00:01:00+00:00",
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.NUMBER])
@pytest.mark.freeze_time("2024-01-01")
async def test_selective_state_update(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
freezer: FrozenDateTimeFactory,
updates: dict[str, Any],
expected_state: str,
last_reported: str,
) -> None:
"""Test skip_update/last_reported."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
await check_selective_state_update(
hass,
mock_device,
mock_listener,
freezer,
entity_id="number.multifunction_alarm_arm_delay",
dpcode="delay_set",
initial_state="15.0",
updates=updates,
expected_state=expected_state,
last_reported=last_reported,
)
@pytest.mark.parametrize(
"mock_device_code",
["mal_gyitctrjj1kefxp2"],
)
async def test_set_value(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
) -> None:
"""Test set value."""
entity_id = "number.multifunction_alarm_arm_delay"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{
ATTR_ENTITY_ID: entity_id,
ATTR_VALUE: 18,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id, [{"code": "delay_set", "value": 18}]
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_number.py",
"license": "Apache License 2.0",
"lines": 104,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_select.py | """Test Tuya select platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.select import (
ATTR_OPTION,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import MockDeviceListener, check_selective_state_update, initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SELECT])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["cl_zah67ekd"],
)
@pytest.mark.parametrize(
("updates", "expected_state", "last_reported"),
[
# Update without dpcode - state should not change, last_reported stays
# at available_reported
({"control": "stop"}, "forward", "2024-01-01T00:00:20+00:00"),
# Update with dpcode - state should change, last_reported advances
({"control_back_mode": "back"}, "back", "2024-01-01T00:01:00+00:00"),
# Update with multiple properties including dpcode - state should change
(
{"control": "stop", "control_back_mode": "back"},
"back",
"2024-01-01T00:01:00+00:00",
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SELECT])
@pytest.mark.freeze_time("2024-01-01")
async def test_selective_state_update(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
freezer: FrozenDateTimeFactory,
updates: dict[str, Any],
expected_state: str,
last_reported: str,
) -> None:
"""Test skip_update/last_reported."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
await check_selective_state_update(
hass,
mock_device,
mock_listener,
freezer,
entity_id="select.kitchen_blinds_motor_mode",
dpcode="control_back_mode",
initial_state="forward",
updates=updates,
expected_state=expected_state,
last_reported=last_reported,
)
@pytest.mark.parametrize(
"mock_device_code",
["cl_zah67ekd"],
)
async def test_select_option(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
) -> None:
"""Test fan mode with windspeed."""
entity_id = "select.kitchen_blinds_motor_mode"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "forward",
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id, [{"code": "control_back_mode", "value": "forward"}]
)
@pytest.mark.parametrize(
"mock_device_code",
["cl_zah67ekd"],
)
async def test_select_invalid_option(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
) -> None:
"""Test fan mode with windspeed."""
entity_id = "select.kitchen_blinds_motor_mode"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
with pytest.raises(ServiceValidationError) as exc:
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "hello",
},
blocking=True,
)
assert exc.value.translation_key == "not_valid_option"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_select.py",
"license": "Apache License 2.0",
"lines": 131,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_sensor.py | """Test Tuya sensor platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.sensor import SensorStateClass
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import MockDeviceListener, check_selective_state_update, initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SENSOR])
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["mcs_8yhypbo7"],
)
@pytest.mark.parametrize(
("updates", "expected_state", "last_reported"),
[
# Update without dpcode - state should not change, last_reported stays
# at available_reported
({"doorcontact_state": True}, "62.0", "2024-01-01T00:00:20+00:00"),
# Update with dpcode - state should change, last_reported advances
({"battery_percentage": 50}, "50.0", "2024-01-01T00:01:00+00:00"),
# Update with multiple properties including dpcode - state should change
(
{"doorcontact_state": True, "battery_percentage": 50},
"50.0",
"2024-01-01T00:01:00+00:00",
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SENSOR])
@pytest.mark.freeze_time("2024-01-01")
async def test_selective_state_update(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
freezer: FrozenDateTimeFactory,
updates: dict[str, Any],
expected_state: str,
last_reported: str,
) -> None:
"""Test skip_update/last_reported."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
await check_selective_state_update(
hass,
mock_device,
mock_listener,
freezer,
entity_id="sensor.boite_aux_lettres_arriere_battery",
dpcode="battery_percentage",
initial_state="62.0",
updates=updates,
expected_state=expected_state,
last_reported=last_reported,
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SENSOR])
@pytest.mark.parametrize("mock_device_code", ["cz_guitoc9iylae4axs"])
async def test_delta_report_sensor(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
) -> None:
"""Test delta report sensor behavior."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
entity_id = "sensor.ha_socket_delta_test_total_energy"
timestamp = 1000
# Delta sensors start from zero and accumulate values
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "0"
assert state.attributes["state_class"] == SensorStateClass.TOTAL_INCREASING
# Send delta update
await mock_listener.async_send_device_update(
hass,
mock_device,
{"add_ele": 200},
{"add_ele": timestamp},
)
state = hass.states.get(entity_id)
assert state is not None
assert float(state.state) == pytest.approx(0.2)
# Send delta update (multiple dpcode)
timestamp += 100
await mock_listener.async_send_device_update(
hass,
mock_device,
{"add_ele": 300, "switch_1": True},
{"add_ele": timestamp, "switch_1": timestamp},
)
state = hass.states.get(entity_id)
assert state is not None
assert float(state.state) == pytest.approx(0.5)
# Send delta update (timestamp not incremented)
await mock_listener.async_send_device_update(
hass,
mock_device,
{"add_ele": 500},
{"add_ele": timestamp}, # same timestamp
)
state = hass.states.get(entity_id)
assert state is not None
assert float(state.state) == pytest.approx(0.5) # unchanged
# Send delta update (unrelated dpcode)
await mock_listener.async_send_device_update(
hass,
mock_device,
{"switch_1": False},
{"switch_1": timestamp + 100},
)
state = hass.states.get(entity_id)
assert state is not None
assert float(state.state) == pytest.approx(0.5) # unchanged
# Send delta update
timestamp += 100
await mock_listener.async_send_device_update(
hass,
mock_device,
{"add_ele": 100},
{"add_ele": timestamp},
)
state = hass.states.get(entity_id)
assert state is not None
assert float(state.state) == pytest.approx(0.6)
# Send delta update (None value)
timestamp += 100
mock_device.status["add_ele"] = None
await mock_listener.async_send_device_update(
hass,
mock_device,
{"add_ele": None},
{"add_ele": timestamp},
)
state = hass.states.get(entity_id)
assert state is not None
assert float(state.state) == pytest.approx(0.6) # unchanged
# Send delta update (no timestamp - skipped)
mock_device.status["add_ele"] = 200
await mock_listener.async_send_device_update(
hass,
mock_device,
{"add_ele": 200},
None,
)
state = hass.states.get(entity_id)
assert state is not None
assert float(state.state) == pytest.approx(0.6) # unchanged
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_sensor.py",
"license": "Apache License 2.0",
"lines": 167,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_siren.py | """Test Tuya siren platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.siren import (
DOMAIN as SIREN_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import MockDeviceListener, check_selective_state_update, initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SIREN])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["sp_sdd5f5f2dl5wydjf"],
)
@pytest.mark.parametrize(
("updates", "expected_state", "last_reported"),
[
# Update without dpcode - state should not change, last_reported stays
# at available_reported
({"basic_wdr": False}, "off", "2024-01-01T00:00:20+00:00"),
# Update with dpcode - state should change, last_reported advances
({"siren_switch": True}, "on", "2024-01-01T00:01:00+00:00"),
# Update with multiple properties including dpcode - state should change
(
{"basic_wdr": False, "siren_switch": True},
"on",
"2024-01-01T00:01:00+00:00",
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SIREN])
@pytest.mark.freeze_time("2024-01-01")
async def test_selective_state_update(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
freezer: FrozenDateTimeFactory,
updates: dict[str, Any],
expected_state: str,
last_reported: str,
) -> None:
"""Test skip_update/last_reported."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
await check_selective_state_update(
hass,
mock_device,
mock_listener,
freezer,
entity_id="siren.c9",
dpcode="siren_switch",
initial_state="off",
updates=updates,
expected_state=expected_state,
last_reported=last_reported,
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SIREN])
@pytest.mark.parametrize(
"mock_device_code",
["sp_sdd5f5f2dl5wydjf"],
)
@pytest.mark.parametrize(
("service", "expected_commands"),
[
(
SERVICE_TURN_ON,
[{"code": "siren_switch", "value": True}],
),
(
SERVICE_TURN_OFF,
[{"code": "siren_switch", "value": False}],
),
],
)
async def test_action(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service: str,
expected_commands: list[dict[str, Any]],
) -> None:
"""Test siren action."""
entity_id = "siren.c9"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
SIREN_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id, expected_commands
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_siren.py",
"license": "Apache License 2.0",
"lines": 119,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tuya/test_switch.py | """Test Tuya switch platform."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.components.tuya import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from . import MockDeviceListener, check_selective_state_update, initialize_entry
from tests.common import MockConfigEntry, snapshot_platform
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SWITCH])
async def test_platform_setup_and_discovery(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_devices: list[CustomerDevice],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform setup and discovery."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mock_device_code",
["cz_PGEkBctAbtzKOZng"],
)
@pytest.mark.parametrize(
("updates", "expected_state", "last_reported"),
[
# Update without dpcode - state should not change, last_reported stays
# at available_reported
({"countdown_1": 50}, "off", "2024-01-01T00:00:20+00:00"),
# Update with dpcode - state should change, last_reported advances
({"switch": True}, "on", "2024-01-01T00:01:00+00:00"),
# Update with multiple properties including dpcode - state should change
(
{"countdown_1": 50, "switch": True},
"on",
"2024-01-01T00:01:00+00:00",
),
],
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SWITCH])
@pytest.mark.freeze_time("2024-01-01")
async def test_selective_state_update(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
mock_listener: MockDeviceListener,
freezer: FrozenDateTimeFactory,
updates: dict[str, Any],
expected_state: str,
last_reported: str,
) -> None:
"""Test skip_update/last_reported."""
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
await check_selective_state_update(
hass,
mock_device,
mock_listener,
freezer,
entity_id="switch.din_socket",
dpcode="switch",
initial_state="off",
updates=updates,
expected_state=expected_state,
last_reported=last_reported,
)
@pytest.mark.parametrize(
("preexisting_entity", "disabled_by", "expected_entity", "expected_issue"),
[
(True, None, True, True),
(True, er.RegistryEntryDisabler.USER, False, False),
(False, None, False, False),
],
)
@pytest.mark.parametrize(
"mock_device_code",
["sfkzq_rzklytdei8i8vo37"],
)
async def test_sfkzq_deprecated_switch(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
issue_registry: ir.IssueRegistry,
entity_registry: er.EntityRegistry,
preexisting_entity: bool,
disabled_by: er.RegistryEntryDisabler,
expected_entity: bool,
expected_issue: bool,
) -> None:
"""Test switch deprecation issue."""
original_entity_id = "switch.balkonbewasserung_switch"
entity_unique_id = "tuya.73ov8i8iedtylkzrqzkfsswitch"
if preexisting_entity:
suggested_id = original_entity_id.replace(f"{SWITCH_DOMAIN}.", "")
entity_registry.async_get_or_create(
SWITCH_DOMAIN,
DOMAIN,
entity_unique_id,
suggested_object_id=suggested_id,
disabled_by=disabled_by,
)
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
assert (
entity_registry.async_get(original_entity_id) is not None
) is expected_entity
assert (
issue_registry.async_get_issue(
domain=DOMAIN,
issue_id=f"deprecated_entity_{entity_unique_id}",
)
is not None
) is expected_issue
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SWITCH])
@pytest.mark.parametrize(
"mock_device_code",
["cz_PGEkBctAbtzKOZng"],
)
@pytest.mark.parametrize(
("service", "expected_commands"),
[
(
SERVICE_TURN_ON,
[{"code": "switch", "value": True}],
),
(
SERVICE_TURN_OFF,
[{"code": "switch", "value": False}],
),
],
)
async def test_action(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
service: str,
expected_commands: list[dict[str, Any]],
) -> None:
"""Test switch action."""
entity_id = "switch.din_socket"
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
mock_manager.send_commands.assert_called_once_with(
mock_device.id, expected_commands
)
@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SWITCH])
@pytest.mark.parametrize(
"mock_device_code",
["cz_PGEkBctAbtzKOZng"],
)
@pytest.mark.parametrize(
("initial_status", "expected_state"),
[
(True, "on"),
(False, "off"),
(None, STATE_UNKNOWN),
("some string", STATE_UNKNOWN),
],
)
async def test_state(
hass: HomeAssistant,
mock_manager: Manager,
mock_config_entry: MockConfigEntry,
mock_device: CustomerDevice,
initial_status: Any,
expected_state: str,
) -> None:
"""Test switch state."""
entity_id = "switch.din_socket"
mock_device.status["switch"] = initial_status
await initialize_entry(hass, mock_manager, mock_config_entry, mock_device)
state = hass.states.get(entity_id)
assert state is not None, f"{entity_id} does not exist"
assert state.state == expected_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tuya/test_switch.py",
"license": "Apache License 2.0",
"lines": 196,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/uptime_kuma/test_config_flow.py | """Test the Uptime Kuma config flow."""
from unittest.mock import AsyncMock
import pytest
from pythonkuma import (
UptimeKumaAuthenticationException,
UptimeKumaConnectionException,
UptimeKumaParseException,
)
from homeassistant.components.uptime_kuma.const import DOMAIN
from homeassistant.config_entries import SOURCE_HASSIO, SOURCE_IGNORE, SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import ADDON_SERVICE_INFO
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://uptime.example.org/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "uptime.example.org"
assert result["data"] == {
CONF_URL: "https://uptime.example.org/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("raise_error", "text_error"),
[
(UptimeKumaConnectionException, "cannot_connect"),
(UptimeKumaAuthenticationException, "invalid_auth"),
(UptimeKumaParseException, "invalid_data"),
(ValueError, "unknown"),
],
)
async def test_form_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_pythonkuma: AsyncMock,
raise_error: Exception,
text_error: str,
) -> None:
"""Test we handle errors and recover."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_pythonkuma.metrics.side_effect = raise_error
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://uptime.example.org/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
mock_pythonkuma.metrics.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://uptime.example.org/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "uptime.example.org"
assert result["data"] == {
CONF_URL: "https://uptime.example.org/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_form_already_configured(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test we abort when entry is already configured."""
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://uptime.example.org/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_flow_reauth(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test reauth flow."""
config_entry.add_to_hass(hass)
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "newapikey"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert config_entry.data[CONF_API_KEY] == "newapikey"
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.parametrize(
("raise_error", "text_error"),
[
(UptimeKumaConnectionException, "cannot_connect"),
(UptimeKumaAuthenticationException, "invalid_auth"),
(UptimeKumaParseException, "invalid_data"),
(ValueError, "unknown"),
],
)
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_flow_reauth_errors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_pythonkuma: AsyncMock,
raise_error: Exception,
text_error: str,
) -> None:
"""Test reauth flow errors and recover."""
config_entry.add_to_hass(hass)
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_pythonkuma.metrics.side_effect = raise_error
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "newapikey"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
mock_pythonkuma.metrics.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "newapikey"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert config_entry.data[CONF_API_KEY] == "newapikey"
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_flow_reconfigure(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test reconfigure flow."""
config_entry.add_to_hass(hass)
result = await config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://uptime.example.org:3001/",
CONF_VERIFY_SSL: False,
CONF_API_KEY: "newapikey",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data == {
CONF_URL: "https://uptime.example.org:3001/",
CONF_VERIFY_SSL: False,
CONF_API_KEY: "newapikey",
}
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.parametrize(
("raise_error", "text_error"),
[
(UptimeKumaConnectionException, "cannot_connect"),
(UptimeKumaAuthenticationException, "invalid_auth"),
(UptimeKumaParseException, "invalid_data"),
(ValueError, "unknown"),
],
)
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_flow_reconfigure_errors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_pythonkuma: AsyncMock,
raise_error: Exception,
text_error: str,
) -> None:
"""Test reconfigure flow errors and recover."""
config_entry.add_to_hass(hass)
result = await config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_pythonkuma.metrics.side_effect = raise_error
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://uptime.example.org:3001/",
CONF_VERIFY_SSL: False,
CONF_API_KEY: "newapikey",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
mock_pythonkuma.metrics.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://uptime.example.org:3001/",
CONF_VERIFY_SSL: False,
CONF_API_KEY: "newapikey",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data == {
CONF_URL: "https://uptime.example.org:3001/",
CONF_VERIFY_SSL: False,
CONF_API_KEY: "newapikey",
}
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_hassio_addon_discovery(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_pythonkuma: AsyncMock,
) -> None:
"""Test config flow initiated by Supervisor."""
mock_pythonkuma.metrics.side_effect = [UptimeKumaAuthenticationException, None]
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=ADDON_SERVICE_INFO,
context={"source": SOURCE_HASSIO},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "hassio_confirm"
assert result["description_placeholders"] == {"addon": "Uptime Kuma"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "apikey"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "a0d7b954_uptime-kuma"
assert result["data"] == {
CONF_URL: "http://localhost:3001/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_hassio_addon_discovery_confirm_only(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
) -> None:
"""Test config flow initiated by Supervisor.
Config flow will first try to configure without authentication and if it
fails will show the form.
"""
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=ADDON_SERVICE_INFO,
context={"source": SOURCE_HASSIO},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "hassio_confirm"
assert result["description_placeholders"] == {"addon": "Uptime Kuma"}
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "a0d7b954_uptime-kuma"
assert result["data"] == {
CONF_URL: "http://localhost:3001/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: None,
}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_hassio_addon_discovery_already_configured(
hass: HomeAssistant,
) -> None:
"""Test config flow initiated by Supervisor."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_URL: "http://localhost:3001/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
},
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=ADDON_SERVICE_INFO,
context={"source": SOURCE_HASSIO},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("raise_error", "text_error"),
[
(UptimeKumaConnectionException, "cannot_connect"),
(UptimeKumaAuthenticationException, "invalid_auth"),
(UptimeKumaParseException, "invalid_data"),
(ValueError, "unknown"),
],
)
async def test_hassio_addon_discovery_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_pythonkuma: AsyncMock,
raise_error: Exception,
text_error: str,
) -> None:
"""Test we handle errors and recover."""
mock_pythonkuma.metrics.side_effect = UptimeKumaAuthenticationException
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=ADDON_SERVICE_INFO,
context={"source": SOURCE_HASSIO},
)
mock_pythonkuma.metrics.side_effect = raise_error
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "apikey"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
mock_pythonkuma.metrics.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "apikey"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "a0d7b954_uptime-kuma"
assert result["data"] == {
CONF_URL: "http://localhost:3001/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_hassio_addon_discovery_ignored(
hass: HomeAssistant,
) -> None:
"""Test we abort discovery flow if discovery was ignored."""
MockConfigEntry(
domain=DOMAIN,
source=SOURCE_IGNORE,
data={},
entry_id="123456789",
unique_id="1234",
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=ADDON_SERVICE_INFO,
context={"source": SOURCE_HASSIO},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_hassio_addon_discovery_update_info(
hass: HomeAssistant,
) -> None:
"""Test we abort discovery flow if already configured and we update from discovery info."""
entry = MockConfigEntry(
domain=DOMAIN,
title="a0d7b954_uptime-kuma",
data={
CONF_URL: "http://localhost:80/",
CONF_VERIFY_SSL: True,
CONF_API_KEY: "apikey",
},
entry_id="123456789",
unique_id="1234",
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=ADDON_SERVICE_INFO,
context={"source": SOURCE_HASSIO},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert entry.data[CONF_URL] == "http://localhost:3001/"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/uptime_kuma/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 405,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/uptime_kuma/test_diagnostics.py | """Tests Uptime Kuma diagnostics platform."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert (
await get_diagnostics_for_config_entry(hass, hass_client, config_entry)
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/uptime_kuma/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/uptime_kuma/test_init.py | """Tests for the Uptime Kuma integration."""
from unittest.mock import AsyncMock
import pytest
from pythonkuma import (
UptimeKumaAuthenticationException,
UptimeKumaException,
UptimeKumaParseException,
)
from homeassistant.components.uptime_kuma.const import DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_entry_setup_unload(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test integration setup and unload."""
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(config_entry.entry_id)
assert config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
("exception", "state"),
[
(UptimeKumaAuthenticationException, ConfigEntryState.SETUP_ERROR),
(UptimeKumaException, ConfigEntryState.SETUP_RETRY),
(UptimeKumaParseException, ConfigEntryState.SETUP_RETRY),
],
)
async def test_config_entry_not_ready(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_pythonkuma: AsyncMock,
exception: Exception,
state: ConfigEntryState,
) -> None:
"""Test config entry not ready."""
mock_pythonkuma.metrics.side_effect = exception
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is state
async def test_config_reauth_flow(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_pythonkuma: AsyncMock,
) -> None:
"""Test config entry auth error starts reauth flow."""
mock_pythonkuma.metrics.side_effect = UptimeKumaAuthenticationException
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
flow = flows[0]
assert flow.get("step_id") == "reauth_confirm"
assert flow.get("handler") == DOMAIN
assert "context" in flow
assert flow["context"].get("source") == SOURCE_REAUTH
assert flow["context"].get("entry_id") == config_entry.entry_id
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_remove_stale_device(
hass: HomeAssistant,
config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test we can remove a device that is not in the coordinator data."""
assert await async_setup_component(hass, "config", {})
ws_client = await hass_ws_client(hass)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, "123456789_1")}
)
config_entry.runtime_data.data.pop(1)
response = await ws_client.remove_device(device_entry.id, config_entry.entry_id)
assert response["success"]
assert (
device_registry.async_get_device(identifiers={(DOMAIN, "123456789_1")}) is None
)
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_remove_current_device(
hass: HomeAssistant,
config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test we cannot remove a device if it is still active."""
assert await async_setup_component(hass, "config", {})
ws_client = await hass_ws_client(hass)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, "123456789_1")}
)
response = await ws_client.remove_device(device_entry.id, config_entry.entry_id)
assert response["success"] is False
assert device_registry.async_get_device(identifiers={(DOMAIN, "123456789_1")})
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_remove_entry_device(
hass: HomeAssistant,
config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test we cannot remove the device with the update entity."""
assert await async_setup_component(hass, "config", {})
ws_client = await hass_ws_client(hass)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "123456789")})
response = await ws_client.remove_device(device_entry.id, config_entry.entry_id)
assert response["success"] is False
assert device_registry.async_get_device(identifiers={(DOMAIN, "123456789")})
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/uptime_kuma/test_init.py",
"license": "Apache License 2.0",
"lines": 127,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/uptime_kuma/test_sensor.py | """Test for Uptime Kuma sensor platform."""
from collections.abc import Generator
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from pythonkuma import MonitorStatus, UptimeKumaMonitor, UptimeKumaVersion
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.uptime_kuma.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.fixture(autouse=True)
def sensor_only() -> Generator[None]:
"""Enable only the sensor platform."""
with patch(
"homeassistant.components.uptime_kuma._PLATFORMS",
[Platform.SENSOR],
):
yield
@pytest.mark.usefixtures("mock_pythonkuma", "entity_registry_enabled_by_default")
async def test_setup(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Snapshot test states of sensor platform."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_migrate_unique_id(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_pythonkuma: AsyncMock,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
device_registry: dr.DeviceRegistry,
) -> None:
"""Snapshot test states of sensor platform."""
mock_pythonkuma.metrics.return_value = {
"Monitor": UptimeKumaMonitor(
monitor_name="Monitor",
monitor_hostname="null",
monitor_port="null",
monitor_status=MonitorStatus.UP,
monitor_url="test",
monitor_tags=["tag1", "tag2:value"],
)
}
mock_pythonkuma.version = UptimeKumaVersion(
version="1.23.16", major="1", minor="23", patch="16"
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert (entity := entity_registry.async_get("sensor.monitor_status"))
assert entity.unique_id == "123456789_Monitor_status"
mock_pythonkuma.metrics.return_value = {
1: UptimeKumaMonitor(
monitor_id=1,
monitor_name="Monitor",
monitor_hostname="null",
monitor_port="null",
monitor_status=MonitorStatus.UP,
monitor_url="test",
monitor_tags=["tag1", "tag2:value"],
)
}
mock_pythonkuma.version = UptimeKumaVersion(
version="2.0.2", major="2", minor="0", patch="2"
)
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (entity := entity_registry.async_get("sensor.monitor_status"))
assert entity.unique_id == "123456789_1_status"
assert (
device := device_registry.async_get_device(
identifiers={(DOMAIN, f"{entity.config_entry_id}_1")}
)
)
assert device.sw_version == "2.0.2"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/uptime_kuma/test_sensor.py",
"license": "Apache License 2.0",
"lines": 90,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/uptime_kuma/test_update.py | """Test the Uptime Kuma update platform."""
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
import pytest
from pythonkuma import UpdateException
from syrupy.assertion import SnapshotAssertion
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
from tests.typing import WebSocketGenerator
@pytest.fixture(autouse=True)
async def update_only() -> AsyncGenerator[None]:
"""Enable only the update platform."""
with patch(
"homeassistant.components.uptime_kuma._PLATFORMS",
[Platform.UPDATE],
):
yield
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_update(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test the update platform."""
ws_client = await hass_ws_client(hass)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
await ws_client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.uptime_example_org_uptime_kuma_version",
}
)
result = await ws_client.receive_json()
assert result["result"] == "**RELEASE_NOTES**"
@pytest.mark.usefixtures("mock_pythonkuma")
async def test_update_unavailable(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_update_checker: AsyncMock,
) -> None:
"""Test update entity unavailable on error."""
mock_update_checker.latest_release.side_effect = UpdateException
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
state = hass.states.get("update.uptime_example_org_uptime_kuma_version")
assert state is not None
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/uptime_kuma/test_update.py",
"license": "Apache License 2.0",
"lines": 59,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/velux/test_binary_sensor.py | """Tests for the Velux binary sensor platform."""
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
import pytest
from pyvlx.exception import PyVLXException
from homeassistant.components.velux import DOMAIN
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceRegistry
from homeassistant.helpers.entity_registry import EntityRegistry
from . import update_polled_entities
from tests.common import MockConfigEntry
@pytest.fixture
def platform() -> Platform:
"""Fixture to specify platform to test."""
return Platform.BINARY_SENSOR
pytestmark = pytest.mark.usefixtures("setup_integration")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_rain_sensor_state(
hass: HomeAssistant,
mock_window: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the rain sensor."""
test_entity_id = "binary_sensor.test_window_rain_sensor"
# simulate no rain detected
await update_polled_entities(hass, freezer)
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_OFF
# simulate rain detected (Velux GPU reports 100)
mock_window.get_limitation.return_value.min_value = 100
await update_polled_entities(hass, freezer)
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_ON
# simulate rain detected (most Velux models report 93)
mock_window.get_limitation.return_value.min_value = 93
await update_polled_entities(hass, freezer)
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_ON
# simulate rain detected (other Velux models report 89)
mock_window.get_limitation.return_value.min_value = 89
await update_polled_entities(hass, freezer)
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_ON
# simulate other limits which do not indicate rain detected
mock_window.get_limitation.return_value.min_value = 88
await update_polled_entities(hass, freezer)
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_OFF
# simulate no rain detected again
mock_window.get_limitation.return_value.min_value = 0
await update_polled_entities(hass, freezer)
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_OFF
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_rain_sensor_device_association(
hass: HomeAssistant,
mock_window: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
) -> None:
"""Test the rain sensor is properly associated with its device."""
test_entity_id = "binary_sensor.test_window_rain_sensor"
# Verify entity exists
state = hass.states.get(test_entity_id)
assert state is not None
# Get entity entry
entity_entry = entity_registry.async_get(test_entity_id)
assert entity_entry is not None
assert entity_entry.device_id is not None
# Get device entry
device_entry = device_registry.async_get(entity_entry.device_id)
assert device_entry is not None
# Verify device has correct identifiers
assert ("velux", mock_window.serial_number) in device_entry.identifiers
assert device_entry.name == mock_window.name
# Verify via_device is gateway
assert device_entry.via_device_id is not None
via_device_entry = device_registry.async_get(device_entry.via_device_id)
assert via_device_entry is not None
assert via_device_entry.identifiers == {
(DOMAIN, f"gateway_{mock_config_entry.entry_id}")
}
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_rain_sensor_unavailability(
hass: HomeAssistant,
mock_window: MagicMock,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test rain sensor becomes unavailable on errors and logs appropriately."""
test_entity_id = "binary_sensor.test_window_rain_sensor"
# Entity should be available initially
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state != STATE_UNAVAILABLE
# Simulate communication error
mock_window.get_limitation.side_effect = PyVLXException("Connection failed")
await update_polled_entities(hass, freezer)
# Entity should now be unavailable
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_UNAVAILABLE
# Verify unavailability was logged once
assert (
"Rain sensor binary_sensor.test_window_rain_sensor is unavailable"
in caplog.text
)
assert "Connection failed" in caplog.text
caplog.clear()
# Another update attempt should not log again (already logged)
await update_polled_entities(hass, freezer)
state = hass.states.get(test_entity_id)
assert state.state == STATE_UNAVAILABLE
assert "is unavailable" not in caplog.text
caplog.clear()
# Simulate recovery
mock_window.get_limitation.side_effect = None
mock_window.get_limitation.return_value.min_value = 0
await update_polled_entities(hass, freezer)
# Entity should be available again
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_OFF
# Verify recovery was logged
assert (
"Rain sensor binary_sensor.test_window_rain_sensor is back online"
in caplog.text
)
caplog.clear()
# Another successful update should not log recovery again
await update_polled_entities(hass, freezer)
state = hass.states.get(test_entity_id)
assert state.state == STATE_OFF
assert "back online" not in caplog.text
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/velux/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 142,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/volvo/const.py | """Define const for Volvo unit tests."""
CLIENT_ID = "1234"
CLIENT_SECRET = "5678"
DEFAULT_API_KEY = "abcdef0123456879abcdef"
DEFAULT_MODEL = "xc40_electric_2024"
DEFAULT_VIN = "YV1ABCDEFG1234567"
MOCK_ACCESS_TOKEN = "mock-access-token"
REDIRECT_URI = "https://example.com/auth/external/callback"
SERVER_TOKEN_RESPONSE = {
"refresh_token": "server-refresh-token",
"access_token": "server-access-token",
"token_type": "Bearer",
"expires_in": 60,
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvo/const.py",
"license": "Apache License 2.0",
"lines": 14,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/volvo/test_config_flow.py | """Test the Volvo config flow."""
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
import pytest
from volvocarsapi.api import VolvoCarsApi
from volvocarsapi.auth import AUTHORIZE_URL, TOKEN_URL
from volvocarsapi.models import VolvoApiException, VolvoCarsVehicle
from volvocarsapi.scopes import ALL_SCOPES
from yarl import URL
from homeassistant import config_entries
from homeassistant.components.volvo.const import CONF_VIN, DOMAIN
from homeassistant.config_entries import ConfigFlowResult
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_API_KEY, CONF_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import config_entry_oauth2_flow
from . import async_load_fixture_as_json, configure_mock
from .const import (
CLIENT_ID,
DEFAULT_API_KEY,
DEFAULT_MODEL,
DEFAULT_VIN,
REDIRECT_URI,
SERVER_TOKEN_RESPONSE,
)
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
@pytest.mark.usefixtures("current_request_with_host")
async def test_full_flow(
hass: HomeAssistant,
config_flow: ConfigFlowResult,
mock_setup_entry: AsyncMock,
mock_config_flow_api: VolvoCarsApi,
) -> None:
"""Check full flow."""
result = await _async_run_flow_to_completion(
hass, config_flow, mock_config_flow_api
)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert len(mock_setup_entry.mock_calls) == 1
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"][CONF_API_KEY] == DEFAULT_API_KEY
assert result["data"][CONF_VIN] == DEFAULT_VIN
assert result["context"]["unique_id"] == DEFAULT_VIN
@pytest.mark.usefixtures("current_request_with_host")
async def test_single_vin_flow(
hass: HomeAssistant,
config_flow: ConfigFlowResult,
mock_setup_entry: AsyncMock,
mock_config_flow_api: VolvoCarsApi,
) -> None:
"""Check flow where API returns a single VIN."""
_configure_mock_vehicles_success(mock_config_flow_api, single_vin=True)
# Since there is only one VIN, the api_key step is the only step
result = await hass.config_entries.flow.async_configure(config_flow["flow_id"])
assert result["step_id"] == "api_key"
result = await hass.config_entries.flow.async_configure(
config_flow["flow_id"], {CONF_API_KEY: "abcdef0123456879abcdef"}
)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert len(mock_setup_entry.mock_calls) == 1
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(("api_key_failure"), [pytest.param(True), pytest.param(False)])
@pytest.mark.usefixtures("current_request_with_host")
async def test_reauth_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
hass_client_no_auth: ClientSessionGenerator,
mock_config_flow_api: VolvoCarsApi,
api_key_failure: bool,
) -> None:
"""Test reauthentication flow."""
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": REDIRECT_URI,
},
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
result = await _async_run_flow_to_completion(
hass,
result,
mock_config_flow_api,
has_vin_step=False,
is_reauth=True,
api_key_failure=api_key_failure,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
@pytest.mark.usefixtures("current_request_with_host")
async def test_reauth_no_stale_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
hass_client_no_auth: ClientSessionGenerator,
mock_config_flow_api: VolvoCarsApi,
) -> None:
"""Test if reauthentication flow does not use stale data."""
old_access_token = mock_config_entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN]
with patch(
"homeassistant.components.volvo.config_flow._create_volvo_cars_api",
return_value=mock_config_flow_api,
) as mock_create_volvo_cars_api:
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": REDIRECT_URI,
},
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
result = await _async_run_flow_to_completion(
hass,
result,
mock_config_flow_api,
has_vin_step=False,
is_reauth=True,
)
assert mock_create_volvo_cars_api.called
call = mock_create_volvo_cars_api.call_args_list[0]
access_token_arg = call.args[1]
assert old_access_token != access_token_arg
async def test_reconfigure_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_config_flow_api: VolvoCarsApi,
) -> None:
"""Test reconfiguration flow."""
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "api_key"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_KEY: "abcdef0123456879abcdef"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
@pytest.mark.usefixtures("current_request_with_host", "mock_config_entry")
async def test_unique_id_flow(
hass: HomeAssistant,
config_flow: ConfigFlowResult,
mock_config_flow_api: VolvoCarsApi,
) -> None:
"""Test unique ID flow."""
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
result = await _async_run_flow_to_completion(
hass, config_flow, mock_config_flow_api
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
@pytest.mark.usefixtures("current_request_with_host")
async def test_api_failure_flow(
hass: HomeAssistant,
config_flow: ConfigFlowResult,
mock_config_flow_api: VolvoCarsApi,
) -> None:
"""Check flow where API throws an exception."""
_configure_mock_vehicles_failure(mock_config_flow_api)
result = await hass.config_entries.flow.async_configure(config_flow["flow_id"])
assert result["step_id"] == "api_key"
result = await hass.config_entries.flow.async_configure(
config_flow["flow_id"], {CONF_API_KEY: "abcdef0123456879abcdef"}
)
assert len(hass.config_entries.async_entries(DOMAIN)) == 0
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "cannot_load_vehicles"
assert result["step_id"] == "api_key"
result = await _async_run_flow_to_completion(
hass, result, mock_config_flow_api, configure=False
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.fixture
async def config_flow(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
) -> config_entries.ConfigFlowResult:
"""Initialize a new config flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": REDIRECT_URI,
},
)
result_url = URL(result["url"])
assert f"{result_url.origin()}{result_url.path}" == AUTHORIZE_URL
assert result_url.query["response_type"] == "code"
assert result_url.query["client_id"] == CLIENT_ID
assert result_url.query["redirect_uri"] == REDIRECT_URI
assert result_url.query["state"] == state
assert result_url.query["code_challenge"]
assert result_url.query["code_challenge_method"] == "S256"
assert result_url.query["scope"] == " ".join(ALL_SCOPES)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
return result
@pytest.fixture
async def mock_config_flow_api(hass: HomeAssistant) -> AsyncGenerator[AsyncMock]:
"""Mock API used in config flow."""
with patch(
"homeassistant.components.volvo.config_flow.VolvoCarsApi",
autospec=True,
) as mock_api:
api: VolvoCarsApi = mock_api.return_value
_configure_mock_vehicles_success(api)
vehicle_data = await async_load_fixture_as_json(hass, "vehicle", DEFAULT_MODEL)
configure_mock(
api.async_get_vehicle_details,
return_value=VolvoCarsVehicle.from_dict(vehicle_data),
)
yield api
@pytest.fixture(autouse=True)
async def mock_auth_client(
aioclient_mock: AiohttpClientMocker,
) -> AsyncGenerator[AsyncMock]:
"""Mock auth requests."""
aioclient_mock.clear_requests()
aioclient_mock.post(
TOKEN_URL,
json=SERVER_TOKEN_RESPONSE,
)
async def _async_run_flow_to_completion(
hass: HomeAssistant,
config_flow: ConfigFlowResult,
mock_config_flow_api: VolvoCarsApi,
*,
configure: bool = True,
has_vin_step: bool = True,
is_reauth: bool = False,
api_key_failure: bool = False,
) -> ConfigFlowResult:
if configure:
if api_key_failure:
_configure_mock_vehicles_failure(mock_config_flow_api)
config_flow = await hass.config_entries.flow.async_configure(
config_flow["flow_id"]
)
if is_reauth and not api_key_failure:
return config_flow
assert config_flow["type"] is FlowResultType.FORM
assert config_flow["step_id"] == "api_key"
_configure_mock_vehicles_success(mock_config_flow_api)
config_flow = await hass.config_entries.flow.async_configure(
config_flow["flow_id"], {CONF_API_KEY: "abcdef0123456879abcdef"}
)
if has_vin_step:
assert config_flow["type"] is FlowResultType.FORM
assert config_flow["step_id"] == "vin"
config_flow = await hass.config_entries.flow.async_configure(
config_flow["flow_id"], {CONF_VIN: DEFAULT_VIN}
)
return config_flow
def _configure_mock_vehicles_success(
mock_config_flow_api: VolvoCarsApi, single_vin: bool = False
) -> None:
vins = [{"vin": DEFAULT_VIN}]
if not single_vin:
vins.append({"vin": "YV10000000AAAAAAA"})
configure_mock(mock_config_flow_api.async_get_vehicles, return_value=vins)
def _configure_mock_vehicles_failure(mock_config_flow_api: VolvoCarsApi) -> None:
configure_mock(
mock_config_flow_api.async_get_vehicles, side_effect=VolvoApiException()
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvo/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 283,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/volvo/test_coordinator.py | """Test Volvo coordinator."""
from collections.abc import Awaitable, Callable
from datetime import timedelta
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
import pytest
from volvocarsapi.api import VolvoCarsApi
from volvocarsapi.models import (
VolvoApiException,
VolvoAuthException,
VolvoCarsValueField,
)
from homeassistant.components.volvo.const import DOMAIN
from homeassistant.components.volvo.coordinator import VERY_SLOW_INTERVAL
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from . import configure_mock
from tests.common import async_fire_time_changed
@pytest.mark.freeze_time("2025-05-31T10:00:00+00:00")
async def test_coordinator_update(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test coordinator update."""
assert await setup_integration()
sensor_id = "sensor.volvo_xc40_odometer"
interval = timedelta(minutes=VERY_SLOW_INTERVAL)
value = {"odometer": VolvoCarsValueField(value=30000, unit="km")}
mock_method: AsyncMock = mock_api.async_get_odometer
state = hass.states.get(sensor_id)
assert state.state == "30000"
value["odometer"].value = 30001
configure_mock(mock_method, return_value=value)
freezer.tick(interval)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_method.call_count == 1
state = hass.states.get(sensor_id)
assert state.state == "30001"
@pytest.mark.freeze_time("2025-05-31T10:00:00+00:00")
async def test_coordinator_with_errors(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test coordinator with errors."""
assert await setup_integration()
sensor_id = "sensor.volvo_xc40_odometer"
interval = timedelta(minutes=VERY_SLOW_INTERVAL)
value = {"odometer": VolvoCarsValueField(value=30000, unit="km")}
mock_method: AsyncMock = mock_api.async_get_odometer
state = hass.states.get(sensor_id)
assert state.state == "30000"
configure_mock(mock_method, side_effect=VolvoApiException())
freezer.tick(interval)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_method.call_count == 1
state = hass.states.get(sensor_id)
assert state.state == STATE_UNAVAILABLE
configure_mock(mock_method, return_value=value)
freezer.tick(interval)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_method.call_count == 1
state = hass.states.get(sensor_id)
assert state.state == "30000"
configure_mock(mock_method, side_effect=Exception())
freezer.tick(interval)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_method.call_count == 1
state = hass.states.get(sensor_id)
assert state.state == STATE_UNAVAILABLE
configure_mock(mock_method, return_value=value)
freezer.tick(interval)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_method.call_count == 1
state = hass.states.get(sensor_id)
assert state.state == "30000"
configure_mock(mock_method, side_effect=VolvoAuthException())
freezer.tick(interval)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_method.call_count == 1
state = hass.states.get(sensor_id)
assert state.state == STATE_UNAVAILABLE
@pytest.mark.freeze_time("2025-05-31T10:00:00+00:00")
async def test_update_coordinator_all_error(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test API returning error for all calls during coordinator update."""
assert await setup_integration()
_mock_api_failure(mock_api)
freezer.tick(timedelta(minutes=VERY_SLOW_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
for state in hass.states.async_all(domain_filter=DOMAIN):
if state.domain != "button":
assert state.state == STATE_UNAVAILABLE
def _mock_api_failure(mock_api: VolvoCarsApi) -> AsyncMock:
"""Mock the Volvo API so that it raises an exception for all calls."""
mock_api.async_get_brakes_status.side_effect = VolvoApiException()
mock_api.async_get_command_accessibility.side_effect = VolvoApiException()
mock_api.async_get_commands.side_effect = VolvoApiException()
mock_api.async_get_diagnostics.side_effect = VolvoApiException()
mock_api.async_get_doors_status.side_effect = VolvoApiException()
mock_api.async_get_energy_capabilities.side_effect = VolvoApiException()
mock_api.async_get_energy_state.side_effect = VolvoApiException()
mock_api.async_get_engine_status.side_effect = VolvoApiException()
mock_api.async_get_engine_warnings.side_effect = VolvoApiException()
mock_api.async_get_fuel_status.side_effect = VolvoApiException()
mock_api.async_get_location.side_effect = VolvoApiException()
mock_api.async_get_odometer.side_effect = VolvoApiException()
mock_api.async_get_recharge_status.side_effect = VolvoApiException()
mock_api.async_get_statistics.side_effect = VolvoApiException()
mock_api.async_get_tyre_states.side_effect = VolvoApiException()
mock_api.async_get_warnings.side_effect = VolvoApiException()
mock_api.async_get_window_states.side_effect = VolvoApiException()
return mock_api
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvo/test_coordinator.py",
"license": "Apache License 2.0",
"lines": 127,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/volvo/test_init.py | """Test Volvo init."""
from collections.abc import Awaitable, Callable
from http import HTTPStatus
from unittest.mock import AsyncMock, patch
import pytest
from volvocarsapi.api import VolvoCarsApi
from volvocarsapi.auth import TOKEN_URL
from volvocarsapi.models import VolvoAuthException
from homeassistant.components.volvo.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
)
from . import configure_mock
from .const import MOCK_ACCESS_TOKEN, SERVER_TOKEN_RESPONSE
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.mark.usefixtures("mock_api")
async def test_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
setup_integration: Callable[[], Awaitable[bool]],
) -> None:
"""Test setting up the integration."""
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
assert await setup_integration()
assert mock_config_entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.usefixtures("mock_api")
async def test_token_refresh_success(
mock_config_entry: MockConfigEntry,
aioclient_mock: AiohttpClientMocker,
setup_integration: Callable[[], Awaitable[bool]],
) -> None:
"""Test where token refresh succeeds."""
assert mock_config_entry.data[CONF_TOKEN]["access_token"] == MOCK_ACCESS_TOKEN
assert await setup_integration()
assert mock_config_entry.state is ConfigEntryState.LOADED
# Verify token
assert len(aioclient_mock.mock_calls) == 1
assert (
mock_config_entry.data[CONF_TOKEN]["access_token"]
== SERVER_TOKEN_RESPONSE["access_token"]
)
@pytest.mark.parametrize(
("token_response"),
[
(HTTPStatus.INTERNAL_SERVER_ERROR),
(HTTPStatus.NOT_FOUND),
],
)
async def test_token_refresh_fail(
mock_config_entry: MockConfigEntry,
aioclient_mock: AiohttpClientMocker,
setup_integration: Callable[[], Awaitable[bool]],
token_response: HTTPStatus,
) -> None:
"""Test where token refresh fails."""
aioclient_mock.post(TOKEN_URL, status=token_response)
assert not await setup_integration()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
@pytest.mark.parametrize(
("token_response"),
[
(HTTPStatus.BAD_REQUEST),
(HTTPStatus.FORBIDDEN),
],
)
async def test_token_refresh_reauth(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
aioclient_mock: AiohttpClientMocker,
setup_integration: Callable[[], Awaitable[bool]],
token_response: HTTPStatus,
) -> None:
"""Test where token refresh indicates unauthorized."""
aioclient_mock.post(TOKEN_URL, status=token_response)
assert not await setup_integration()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert flows
assert flows[0]["handler"] == DOMAIN
assert flows[0]["step_id"] == "reauth_confirm"
async def test_no_vehicle(
mock_config_entry: MockConfigEntry,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test no vehicle during coordinator setup."""
mock_method: AsyncMock = mock_api.async_get_vehicle_details
configure_mock(mock_method, return_value=None, side_effect=None)
assert not await setup_integration()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_vehicle_auth_failure(
mock_config_entry: MockConfigEntry,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test auth failure during coordinator setup."""
mock_method: AsyncMock = mock_api.async_get_vehicle_details
configure_mock(mock_method, return_value=None, side_effect=VolvoAuthException())
assert not await setup_integration()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_oauth_implementation_not_available(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that unavailable OAuth implementation raises ConfigEntryNotReady."""
mock_config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.volvo.async_get_config_entry_implementation",
side_effect=ImplementationUnavailableError,
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvo/test_init.py",
"license": "Apache License 2.0",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/volvo/test_sensor.py | """Test Volvo sensors."""
from collections.abc import Awaitable, Callable
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from volvocarsapi.api import VolvoCarsApi
from volvocarsapi.models import (
VolvoCarsErrorResult,
VolvoCarsValue,
VolvoCarsValueField,
)
from homeassistant.components.volvo.const import DOMAIN
from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("mock_api", "full_model")
@pytest.mark.parametrize(
"full_model",
[
"ex30_2024",
"s90_diesel_2018",
"xc40_electric_2024",
"xc60_phev_2020",
"xc90_petrol_2019",
"xc90_phev_2024",
],
)
async def test_sensor(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test sensor."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("mock_api", "full_model")
@pytest.mark.parametrize(
"full_model",
["xc40_electric_2024"],
)
async def test_distance_to_empty_battery(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
) -> None:
"""Test using `distanceToEmptyBattery` instead of `electricRange`."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
assert hass.states.get("sensor.volvo_xc40_distance_to_empty_battery").state == "250"
@pytest.mark.usefixtures("mock_api", "full_model")
@pytest.mark.parametrize(
("full_model", "short_model"),
[("ex30_2024", "ex30"), ("xc60_phev_2020", "xc60")],
)
async def test_skip_invalid_api_fields(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
short_model: str,
) -> None:
"""Test if invalid values are not creating a sensor."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
assert not hass.states.get(f"sensor.volvo_{short_model}_charging_current_limit")
@pytest.mark.usefixtures("mock_api", "full_model")
@pytest.mark.parametrize(
"full_model",
["ex30_2024"],
)
async def test_charging_power_value(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
) -> None:
"""Test if charging_power_value is zero if supported, but not charging."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
assert hass.states.get("sensor.volvo_ex30_charging_power").state == "0"
@pytest.mark.usefixtures("mock_api", "full_model")
@pytest.mark.parametrize(
"full_model",
[
"ex30_2024",
"s90_diesel_2018",
"xc40_electric_2024",
"xc60_phev_2020",
"xc90_petrol_2019",
"xc90_phev_2024",
],
)
async def test_unique_ids(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test sensor for unique id's."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
assert f"Platform {DOMAIN} does not generate unique IDs" not in caplog.text
async def test_availability_status_reason(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test availability_status entity returns unavailable reason."""
mock_method: AsyncMock = mock_api.async_get_command_accessibility
mock_method.return_value["availabilityStatus"] = VolvoCarsValue(
value="UNAVAILABLE", extra_data={"unavailable_reason": "no_internet"}
)
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
state = hass.states.get("sensor.volvo_xc40_car_connection")
assert state.state == "no_internet"
async def test_time_to_service_non_value_field(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test time_to_service entity with non-VolvoCarsValueField returns 0."""
mock_method: AsyncMock = mock_api.async_get_diagnostics
mock_method.return_value["timeToService"] = VolvoCarsErrorResult(message="invalid")
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
state = hass.states.get("sensor.volvo_xc40_time_to_service")
assert state.state == "0"
async def test_time_to_service_months_conversion(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test time_to_service entity converts months to days."""
mock_method: AsyncMock = mock_api.async_get_diagnostics
mock_method.return_value["timeToService"] = VolvoCarsValueField(
value=3, unit="months"
)
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
state = hass.states.get("sensor.volvo_xc40_time_to_service")
assert state.state == "90"
async def test_charging_power_value_fallback(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
) -> None:
"""Test charging_power entity returns 0 for invalid field types."""
mock_method: AsyncMock = mock_api.async_get_energy_state
mock_method.return_value["chargingPower"] = VolvoCarsErrorResult(message="invalid")
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
state = hass.states.get("sensor.volvo_xc40_charging_power")
assert state.state == "0"
async def test_charging_power_status_unknown_value(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test charging_power_status entity with unknown status logs warning."""
mock_method: AsyncMock = mock_api.async_get_energy_state
mock_method.return_value["chargerPowerStatus"] = VolvoCarsValue(
value="unknown_status"
)
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.SENSOR]):
assert await setup_integration()
state = hass.states.get("sensor.volvo_xc40_charging_power_status")
assert state.state == STATE_UNKNOWN
assert "Unknown value 'unknown_status' for charging_power_status" in caplog.text
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvo/test_sensor.py",
"license": "Apache License 2.0",
"lines": 168,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/waqi/test_init.py | """Test the World Air Quality Index (WAQI) initialization."""
from typing import Any
from unittest.mock import AsyncMock, patch
from aiowaqi import WAQIError
import pytest
from homeassistant.components.waqi import DOMAIN
from homeassistant.components.waqi.const import CONF_STATION_NUMBER
from homeassistant.config_entries import ConfigEntryDisabler, ConfigEntryState
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.device_registry import DeviceEntryDisabler
from homeassistant.helpers.entity_registry import RegistryEntryDisabler
from . import setup_integration
from tests.common import MockConfigEntry
async def test_setup_failed(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_waqi: AsyncMock,
) -> None:
"""Test setup failure due to API error."""
mock_waqi.get_by_station_number.side_effect = WAQIError("API error")
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_migration_from_v1(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test migration from version 1 to version 2."""
# Create a v1 config entry with conversation options and an entity
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_API_KEY: "1234", CONF_STATION_NUMBER: 4584},
version=1,
unique_id="4584",
title="de Jongweg, Utrecht",
)
mock_config_entry.add_to_hass(hass)
mock_config_entry_2 = MockConfigEntry(
domain=DOMAIN,
data={CONF_API_KEY: "1234", CONF_STATION_NUMBER: 4585},
version=1,
unique_id="4585",
title="Not de Jongweg, Utrecht",
)
mock_config_entry_2.add_to_hass(hass)
device_1 = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, "4584")},
name="de Jongweg, Utrecht",
entry_type=dr.DeviceEntryType.SERVICE,
)
entity_registry.async_get_or_create(
"sensor",
DOMAIN,
"4584_air_quality",
config_entry=mock_config_entry,
device_id=device_1.id,
suggested_object_id="de_jongweg_utrecht",
)
device_2 = device_registry.async_get_or_create(
config_entry_id=mock_config_entry_2.entry_id,
identifiers={(DOMAIN, "4585")},
name="Not de Jongweg, Utrecht",
entry_type=dr.DeviceEntryType.SERVICE,
)
entity_registry.async_get_or_create(
"sensor",
DOMAIN,
"4585_air_quality",
config_entry=mock_config_entry_2,
device_id=device_2.id,
suggested_object_id="not_de_jongweg_utrecht",
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
entry = entries[0]
assert entry.version == 2
assert entry.minor_version == 1
assert not entry.options
assert entry.title == "WAQI"
assert len(entry.subentries) == 2
subentry = list(entry.subentries.values())[0]
assert subentry.subentry_type == "station"
assert subentry.data[CONF_STATION_NUMBER] == 4584
assert subentry.unique_id == "4584"
assert subentry.title == "de Jongweg, Utrecht"
entity = entity_registry.async_get("sensor.de_jongweg_utrecht")
assert entity.unique_id == "4584_air_quality"
assert entity.config_subentry_id == subentry.subentry_id
assert entity.config_entry_id == entry.entry_id
assert (device := device_registry.async_get_device(identifiers={(DOMAIN, "4584")}))
assert device.identifiers == {(DOMAIN, "4584")}
assert device.id == device_1.id
assert device.config_entries == {mock_config_entry.entry_id}
assert device.config_entries_subentries == {
mock_config_entry.entry_id: {subentry.subentry_id}
}
subentry = list(entry.subentries.values())[1]
assert subentry.subentry_type == "station"
assert subentry.data[CONF_STATION_NUMBER] == 4585
assert subentry.unique_id == "4585"
assert subentry.title == "Not de Jongweg, Utrecht"
entity = entity_registry.async_get("sensor.not_de_jongweg_utrecht")
assert entity.unique_id == "4585_air_quality"
assert entity.config_subentry_id == subentry.subentry_id
assert entity.config_entry_id == entry.entry_id
assert (device := device_registry.async_get_device(identifiers={(DOMAIN, "4585")}))
assert device.identifiers == {(DOMAIN, "4585")}
assert device.id == device_2.id
assert device.config_entries == {mock_config_entry.entry_id}
assert device.config_entries_subentries == {
mock_config_entry.entry_id: {subentry.subentry_id}
}
@pytest.mark.parametrize(
(
"config_entry_disabled_by",
"merged_config_entry_disabled_by",
"sensor_subentry_data",
"main_config_entry",
),
[
(
[ConfigEntryDisabler.USER, None],
None,
[
{
"sensor_entity_id": "sensor.not_de_jongweg_utrecht_air_quality_index",
"device_disabled_by": None,
"entity_disabled_by": None,
"device": 1,
},
{
"sensor_entity_id": "sensor.de_jongweg_utrecht_air_quality_index",
"device_disabled_by": DeviceEntryDisabler.USER,
"entity_disabled_by": RegistryEntryDisabler.DEVICE,
"device": 0,
},
],
1,
),
(
[None, ConfigEntryDisabler.USER],
None,
[
{
"sensor_entity_id": "sensor.de_jongweg_utrecht_air_quality_index",
"device_disabled_by": DeviceEntryDisabler.USER,
"entity_disabled_by": RegistryEntryDisabler.DEVICE,
"device": 0,
},
{
"sensor_entity_id": "sensor.not_de_jongweg_utrecht_air_quality_index",
"device_disabled_by": None,
"entity_disabled_by": None,
"device": 1,
},
],
0,
),
(
[ConfigEntryDisabler.USER, ConfigEntryDisabler.USER],
ConfigEntryDisabler.USER,
[
{
"sensor_entity_id": "sensor.de_jongweg_utrecht_air_quality_index",
"device_disabled_by": DeviceEntryDisabler.CONFIG_ENTRY,
"entity_disabled_by": RegistryEntryDisabler.CONFIG_ENTRY,
"device": 0,
},
{
"sensor_entity_id": "sensor.not_de_jongweg_utrecht_air_quality_index",
"device_disabled_by": DeviceEntryDisabler.CONFIG_ENTRY,
"entity_disabled_by": None,
"device": 1,
},
],
0,
),
],
)
async def test_migration_from_v1_disabled(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
config_entry_disabled_by: list[ConfigEntryDisabler | None],
merged_config_entry_disabled_by: ConfigEntryDisabler | None,
sensor_subentry_data: list[dict[str, Any]],
main_config_entry: int,
) -> None:
"""Test migration where the config entries are disabled."""
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_API_KEY: "1234", CONF_STATION_NUMBER: 4584},
version=1,
unique_id="4584",
title="de Jongweg, Utrecht",
disabled_by=config_entry_disabled_by[0],
)
mock_config_entry.add_to_hass(hass)
mock_config_entry_2 = MockConfigEntry(
domain=DOMAIN,
data={CONF_API_KEY: "1234", CONF_STATION_NUMBER: 4585},
version=1,
unique_id="4585",
title="Not de Jongweg, Utrecht",
disabled_by=config_entry_disabled_by[1],
)
mock_config_entry_2.add_to_hass(hass)
mock_config_entries = [mock_config_entry, mock_config_entry_2]
device_1 = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, mock_config_entry.unique_id)},
name=mock_config_entry.title,
entry_type=dr.DeviceEntryType.SERVICE,
disabled_by=DeviceEntryDisabler.CONFIG_ENTRY,
)
entity_registry.async_get_or_create(
"sensor",
DOMAIN,
mock_config_entry.unique_id,
config_entry=mock_config_entry,
device_id=device_1.id,
suggested_object_id="de_jongweg_utrecht_air_quality_index",
disabled_by=RegistryEntryDisabler.CONFIG_ENTRY,
)
device_2 = device_registry.async_get_or_create(
config_entry_id=mock_config_entry_2.entry_id,
identifiers={(DOMAIN, mock_config_entry_2.unique_id)},
name=mock_config_entry_2.title,
entry_type=dr.DeviceEntryType.SERVICE,
)
entity_registry.async_get_or_create(
"sensor",
DOMAIN,
mock_config_entry_2.unique_id,
config_entry=mock_config_entry_2,
device_id=device_2.id,
suggested_object_id="not_de_jongweg_utrecht_air_quality_index",
)
devices = [device_1, device_2]
# Run migration
with patch(
"homeassistant.components.waqi.async_setup_entry",
return_value=True,
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
entry = entries[0]
assert entry.disabled_by is merged_config_entry_disabled_by
assert entry.version == 2
assert entry.minor_version == 1
assert not entry.options
assert entry.title == "WAQI"
assert len(entry.subentries) == 2
station_subentries = [
subentry
for subentry in entry.subentries.values()
if subentry.subentry_type == "station"
]
assert len(station_subentries) == 2
for subentry in station_subentries:
assert subentry.data == {CONF_STATION_NUMBER: int(subentry.unique_id)}
assert "de Jongweg" in subentry.title
assert not device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry.entry_id)}
)
assert not device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry_2.entry_id)}
)
for idx, subentry in enumerate(station_subentries):
subentry_data = sensor_subentry_data[idx]
entity = entity_registry.async_get(subentry_data["sensor_entity_id"])
assert entity.unique_id == subentry.unique_id
assert entity.config_subentry_id == subentry.subentry_id
assert entity.config_entry_id == entry.entry_id
assert entity.disabled_by is subentry_data["entity_disabled_by"]
assert (
device := device_registry.async_get_device(
identifiers={(DOMAIN, subentry.unique_id)}
)
)
assert device.identifiers == {(DOMAIN, subentry.unique_id)}
assert device.id == devices[subentry_data["device"]].id
assert device.config_entries == {
mock_config_entries[main_config_entry].entry_id
}
assert device.config_entries_subentries == {
mock_config_entries[main_config_entry].entry_id: {subentry.subentry_id}
}
assert device.disabled_by is subentry_data["device_disabled_by"]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/waqi/test_init.py",
"license": "Apache License 2.0",
"lines": 297,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/weatherflow_cloud/test_coordinators.py | """Tests for the WeatherFlow Cloud coordinators."""
from unittest.mock import AsyncMock, Mock
from aiohttp import ClientResponseError
import pytest
from weatherflow4py.models.ws.types import EventType
from weatherflow4py.models.ws.websocket_request import (
ListenStartMessage,
RapidWindListenStartMessage,
)
from weatherflow4py.models.ws.websocket_response import (
EventDataRapidWind,
ObservationTempestWS,
RapidWindWS,
)
from homeassistant.components.weatherflow_cloud.coordinator import (
WeatherFlowCloudUpdateCoordinatorREST,
WeatherFlowObservationCoordinator,
WeatherFlowWindCoordinator,
)
from homeassistant.config_entries import ConfigEntryAuthFailed
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import UpdateFailed
from tests.common import MockConfigEntry
async def test_wind_coordinator_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_rest_api: AsyncMock,
mock_websocket_api: AsyncMock,
mock_stations_data: Mock,
) -> None:
"""Test wind coordinator setup."""
coordinator = WeatherFlowWindCoordinator(
hass=hass,
config_entry=mock_config_entry,
rest_api=mock_rest_api,
websocket_api=mock_websocket_api,
stations=mock_stations_data,
)
await coordinator.async_setup()
# Verify websocket setup
mock_websocket_api.connect.assert_called_once()
mock_websocket_api.register_callback.assert_called_once_with(
message_type=EventType.RAPID_WIND,
callback=coordinator._handle_websocket_message,
)
# In the refactored code, send_message is called for each device ID
assert mock_websocket_api.send_message.called
# Verify at least one message is of the correct type
call_args_list = mock_websocket_api.send_message.call_args_list
assert any(
isinstance(call.args[0], RapidWindListenStartMessage) for call in call_args_list
)
async def test_observation_coordinator_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_rest_api: AsyncMock,
mock_websocket_api: AsyncMock,
mock_stations_data: Mock,
) -> None:
"""Test observation coordinator setup."""
coordinator = WeatherFlowObservationCoordinator(
hass=hass,
config_entry=mock_config_entry,
rest_api=mock_rest_api,
websocket_api=mock_websocket_api,
stations=mock_stations_data,
)
await coordinator.async_setup()
# Verify websocket setup
mock_websocket_api.connect.assert_called_once()
mock_websocket_api.register_callback.assert_called_once_with(
message_type=EventType.OBSERVATION,
callback=coordinator._handle_websocket_message,
)
# In the refactored code, send_message is called for each device ID
assert mock_websocket_api.send_message.called
# Verify at least one message is of the correct type
call_args_list = mock_websocket_api.send_message.call_args_list
assert any(isinstance(call.args[0], ListenStartMessage) for call in call_args_list)
async def test_wind_coordinator_message_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_rest_api: AsyncMock,
mock_websocket_api: AsyncMock,
mock_stations_data: Mock,
) -> None:
"""Test wind coordinator message handling."""
coordinator = WeatherFlowWindCoordinator(
hass=hass,
config_entry=mock_config_entry,
rest_api=mock_rest_api,
websocket_api=mock_websocket_api,
stations=mock_stations_data,
)
# Create mock wind data
mock_wind_data = Mock(spec=EventDataRapidWind)
mock_message = Mock(spec=RapidWindWS)
# Use a device ID from the actual mock data
# The first device from the first station in the mock data
device_id = mock_stations_data.stations[0].devices[0].device_id
station_id = mock_stations_data.stations[0].station_id
mock_message.device_id = device_id
mock_message.ob = mock_wind_data
# Handle the message
await coordinator._handle_websocket_message(mock_message)
# Verify data was stored correctly
assert coordinator._ws_data[station_id][device_id] == mock_wind_data
async def test_observation_coordinator_message_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_rest_api: AsyncMock,
mock_websocket_api: AsyncMock,
mock_stations_data: Mock,
) -> None:
"""Test observation coordinator message handling."""
coordinator = WeatherFlowObservationCoordinator(
hass=hass,
config_entry=mock_config_entry,
rest_api=mock_rest_api,
websocket_api=mock_websocket_api,
stations=mock_stations_data,
)
# Create mock observation data
mock_message = Mock(spec=ObservationTempestWS)
# Use a device ID from the actual mock data
# The first device from the first station in the mock data
device_id = mock_stations_data.stations[0].devices[0].device_id
station_id = mock_stations_data.stations[0].station_id
mock_message.device_id = device_id
# Handle the message
await coordinator._handle_websocket_message(mock_message)
# Verify data was stored correctly (for observations, the message IS the data)
assert coordinator._ws_data[station_id][device_id] == mock_message
async def test_rest_coordinator_auth_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_rest_api: AsyncMock,
mock_stations_data: Mock,
) -> None:
"""Test REST coordinator handling of 401 auth error."""
# Create the coordinator
coordinator = WeatherFlowCloudUpdateCoordinatorREST(
hass=hass,
config_entry=mock_config_entry,
rest_api=mock_rest_api,
stations=mock_stations_data,
)
# Mock a 401 auth error
mock_rest_api.get_all_data.side_effect = ClientResponseError(
request_info=Mock(),
history=Mock(),
status=401,
message="Unauthorized",
)
# Verify the error is properly converted to ConfigEntryAuthFailed
with pytest.raises(ConfigEntryAuthFailed):
await coordinator._async_update_data()
async def test_rest_coordinator_other_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_rest_api: AsyncMock,
mock_stations_data: Mock,
) -> None:
"""Test REST coordinator handling of non-auth errors."""
# Create the coordinator
coordinator = WeatherFlowCloudUpdateCoordinatorREST(
hass=hass,
config_entry=mock_config_entry,
rest_api=mock_rest_api,
stations=mock_stations_data,
)
# Mock a 500 server error
mock_rest_api.get_all_data.side_effect = ClientResponseError(
request_info=Mock(),
history=Mock(),
status=500,
message="Internal Server Error",
)
# Verify the error is properly converted to UpdateFailed
with pytest.raises(
UpdateFailed, match="Update failed: 500, message='Internal Server Error'"
):
await coordinator._async_update_data()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/weatherflow_cloud/test_coordinators.py",
"license": "Apache License 2.0",
"lines": 183,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/wiz/test_fan.py | """Tests for fan platform."""
from typing import Any
from unittest.mock import patch
import pytest
from pywizlight import BulbType
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.fan import (
ATTR_DIRECTION,
ATTR_PERCENTAGE,
ATTR_PRESET_MODE,
DIRECTION_FORWARD,
DIRECTION_REVERSE,
DOMAIN as FAN_DOMAIN,
SERVICE_SET_DIRECTION,
SERVICE_SET_PERCENTAGE,
SERVICE_SET_PRESET_MODE,
)
from homeassistant.components.wiz.fan import PRESET_MODE_BREEZE
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import (
FAKE_DIMMABLE_FAN,
FAKE_DIMMABLE_FAN_2,
FAKE_MAC,
async_push_update,
async_setup_integration,
)
from tests.common import snapshot_platform
ENTITY_ID = "fan.mock_title"
INITIAL_PARAMS = {
"mac": FAKE_MAC,
"fanState": 0,
"fanMode": 1,
"fanSpeed": 1,
"fanRevrs": 0,
}
@pytest.mark.parametrize("bulb_type", [FAKE_DIMMABLE_FAN, FAKE_DIMMABLE_FAN_2])
@patch("homeassistant.components.wiz.PLATFORMS", [Platform.FAN])
async def test_entity(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
bulb_type: BulbType,
) -> None:
"""Test the fan entity."""
entry = (await async_setup_integration(hass, bulb_type=bulb_type))[1]
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
def _update_params(
params: dict[str, Any],
state: int | None = None,
mode: int | None = None,
speed: int | None = None,
reverse: int | None = None,
) -> dict[str, Any]:
"""Get the parameters for the update."""
if state is not None:
params["fanState"] = state
if mode is not None:
params["fanMode"] = mode
if speed is not None:
params["fanSpeed"] = speed
if reverse is not None:
params["fanRevrs"] = reverse
return params
async def test_turn_on_off(hass: HomeAssistant) -> None:
"""Test turning the fan on and off."""
device, _ = await async_setup_integration(hass, bulb_type=FAKE_DIMMABLE_FAN)
params = INITIAL_PARAMS.copy()
await hass.services.async_call(
FAN_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ENTITY_ID}, blocking=True
)
calls = device.fan_turn_on.mock_calls
assert len(calls) == 1
args = calls[0][2]
assert args == {"mode": None, "speed": None}
await async_push_update(hass, device, _update_params(params, state=1, **args))
device.fan_turn_on.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_ON
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: PRESET_MODE_BREEZE},
blocking=True,
)
calls = device.fan_turn_on.mock_calls
assert len(calls) == 1
args = calls[0][2]
assert args == {"mode": 2, "speed": None}
await async_push_update(hass, device, _update_params(params, state=1, **args))
device.fan_turn_on.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_ON
assert state.attributes[ATTR_PRESET_MODE] == PRESET_MODE_BREEZE
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PERCENTAGE: 50},
blocking=True,
)
calls = device.fan_turn_on.mock_calls
assert len(calls) == 1
args = calls[0][2]
assert args == {"mode": 1, "speed": 3}
await async_push_update(hass, device, _update_params(params, state=1, **args))
device.fan_turn_on.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_ON
assert state.attributes[ATTR_PERCENTAGE] == 50
assert state.attributes[ATTR_PRESET_MODE] is None
await hass.services.async_call(
FAN_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ENTITY_ID}, blocking=True
)
calls = device.fan_turn_off.mock_calls
assert len(calls) == 1
await async_push_update(hass, device, _update_params(params, state=0))
device.fan_turn_off.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_OFF
async def test_fan_set_preset_mode(hass: HomeAssistant) -> None:
"""Test setting the fan preset mode."""
device, _ = await async_setup_integration(hass, bulb_type=FAKE_DIMMABLE_FAN)
params = INITIAL_PARAMS.copy()
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: PRESET_MODE_BREEZE},
blocking=True,
)
calls = device.fan_set_state.mock_calls
assert len(calls) == 1
args = calls[0][2]
assert args == {"mode": 2}
await async_push_update(hass, device, _update_params(params, state=1, **args))
device.fan_set_state.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_ON
assert state.attributes[ATTR_PRESET_MODE] == PRESET_MODE_BREEZE
async def test_fan_set_percentage(hass: HomeAssistant) -> None:
"""Test setting the fan percentage."""
device, _ = await async_setup_integration(hass, bulb_type=FAKE_DIMMABLE_FAN)
params = INITIAL_PARAMS.copy()
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_PERCENTAGE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PERCENTAGE: 50},
blocking=True,
)
calls = device.fan_set_state.mock_calls
assert len(calls) == 1
args = calls[0][2]
assert args == {"mode": 1, "speed": 3}
await async_push_update(hass, device, _update_params(params, state=1, **args))
device.fan_set_state.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_ON
assert state.attributes[ATTR_PERCENTAGE] == 50
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_PERCENTAGE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PERCENTAGE: 0},
blocking=True,
)
calls = device.fan_turn_off.mock_calls
assert len(calls) == 1
await async_push_update(hass, device, _update_params(params, state=0))
device.fan_set_state.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_OFF
assert state.attributes[ATTR_PERCENTAGE] == 50
async def test_fan_set_direction(hass: HomeAssistant) -> None:
"""Test setting the fan direction."""
device, _ = await async_setup_integration(hass, bulb_type=FAKE_DIMMABLE_FAN)
params = INITIAL_PARAMS.copy()
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_DIRECTION,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_DIRECTION: DIRECTION_REVERSE},
blocking=True,
)
calls = device.fan_set_state.mock_calls
assert len(calls) == 1
args = calls[0][2]
assert args == {"reverse": 1}
await async_push_update(hass, device, _update_params(params, **args))
device.fan_set_state.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_OFF
assert state.attributes[ATTR_DIRECTION] == DIRECTION_REVERSE
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_DIRECTION,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_DIRECTION: DIRECTION_FORWARD},
blocking=True,
)
calls = device.fan_set_state.mock_calls
assert len(calls) == 1
args = calls[0][2]
assert args == {"reverse": 0}
await async_push_update(hass, device, _update_params(params, **args))
device.fan_set_state.reset_mock()
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_OFF
assert state.attributes[ATTR_DIRECTION] == DIRECTION_FORWARD
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/wiz/test_fan.py",
"license": "Apache License 2.0",
"lines": 212,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/yolink/test_init.py | """Tests for the yolink integration."""
from unittest.mock import patch
import pytest
from homeassistant.components.yolink import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
)
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("setup_credentials", "mock_auth_manager", "mock_yolink_home")
async def test_device_remove_devices(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test we can only remove a device that no longer exists."""
device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, "stale_device_id")},
)
device_entries = dr.async_entries_for_config_entry(
device_registry, mock_config_entry.entry_id
)
assert len(device_entries) == 1
device_entry = device_entries[0]
assert device_entry.identifiers == {(DOMAIN, "stale_device_id")}
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
device_entries = dr.async_entries_for_config_entry(
device_registry, mock_config_entry.entry_id
)
assert len(device_entries) == 0
@pytest.mark.usefixtures("setup_credentials", "mock_auth_manager", "mock_yolink_home")
async def test_oauth_implementation_not_available(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test that an unavailable OAuth implementation raises ConfigEntryNotReady."""
assert await async_setup_component(hass, "cloud", {})
with patch(
"homeassistant.components.yolink.async_get_config_entry_implementation",
side_effect=ImplementationUnavailableError,
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/yolink/test_init.py",
"license": "Apache License 2.0",
"lines": 48,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/zone/test_condition.py | """The tests for the location condition."""
import pytest
from homeassistant.components.zone import condition as zone_condition
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConditionError
from homeassistant.helpers import condition, config_validation as cv
async def test_zone_raises(hass: HomeAssistant) -> None:
"""Test that zone raises ConditionError on errors."""
config = {
"condition": "zone",
"options": {"entity_id": "device_tracker.cat", "zone": "zone.home"},
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
with pytest.raises(ConditionError, match="no zone"):
zone_condition.zone(hass, zone_ent=None, entity="sensor.any")
with pytest.raises(ConditionError, match="unknown zone"):
test(hass)
hass.states.async_set(
"zone.home",
"zoning",
{"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10},
)
with pytest.raises(ConditionError, match="no entity"):
zone_condition.zone(hass, zone_ent="zone.home", entity=None)
with pytest.raises(ConditionError, match="unknown entity"):
test(hass)
hass.states.async_set(
"device_tracker.cat",
"home",
{"friendly_name": "cat"},
)
with pytest.raises(ConditionError, match="latitude"):
test(hass)
hass.states.async_set(
"device_tracker.cat",
"home",
{"friendly_name": "cat", "latitude": 2.1},
)
with pytest.raises(ConditionError, match="longitude"):
test(hass)
hass.states.async_set(
"device_tracker.cat",
"home",
{"friendly_name": "cat", "latitude": 2.1, "longitude": 1.1},
)
# All okay, now test multiple failed conditions
assert test(hass)
config = {
"condition": "zone",
"options": {
"entity_id": ["device_tracker.cat", "device_tracker.dog"],
"zone": ["zone.home", "zone.work"],
},
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
with pytest.raises(ConditionError, match="dog"):
test(hass)
with pytest.raises(ConditionError, match="work"):
test(hass)
hass.states.async_set(
"zone.work",
"zoning",
{"name": "work", "latitude": 20, "longitude": 10, "radius": 25000},
)
hass.states.async_set(
"device_tracker.dog",
"work",
{"friendly_name": "dog", "latitude": 20.1, "longitude": 10.1},
)
assert test(hass)
async def test_zone_multiple_entities(hass: HomeAssistant) -> None:
"""Test with multiple entities in condition."""
config = {
"condition": "and",
"conditions": [
{
"alias": "Zone Condition",
"condition": "zone",
"options": {
"entity_id": ["device_tracker.person_1", "device_tracker.person_2"],
"zone": "zone.home",
},
},
],
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
hass.states.async_set(
"zone.home",
"zoning",
{"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10},
)
hass.states.async_set(
"device_tracker.person_1",
"home",
{"friendly_name": "person_1", "latitude": 2.1, "longitude": 1.1},
)
hass.states.async_set(
"device_tracker.person_2",
"home",
{"friendly_name": "person_2", "latitude": 2.1, "longitude": 1.1},
)
assert test(hass)
hass.states.async_set(
"device_tracker.person_1",
"home",
{"friendly_name": "person_1", "latitude": 20.1, "longitude": 10.1},
)
hass.states.async_set(
"device_tracker.person_2",
"home",
{"friendly_name": "person_2", "latitude": 2.1, "longitude": 1.1},
)
assert not test(hass)
hass.states.async_set(
"device_tracker.person_1",
"home",
{"friendly_name": "person_1", "latitude": 2.1, "longitude": 1.1},
)
hass.states.async_set(
"device_tracker.person_2",
"home",
{"friendly_name": "person_2", "latitude": 20.1, "longitude": 10.1},
)
assert not test(hass)
async def test_multiple_zones(hass: HomeAssistant) -> None:
"""Test with multiple entities in condition."""
config = {
"condition": "and",
"conditions": [
{
"condition": "zone",
"options": {
"entity_id": "device_tracker.person",
"zone": ["zone.home", "zone.work"],
},
},
],
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
hass.states.async_set(
"zone.home",
"zoning",
{"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10},
)
hass.states.async_set(
"zone.work",
"zoning",
{"name": "work", "latitude": 20.1, "longitude": 10.1, "radius": 10},
)
hass.states.async_set(
"device_tracker.person",
"home",
{"friendly_name": "person", "latitude": 2.1, "longitude": 1.1},
)
assert test(hass)
hass.states.async_set(
"device_tracker.person",
"home",
{"friendly_name": "person", "latitude": 20.1, "longitude": 10.1},
)
assert test(hass)
hass.states.async_set(
"device_tracker.person",
"home",
{"friendly_name": "person", "latitude": 50.1, "longitude": 20.1},
)
assert not test(hass)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/zone/test_condition.py",
"license": "Apache License 2.0",
"lines": 175,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/test_target.py | """Test service helpers."""
import pytest
from homeassistant.components.group import Group
from homeassistant.const import (
ATTR_AREA_ID,
ATTR_DEVICE_ID,
ATTR_ENTITY_ID,
ATTR_FLOOR_ID,
ATTR_LABEL_ID,
ENTITY_MATCH_NONE,
STATE_OFF,
STATE_ON,
EntityCategory,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import (
area_registry as ar,
device_registry as dr,
entity_registry as er,
floor_registry as fr,
label_registry as lr,
target,
)
from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
RegistryEntryWithDefaults,
mock_area_registry,
mock_device_registry,
mock_registry,
)
async def set_states_and_check_target_events(
hass: HomeAssistant,
events: list[target.TargetStateChangedData],
state: str,
entities_to_set_state: list[str],
entities_to_assert_change: list[str],
) -> None:
"""Toggle the state entities and check for events."""
for entity_id in entities_to_set_state:
hass.states.async_set(entity_id, state)
await hass.async_block_till_done()
assert len(events) == len(entities_to_assert_change)
entities_seen = set()
for event in events:
state_change_event = event.state_change_event
entities_seen.add(state_change_event.data["entity_id"])
assert state_change_event.data["new_state"].state == state
assert event.targeted_entity_ids == set(entities_to_assert_change)
assert entities_seen == set(entities_to_assert_change)
events.clear()
@pytest.fixture
def registries_mock(hass: HomeAssistant) -> None:
"""Mock including floor and area info."""
hass.states.async_set("light.Bowl", STATE_ON)
hass.states.async_set("light.Ceiling", STATE_OFF)
hass.states.async_set("light.Kitchen", STATE_OFF)
area_in_floor = ar.AreaEntry(
id="test-area",
name="Test area",
aliases={},
floor_id="test-floor",
icon=None,
picture=None,
temperature_entity_id=None,
humidity_entity_id=None,
)
area_in_floor_a = ar.AreaEntry(
id="area-a",
name="Area A",
aliases={},
floor_id="floor-a",
icon=None,
picture=None,
temperature_entity_id=None,
humidity_entity_id=None,
)
area_with_labels = ar.AreaEntry(
id="area-with-labels",
name="Area with labels",
aliases={},
floor_id=None,
icon=None,
labels={"label_area"},
picture=None,
temperature_entity_id=None,
humidity_entity_id=None,
)
mock_area_registry(
hass,
{
area_in_floor.id: area_in_floor,
area_in_floor_a.id: area_in_floor_a,
area_with_labels.id: area_with_labels,
},
)
device_in_area = dr.DeviceEntry(id="device-test-area", area_id="test-area")
device_no_area = dr.DeviceEntry(id="device-no-area-id")
device_diff_area = dr.DeviceEntry(id="device-diff-area", area_id="diff-area")
device_area_a = dr.DeviceEntry(id="device-area-a-id", area_id="area-a")
device_has_label1 = dr.DeviceEntry(id="device-has-label1-id", labels={"label1"})
device_has_label2 = dr.DeviceEntry(id="device-has-label2-id", labels={"label2"})
device_has_labels = dr.DeviceEntry(
id="device-has-labels-id",
labels={"label1", "label2"},
area_id=area_with_labels.id,
)
mock_device_registry(
hass,
{
device_in_area.id: device_in_area,
device_no_area.id: device_no_area,
device_diff_area.id: device_diff_area,
device_area_a.id: device_area_a,
device_has_label1.id: device_has_label1,
device_has_label2.id: device_has_label2,
device_has_labels.id: device_has_labels,
},
)
entity_in_own_area = RegistryEntryWithDefaults(
entity_id="light.in_own_area",
unique_id="in-own-area-id",
platform="test",
area_id="own-area",
)
config_entity_in_own_area = RegistryEntryWithDefaults(
entity_id="light.config_in_own_area",
unique_id="config-in-own-area-id",
platform="test",
area_id="own-area",
entity_category=EntityCategory.CONFIG,
)
hidden_entity_in_own_area = RegistryEntryWithDefaults(
entity_id="light.hidden_in_own_area",
unique_id="hidden-in-own-area-id",
platform="test",
area_id="own-area",
hidden_by=er.RegistryEntryHider.USER,
)
entity_in_area = RegistryEntryWithDefaults(
entity_id="light.in_area",
unique_id="in-area-id",
platform="test",
device_id=device_in_area.id,
)
config_entity_in_area = RegistryEntryWithDefaults(
entity_id="light.config_in_area",
unique_id="config-in-area-id",
platform="test",
device_id=device_in_area.id,
entity_category=EntityCategory.CONFIG,
)
hidden_entity_in_area = RegistryEntryWithDefaults(
entity_id="light.hidden_in_area",
unique_id="hidden-in-area-id",
platform="test",
device_id=device_in_area.id,
hidden_by=er.RegistryEntryHider.USER,
)
entity_in_other_area = RegistryEntryWithDefaults(
entity_id="light.in_other_area",
unique_id="in-area-a-id",
platform="test",
device_id=device_in_area.id,
area_id="other-area",
)
entity_assigned_to_area = RegistryEntryWithDefaults(
entity_id="light.assigned_to_area",
unique_id="assigned-area-id",
platform="test",
device_id=device_in_area.id,
area_id="test-area",
)
entity_no_area = RegistryEntryWithDefaults(
entity_id="light.no_area",
unique_id="no-area-id",
platform="test",
device_id=device_no_area.id,
)
config_entity_no_area = RegistryEntryWithDefaults(
entity_id="light.config_no_area",
unique_id="config-no-area-id",
platform="test",
device_id=device_no_area.id,
entity_category=EntityCategory.CONFIG,
)
hidden_entity_no_area = RegistryEntryWithDefaults(
entity_id="light.hidden_no_area",
unique_id="hidden-no-area-id",
platform="test",
device_id=device_no_area.id,
hidden_by=er.RegistryEntryHider.USER,
)
entity_diff_area = RegistryEntryWithDefaults(
entity_id="light.diff_area",
unique_id="diff-area-id",
platform="test",
device_id=device_diff_area.id,
)
entity_in_area_a = RegistryEntryWithDefaults(
entity_id="light.in_area_a",
unique_id="in-area-a-id",
platform="test",
device_id=device_area_a.id,
area_id="area-a",
)
entity_in_area_b = RegistryEntryWithDefaults(
entity_id="light.in_area_b",
unique_id="in-area-b-id",
platform="test",
device_id=device_area_a.id,
area_id="area-b",
)
entity_with_my_label = RegistryEntryWithDefaults(
entity_id="light.with_my_label",
unique_id="with_my_label",
platform="test",
labels={"my-label"},
)
hidden_entity_with_my_label = RegistryEntryWithDefaults(
entity_id="light.hidden_with_my_label",
unique_id="hidden_with_my_label",
platform="test",
labels={"my-label"},
hidden_by=er.RegistryEntryHider.USER,
)
config_entity_with_my_label = RegistryEntryWithDefaults(
entity_id="light.config_with_my_label",
unique_id="config_with_my_label",
platform="test",
labels={"my-label"},
entity_category=EntityCategory.CONFIG,
)
diag_entity_with_my_label = RegistryEntryWithDefaults(
entity_id="light.diag_with_my_label",
unique_id="diag_with_my_label",
platform="test",
labels={"my-label"},
entity_category=EntityCategory.DIAGNOSTIC,
)
entity_with_label1_from_device = RegistryEntryWithDefaults(
entity_id="light.with_label1_from_device",
unique_id="with_label1_from_device",
platform="test",
device_id=device_has_label1.id,
)
entity_with_label1_from_device_and_different_area = RegistryEntryWithDefaults(
entity_id="light.with_label1_from_device_diff_area",
unique_id="with_label1_from_device_diff_area",
platform="test",
device_id=device_has_label1.id,
area_id=area_in_floor_a.id,
)
entity_with_label1_and_label2_from_device = RegistryEntryWithDefaults(
entity_id="light.with_label1_and_label2_from_device",
unique_id="with_label1_and_label2_from_device",
platform="test",
labels={"label1"},
device_id=device_has_label2.id,
)
entity_with_labels_from_device = RegistryEntryWithDefaults(
entity_id="light.with_labels_from_device",
unique_id="with_labels_from_device",
platform="test",
device_id=device_has_labels.id,
)
mock_registry(
hass,
{
entity_in_own_area.entity_id: entity_in_own_area,
config_entity_in_own_area.entity_id: config_entity_in_own_area,
hidden_entity_in_own_area.entity_id: hidden_entity_in_own_area,
entity_in_area.entity_id: entity_in_area,
config_entity_in_area.entity_id: config_entity_in_area,
hidden_entity_in_area.entity_id: hidden_entity_in_area,
entity_in_other_area.entity_id: entity_in_other_area,
entity_assigned_to_area.entity_id: entity_assigned_to_area,
entity_no_area.entity_id: entity_no_area,
config_entity_no_area.entity_id: config_entity_no_area,
hidden_entity_no_area.entity_id: hidden_entity_no_area,
entity_diff_area.entity_id: entity_diff_area,
entity_in_area_a.entity_id: entity_in_area_a,
entity_in_area_b.entity_id: entity_in_area_b,
config_entity_with_my_label.entity_id: config_entity_with_my_label,
diag_entity_with_my_label.entity_id: diag_entity_with_my_label,
entity_with_label1_and_label2_from_device.entity_id: entity_with_label1_and_label2_from_device,
entity_with_label1_from_device.entity_id: entity_with_label1_from_device,
entity_with_label1_from_device_and_different_area.entity_id: entity_with_label1_from_device_and_different_area,
entity_with_labels_from_device.entity_id: entity_with_labels_from_device,
entity_with_my_label.entity_id: entity_with_my_label,
hidden_entity_with_my_label.entity_id: hidden_entity_with_my_label,
},
)
@pytest.mark.parametrize(
("selector_config", "expand_group", "expected_selected"),
[
(
{
ATTR_ENTITY_ID: ENTITY_MATCH_NONE,
ATTR_AREA_ID: ENTITY_MATCH_NONE,
ATTR_FLOOR_ID: ENTITY_MATCH_NONE,
ATTR_LABEL_ID: ENTITY_MATCH_NONE,
},
False,
target.SelectedEntities(),
),
(
{ATTR_ENTITY_ID: "light.bowl"},
False,
target.SelectedEntities(referenced={"light.bowl"}),
),
(
{ATTR_ENTITY_ID: "group.test"},
True,
target.SelectedEntities(referenced={"light.ceiling", "light.kitchen"}),
),
(
{ATTR_ENTITY_ID: "group.test"},
False,
target.SelectedEntities(referenced={"group.test"}),
),
(
{ATTR_AREA_ID: "own-area"},
False,
target.SelectedEntities(
indirectly_referenced={"light.in_own_area"},
referenced_areas={"own-area"},
missing_areas={"own-area"},
),
),
(
{ATTR_AREA_ID: "test-area"},
False,
target.SelectedEntities(
indirectly_referenced={
"light.in_area",
"light.assigned_to_area",
},
referenced_areas={"test-area"},
referenced_devices={"device-test-area"},
),
),
(
{ATTR_AREA_ID: ["test-area", "diff-area"]},
False,
target.SelectedEntities(
indirectly_referenced={
"light.in_area",
"light.diff_area",
"light.assigned_to_area",
},
referenced_areas={"test-area", "diff-area"},
referenced_devices={"device-diff-area", "device-test-area"},
missing_areas={"diff-area"},
),
),
(
{ATTR_DEVICE_ID: "device-no-area-id"},
False,
target.SelectedEntities(
indirectly_referenced={"light.no_area"},
referenced_devices={"device-no-area-id"},
),
),
(
{ATTR_DEVICE_ID: "device-area-a-id"},
False,
target.SelectedEntities(
indirectly_referenced={"light.in_area_a", "light.in_area_b"},
referenced_devices={"device-area-a-id"},
),
),
(
{ATTR_FLOOR_ID: "test-floor"},
False,
target.SelectedEntities(
indirectly_referenced={"light.in_area", "light.assigned_to_area"},
referenced_devices={"device-test-area"},
referenced_areas={"test-area"},
missing_floors={"test-floor"},
),
),
(
{ATTR_FLOOR_ID: ["test-floor", "floor-a"]},
False,
target.SelectedEntities(
indirectly_referenced={
"light.in_area",
"light.assigned_to_area",
"light.in_area_a",
"light.with_label1_from_device_diff_area",
},
referenced_devices={"device-area-a-id", "device-test-area"},
referenced_areas={"area-a", "test-area"},
missing_floors={"floor-a", "test-floor"},
),
),
(
{ATTR_LABEL_ID: "my-label"},
False,
target.SelectedEntities(
indirectly_referenced={
"light.with_my_label",
"light.config_with_my_label",
"light.diag_with_my_label",
},
missing_labels={"my-label"},
),
),
(
{ATTR_LABEL_ID: "label1"},
False,
target.SelectedEntities(
indirectly_referenced={
"light.with_label1_from_device",
"light.with_label1_from_device_diff_area",
"light.with_labels_from_device",
"light.with_label1_and_label2_from_device",
},
referenced_devices={"device-has-label1-id", "device-has-labels-id"},
missing_labels={"label1"},
),
),
(
{ATTR_LABEL_ID: ["label2"]},
False,
target.SelectedEntities(
indirectly_referenced={
"light.with_labels_from_device",
"light.with_label1_and_label2_from_device",
},
referenced_devices={"device-has-label2-id", "device-has-labels-id"},
missing_labels={"label2"},
),
),
(
{ATTR_LABEL_ID: ["label_area"]},
False,
target.SelectedEntities(
indirectly_referenced={"light.with_labels_from_device"},
referenced_devices={"device-has-labels-id"},
referenced_areas={"area-with-labels"},
missing_labels={"label_area"},
),
),
],
)
@pytest.mark.parametrize(
"selection_class", [target.TargetSelection, target.TargetSelectorData]
)
@pytest.mark.usefixtures("registries_mock")
async def test_extract_referenced_entity_ids(
hass: HomeAssistant,
selector_config: ConfigType,
expand_group: bool,
expected_selected: target.SelectedEntities,
selection_class,
) -> None:
"""Test extract_entity_ids method."""
hass.states.async_set("light.Bowl", STATE_ON)
hass.states.async_set("light.Ceiling", STATE_OFF)
hass.states.async_set("light.Kitchen", STATE_OFF)
assert await async_setup_component(hass, "group", {})
await hass.async_block_till_done()
await Group.async_create_group(
hass,
"test",
created_by_service=False,
entity_ids=["light.Ceiling", "light.Kitchen"],
icon=None,
mode=None,
object_id=None,
order=None,
)
target_selection = selection_class(selector_config)
assert (
target.async_extract_referenced_entity_ids(
hass, target_selection, expand_group=expand_group
)
== expected_selected
)
async def test_async_track_target_selector_state_change_event_empty_selector(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test async_track_target_selector_state_change_event with empty selector."""
@callback
def state_change_callback(event):
"""Handle state change events."""
with pytest.raises(HomeAssistantError) as excinfo:
target.async_track_target_selector_state_change_event(
hass, {}, state_change_callback
)
assert str(excinfo.value) == (
"Target selector {} does not have any selectors defined"
)
async def test_async_track_target_selector_state_change_event(
hass: HomeAssistant,
) -> None:
"""Test async_track_target_selector_state_change_event with multiple targets."""
events: list[target.TargetStateChangedData] = []
@callback
def state_change_callback(event: target.TargetStateChangedData):
"""Handle state change events."""
events.append(event)
last_state = STATE_OFF
async def set_states_and_check_events(
entities_to_set_state: list[str], entities_to_assert_change: list[str]
) -> None:
"""Toggle the state entities and check for events."""
nonlocal last_state
last_state = STATE_ON if last_state == STATE_OFF else STATE_OFF
await set_states_and_check_target_events(
hass, events, last_state, entities_to_set_state, entities_to_assert_change
)
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
device_reg = dr.async_get(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
identifiers={("test", "device_1")},
)
untargeted_device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
identifiers={("test", "area_device")},
)
entity_reg = er.async_get(hass)
device_entity = entity_reg.async_get_or_create(
domain="light",
platform="test",
unique_id="device_light",
device_id=device_entry.id,
).entity_id
untargeted_device_entity = entity_reg.async_get_or_create(
domain="light",
platform="test",
unique_id="area_device_light",
device_id=untargeted_device_entry.id,
).entity_id
untargeted_entity = entity_reg.async_get_or_create(
domain="light",
platform="test",
unique_id="untargeted_light",
).entity_id
targeted_entity = "light.test_light"
targeted_entities = [targeted_entity, device_entity]
await set_states_and_check_events(targeted_entities, [])
label = lr.async_get(hass).async_create("Test Label").name
area = ar.async_get(hass).async_create("Test Area").id
floor = fr.async_get(hass).async_create("Test Floor").floor_id
selector_config = {
ATTR_ENTITY_ID: targeted_entity,
ATTR_DEVICE_ID: device_entry.id,
ATTR_AREA_ID: area,
ATTR_FLOOR_ID: floor,
ATTR_LABEL_ID: label,
}
unsub = target.async_track_target_selector_state_change_event(
hass, selector_config, state_change_callback
)
# Test directly targeted entity and device
await set_states_and_check_events(targeted_entities, targeted_entities)
# Add new entity to the targeted device -> should trigger on state change
device_entity_2 = entity_reg.async_get_or_create(
domain="light",
platform="test",
unique_id="device_light_2",
device_id=device_entry.id,
).entity_id
targeted_entities = [targeted_entity, device_entity, device_entity_2]
await set_states_and_check_events(targeted_entities, targeted_entities)
# Test untargeted entity -> should not trigger
await set_states_and_check_events(
[*targeted_entities, untargeted_entity], targeted_entities
)
# Add label to untargeted entity -> should trigger now
entity_reg.async_update_entity(untargeted_entity, labels={label})
await set_states_and_check_events(
[*targeted_entities, untargeted_entity], [*targeted_entities, untargeted_entity]
)
# Remove label from untargeted entity -> should not trigger anymore
entity_reg.async_update_entity(untargeted_entity, labels={})
await set_states_and_check_events(
[*targeted_entities, untargeted_entity], targeted_entities
)
# Add area to untargeted entity -> should trigger now
entity_reg.async_update_entity(untargeted_entity, area_id=area)
await set_states_and_check_events(
[*targeted_entities, untargeted_entity], [*targeted_entities, untargeted_entity]
)
# Remove area from untargeted entity -> should not trigger anymore
entity_reg.async_update_entity(untargeted_entity, area_id=None)
await set_states_and_check_events(
[*targeted_entities, untargeted_entity], targeted_entities
)
# Add area to untargeted device -> should trigger on state change
device_reg.async_update_device(untargeted_device_entry.id, area_id=area)
await set_states_and_check_events(
[*targeted_entities, untargeted_device_entity],
[*targeted_entities, untargeted_device_entity],
)
# Remove area from untargeted device -> should not trigger anymore
device_reg.async_update_device(untargeted_device_entry.id, area_id=None)
await set_states_and_check_events(
[*targeted_entities, untargeted_device_entity], targeted_entities
)
# Set the untargeted area on the untargeted entity -> should not trigger
untracked_area = ar.async_get(hass).async_create("Untargeted Area").id
entity_reg.async_update_entity(untargeted_entity, area_id=untracked_area)
await set_states_and_check_events(
[*targeted_entities, untargeted_entity], targeted_entities
)
# Set targeted floor on the untargeted area -> should trigger now
ar.async_get(hass).async_update(untracked_area, floor_id=floor)
await set_states_and_check_events(
[*targeted_entities, untargeted_entity],
[*targeted_entities, untargeted_entity],
)
# Remove untargeted area from targeted floor -> should not trigger anymore
ar.async_get(hass).async_update(untracked_area, floor_id=None)
await set_states_and_check_events(
[*targeted_entities, untargeted_entity], targeted_entities
)
# After unsubscribing, changes should not trigger
unsub()
await set_states_and_check_events(targeted_entities, [])
async def test_async_track_target_selector_state_change_event_filter(
hass: HomeAssistant,
) -> None:
"""Test async_track_target_selector_state_change_event with entity filter."""
events: list[target.TargetStateChangedData] = []
filtered_entity = ""
@callback
def entity_filter(entity_ids: set[str]) -> set[str]:
return {entity_id for entity_id in entity_ids if entity_id != filtered_entity}
@callback
def state_change_callback(event: target.TargetStateChangedData):
"""Handle state change events."""
events.append(event)
last_state = STATE_OFF
async def set_states_and_check_events(
entities_to_set_state: list[str], entities_to_assert_change: list[str]
) -> None:
"""Toggle the state entities and check for events."""
nonlocal last_state
last_state = STATE_ON if last_state == STATE_OFF else STATE_OFF
await set_states_and_check_target_events(
hass, events, last_state, entities_to_set_state, entities_to_assert_change
)
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
entity_reg = er.async_get(hass)
label = lr.async_get(hass).async_create("Test Label").name
label_entity = entity_reg.async_get_or_create(
domain="light",
platform="test",
unique_id="label_light",
).entity_id
entity_reg.async_update_entity(label_entity, labels={label})
targeted_entity = "light.test_light"
targeted_entities = [targeted_entity, label_entity]
await set_states_and_check_events(targeted_entities, [])
selector_config = {
ATTR_ENTITY_ID: targeted_entity,
ATTR_LABEL_ID: label,
}
unsub = target.async_track_target_selector_state_change_event(
hass, selector_config, state_change_callback, entity_filter
)
await set_states_and_check_events(
targeted_entities, [targeted_entity, label_entity]
)
filtered_entity = targeted_entity
# Fire an event so that the targeted entities are re-evaluated
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{
"action": "update",
"entity_id": "light.other",
"changes": {},
},
)
await set_states_and_check_events([targeted_entity, label_entity], [label_entity])
filtered_entity = label_entity
# Fire an event so that the targeted entities are re-evaluated
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{
"action": "update",
"entity_id": "light.other",
"changes": {},
},
)
await set_states_and_check_events(
[targeted_entity, label_entity], [targeted_entity]
)
unsub()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/test_target.py",
"license": "Apache License 2.0",
"lines": 698,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/util/test_resource.py | """Test the resource utility module."""
import os
import resource
from unittest.mock import call, patch
import pytest
from homeassistant.util.resource import (
DEFAULT_SOFT_FILE_LIMIT,
set_open_file_descriptor_limit,
)
@pytest.mark.parametrize(
("original_soft", "expected_calls", "should_log_already_sufficient"),
[
(
1024,
[call(resource.RLIMIT_NOFILE, (DEFAULT_SOFT_FILE_LIMIT, 524288))],
False,
),
(
DEFAULT_SOFT_FILE_LIMIT - 1,
[call(resource.RLIMIT_NOFILE, (DEFAULT_SOFT_FILE_LIMIT, 524288))],
False,
),
(DEFAULT_SOFT_FILE_LIMIT, [], True),
(DEFAULT_SOFT_FILE_LIMIT + 1, [], True),
],
)
def test_set_open_file_descriptor_limit_default(
caplog: pytest.LogCaptureFixture,
original_soft: int,
expected_calls: list,
should_log_already_sufficient: bool,
) -> None:
"""Test setting file limit with default value."""
original_hard = 524288
with (
patch(
"homeassistant.util.resource.resource.getrlimit",
return_value=(original_soft, original_hard),
),
patch("homeassistant.util.resource.resource.setrlimit") as mock_setrlimit,
):
set_open_file_descriptor_limit()
assert mock_setrlimit.call_args_list == expected_calls
assert (
f"Current soft limit ({original_soft}) is already" in caplog.text
) is should_log_already_sufficient
@pytest.mark.parametrize(
(
"original_soft",
"custom_limit",
"expected_calls",
"should_log_already_sufficient",
),
[
(1499, 1500, [call(resource.RLIMIT_NOFILE, (1500, 524288))], False),
(1500, 1500, [], True),
(1501, 1500, [], True),
],
)
def test_set_open_file_descriptor_limit_environment_variable(
caplog: pytest.LogCaptureFixture,
original_soft: int,
custom_limit: int,
expected_calls: list,
should_log_already_sufficient: bool,
) -> None:
"""Test setting file limit from environment variable."""
original_hard = 524288
with (
patch.dict(os.environ, {"SOFT_FILE_LIMIT": str(custom_limit)}),
patch(
"homeassistant.util.resource.resource.getrlimit",
return_value=(original_soft, original_hard),
),
patch("homeassistant.util.resource.resource.setrlimit") as mock_setrlimit,
):
set_open_file_descriptor_limit()
assert mock_setrlimit.call_args_list == expected_calls
assert (
f"Current soft limit ({original_soft}) is already" in caplog.text
) is should_log_already_sufficient
def test_set_open_file_descriptor_limit_exceeds_hard_limit(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test setting file limit that exceeds hard limit."""
original_soft, original_hard = (1024, 524288)
excessive_limit = original_hard + 1
with (
patch.dict(os.environ, {"SOFT_FILE_LIMIT": str(excessive_limit)}),
patch(
"homeassistant.util.resource.resource.getrlimit",
return_value=(original_soft, original_hard),
),
patch("homeassistant.util.resource.resource.setrlimit") as mock_setrlimit,
):
set_open_file_descriptor_limit()
mock_setrlimit.assert_called_once_with(
resource.RLIMIT_NOFILE, (original_hard, original_hard)
)
assert (
f"Requested soft limit ({excessive_limit}) exceeds hard limit ({original_hard})"
in caplog.text
)
def test_set_open_file_descriptor_limit_os_error(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test handling OSError when setting file limit."""
with (
patch(
"homeassistant.util.resource.resource.getrlimit",
return_value=(1024, 524288),
),
patch(
"homeassistant.util.resource.resource.setrlimit",
side_effect=OSError("Permission denied"),
),
):
set_open_file_descriptor_limit()
assert "Failed to set file descriptor limit" in caplog.text
assert "Permission denied" in caplog.text
def test_set_open_file_descriptor_limit_value_error(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test handling ValueError when setting file limit."""
with (
patch.dict(os.environ, {"SOFT_FILE_LIMIT": "invalid_value"}),
patch(
"homeassistant.util.resource.resource.getrlimit",
return_value=(1024, 524288),
),
):
set_open_file_descriptor_limit()
assert "Invalid file descriptor limit value" in caplog.text
assert "'invalid_value'" in caplog.text
| {
"repo_id": "home-assistant/core",
"file_path": "tests/util/test_resource.py",
"license": "Apache License 2.0",
"lines": 134,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nibe_heatpump/test_binary_sensor.py | """Test the Nibe Heat Pump binary sensor entities."""
from typing import Any
from unittest.mock import patch
from nibe.heatpump import Model
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import async_add_model
from tests.common import snapshot_platform
@pytest.fixture(autouse=True)
async def fixture_single_platform():
"""Only allow this platform to load."""
with patch(
"homeassistant.components.nibe_heatpump.PLATFORMS", [Platform.BINARY_SENSOR]
):
yield
@pytest.mark.parametrize(
("model", "address", "value"),
[
(Model.F1255, 49239, "OFF"),
(Model.F1255, 49239, "ON"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_update(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
model: Model,
address: int,
value: Any,
coils: dict[int, Any],
snapshot: SnapshotAssertion,
) -> None:
"""Test setting of value."""
coils[address] = value
entry = await async_add_model(hass, model)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nibe_heatpump/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 39,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nibe_heatpump/test_switch.py | """Test the Nibe Heat Pump switch entities."""
from typing import Any
from unittest.mock import AsyncMock, patch
from nibe.coil import CoilData
from nibe.heatpump import Model
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import async_add_model
from tests.common import snapshot_platform
@pytest.fixture(autouse=True)
async def fixture_single_platform():
"""Only allow this platform to load."""
with patch("homeassistant.components.nibe_heatpump.PLATFORMS", [Platform.SWITCH]):
yield
@pytest.mark.parametrize(
("model", "address", "value"),
[
(Model.F1255, 48043, "INACTIVE"),
(Model.F1255, 48043, "ACTIVE"),
(Model.F1255, 48071, "OFF"),
(Model.F1255, 48071, "ON"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_update(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
model: Model,
address: int,
value: Any,
coils: dict[int, Any],
snapshot: SnapshotAssertion,
) -> None:
"""Test setting of value."""
coils[address] = value
entry = await async_add_model(hass, model)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
@pytest.mark.parametrize(
("model", "address", "entity_id", "state"),
[
(Model.F1255, 48043, "switch.holiday_activated_48043", "INACTIVE"),
(Model.F1255, 48071, "switch.flm_1_accessory_48071", "OFF"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_turn_on(
hass: HomeAssistant,
mock_connection: AsyncMock,
model: Model,
entity_id: str,
address: int,
state: Any,
coils: dict[int, Any],
) -> None:
"""Test setting of value."""
coils[address] = state
await async_add_model(hass, model)
# Write value
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
# Verify written
args = mock_connection.write_coil.call_args
assert args
coil = args.args[0]
assert isinstance(coil, CoilData)
assert coil.coil.address == address
assert coil.raw_value == 1
@pytest.mark.parametrize(
("model", "address", "entity_id", "state"),
[
(Model.F1255, 48043, "switch.holiday_activated_48043", "INACTIVE"),
(Model.F1255, 48071, "switch.flm_1_accessory_48071", "ON"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_turn_off(
hass: HomeAssistant,
mock_connection: AsyncMock,
model: Model,
entity_id: str,
address: int,
state: Any,
coils: dict[int, Any],
) -> None:
"""Test setting of value."""
coils[address] = state
await async_add_model(hass, model)
# Write value
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
# Verify written
args = mock_connection.write_coil.call_args
assert args
coil = args.args[0]
assert isinstance(coil, CoilData)
assert coil.coil.address == address
assert coil.raw_value == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nibe_heatpump/test_switch.py",
"license": "Apache License 2.0",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/remote_calendar/client.py | """Specifies the parameter for the httpx download."""
from httpx import AsyncClient, Response, Timeout
async def get_calendar(client: AsyncClient, url: str) -> Response:
"""Make an HTTP GET request using Home Assistant's async HTTPX client with timeout."""
return await client.get(
url,
follow_redirects=True,
timeout=Timeout(5, read=30, write=5, pool=5),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/remote_calendar/client.py",
"license": "Apache License 2.0",
"lines": 9,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/abode/services.py | """Support for the Abode Security System."""
from __future__ import annotations
from jaraco.abode.exceptions import Exception as AbodeException
import voluptuous as vol
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import dispatcher_send
from .const import DOMAIN, DOMAIN_DATA, LOGGER
ATTR_SETTING = "setting"
ATTR_VALUE = "value"
CHANGE_SETTING_SCHEMA = vol.Schema(
{vol.Required(ATTR_SETTING): cv.string, vol.Required(ATTR_VALUE): cv.string}
)
CAPTURE_IMAGE_SCHEMA = vol.Schema({ATTR_ENTITY_ID: cv.entity_ids})
AUTOMATION_SCHEMA = vol.Schema({ATTR_ENTITY_ID: cv.entity_ids})
def _change_setting(call: ServiceCall) -> None:
"""Change an Abode system setting."""
setting = call.data[ATTR_SETTING]
value = call.data[ATTR_VALUE]
try:
call.hass.data[DOMAIN_DATA].abode.set_setting(setting, value)
except AbodeException as ex:
LOGGER.warning(ex)
def _capture_image(call: ServiceCall) -> None:
"""Capture a new image."""
entity_ids = call.data[ATTR_ENTITY_ID]
target_entities = [
entity_id
for entity_id in call.hass.data[DOMAIN_DATA].entity_ids
if entity_id in entity_ids
]
for entity_id in target_entities:
signal = f"abode_camera_capture_{entity_id}"
dispatcher_send(call.hass, signal)
def _trigger_automation(call: ServiceCall) -> None:
"""Trigger an Abode automation."""
entity_ids = call.data[ATTR_ENTITY_ID]
target_entities = [
entity_id
for entity_id in call.hass.data[DOMAIN_DATA].entity_ids
if entity_id in entity_ids
]
for entity_id in target_entities:
signal = f"abode_trigger_automation_{entity_id}"
dispatcher_send(call.hass, signal)
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Home Assistant services."""
hass.services.async_register(
DOMAIN, "change_setting", _change_setting, schema=CHANGE_SETTING_SCHEMA
)
hass.services.async_register(
DOMAIN, "capture_image", _capture_image, schema=CAPTURE_IMAGE_SCHEMA
)
hass.services.async_register(
DOMAIN, "trigger_automation", _trigger_automation, schema=AUTOMATION_SCHEMA
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/abode/services.py",
"license": "Apache License 2.0",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/adax/sensor.py | """Support for Adax energy sensors."""
from __future__ import annotations
from dataclasses import dataclass
from typing import cast
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import UnitOfEnergy, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import AdaxConfigEntry
from .const import CONNECTION_TYPE, DOMAIN, LOCAL
from .coordinator import AdaxCloudCoordinator
@dataclass(kw_only=True, frozen=True)
class AdaxSensorDescription(SensorEntityDescription):
"""Describes Adax sensor entity."""
data_key: str
SENSORS: tuple[AdaxSensorDescription, ...] = (
AdaxSensorDescription(
key="temperature",
data_key="temperature",
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
),
AdaxSensorDescription(
key="energy",
data_key="energyWh",
device_class=SensorDeviceClass.ENERGY,
native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
state_class=SensorStateClass.TOTAL_INCREASING,
suggested_display_precision=3,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: AdaxConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Adax sensors with config flow."""
if entry.data.get(CONNECTION_TYPE) != LOCAL:
cloud_coordinator = cast(AdaxCloudCoordinator, entry.runtime_data)
# Create individual energy sensors for each device
async_add_entities(
[
AdaxSensor(cloud_coordinator, entity_description, device_id)
for device_id in cloud_coordinator.data
for entity_description in SENSORS
]
)
class AdaxSensor(CoordinatorEntity[AdaxCloudCoordinator], SensorEntity):
"""Representation of an Adax sensor."""
entity_description: AdaxSensorDescription
_attr_has_entity_name = True
def __init__(
self,
coordinator: AdaxCloudCoordinator,
entity_description: AdaxSensorDescription,
device_id: str,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.entity_description = entity_description
self._device_id = device_id
room = coordinator.data[device_id]
self._attr_unique_id = (
f"{room['homeId']}_{device_id}_{self.entity_description.key}"
)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device_id)},
name=room["name"],
manufacturer="Adax",
)
@property
def available(self) -> bool:
"""Return True if entity is available."""
return (
super().available
and self.entity_description.data_key
in self.coordinator.data[self._device_id]
)
@property
def native_value(self) -> int | float | None:
"""Return the native value of the sensor."""
return self.coordinator.data[self._device_id].get(
self.entity_description.data_key
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/adax/sensor.py",
"license": "Apache License 2.0",
"lines": 94,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ai_task/const.py | """Constants for the AI Task integration."""
from __future__ import annotations
from enum import IntFlag
from typing import TYPE_CHECKING, Final
from homeassistant.util.hass_dict import HassKey
if TYPE_CHECKING:
from homeassistant.components.media_source import local_source
from homeassistant.helpers.entity_component import EntityComponent
from . import AITaskPreferences
from .entity import AITaskEntity
DOMAIN = "ai_task"
DATA_COMPONENT: HassKey[EntityComponent[AITaskEntity]] = HassKey(DOMAIN)
DATA_PREFERENCES: HassKey[AITaskPreferences] = HassKey(f"{DOMAIN}_preferences")
DATA_MEDIA_SOURCE: HassKey[local_source.LocalSource] = HassKey(f"{DOMAIN}_media_source")
IMAGE_DIR: Final = "image"
IMAGE_EXPIRY_TIME = 60 * 60 # 1 hour
SERVICE_GENERATE_DATA = "generate_data"
SERVICE_GENERATE_IMAGE = "generate_image"
ATTR_INSTRUCTIONS: Final = "instructions"
ATTR_TASK_NAME: Final = "task_name"
ATTR_STRUCTURE: Final = "structure"
ATTR_REQUIRED: Final = "required"
ATTR_ATTACHMENTS: Final = "attachments"
DEFAULT_SYSTEM_PROMPT = (
"You are a Home Assistant expert and help users with their tasks."
)
class AITaskEntityFeature(IntFlag):
"""Supported features of the AI task entity."""
GENERATE_DATA = 1
"""Generate data based on instructions."""
SUPPORT_ATTACHMENTS = 2
"""Support attachments with generate data."""
GENERATE_IMAGE = 4
"""Generate images based on instructions."""
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ai_task/const.py",
"license": "Apache License 2.0",
"lines": 34,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ai_task/entity.py | """Entity for the AI Task integration."""
from collections.abc import AsyncGenerator
import contextlib
from typing import final
from propcache.api import cached_property
from homeassistant.components.conversation import (
ChatLog,
UserContent,
async_get_chat_log,
)
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.helpers import llm
from homeassistant.helpers.chat_session import ChatSession
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.util import dt as dt_util
from .const import DEFAULT_SYSTEM_PROMPT, DOMAIN, AITaskEntityFeature
from .task import GenDataTask, GenDataTaskResult, GenImageTask, GenImageTaskResult
class AITaskEntity(RestoreEntity):
"""Entity that supports conversations."""
_attr_should_poll = False
_attr_supported_features = AITaskEntityFeature(0)
__last_activity: str | None = None
@property
@final
def state(self) -> str | None:
"""Return the state of the entity."""
if self.__last_activity is None:
return None
return self.__last_activity
@cached_property
def supported_features(self) -> AITaskEntityFeature:
"""Flag supported features."""
return self._attr_supported_features
async def async_internal_added_to_hass(self) -> None:
"""Call when the entity is added to hass."""
await super().async_internal_added_to_hass()
state = await self.async_get_last_state()
if (
state is not None
and state.state is not None
and state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN)
):
self.__last_activity = state.state
@final
@contextlib.asynccontextmanager
async def _async_get_ai_task_chat_log(
self,
session: ChatSession,
task: GenDataTask | GenImageTask,
) -> AsyncGenerator[ChatLog]:
"""Context manager used to manage the ChatLog used during an AI Task."""
user_llm_hass_api: llm.API | None = None
if isinstance(task, GenDataTask):
user_llm_hass_api = task.llm_api
# pylint: disable-next=contextmanager-generator-missing-cleanup
with (
async_get_chat_log(
self.hass,
session,
None,
) as chat_log,
):
await chat_log.async_provide_llm_data(
llm.LLMContext(
platform=self.platform.domain,
context=None,
language=None,
assistant=DOMAIN,
device_id=None,
),
user_llm_prompt=DEFAULT_SYSTEM_PROMPT,
user_llm_hass_api=user_llm_hass_api,
)
chat_log.async_add_user_content(
UserContent(task.instructions, attachments=task.attachments)
)
yield chat_log
@final
async def internal_async_generate_data(
self,
session: ChatSession,
task: GenDataTask,
) -> GenDataTaskResult:
"""Run a gen data task."""
self.__last_activity = dt_util.utcnow().isoformat()
self.async_write_ha_state()
async with self._async_get_ai_task_chat_log(session, task) as chat_log:
return await self._async_generate_data(task, chat_log)
async def _async_generate_data(
self,
task: GenDataTask,
chat_log: ChatLog,
) -> GenDataTaskResult:
"""Handle a gen data task."""
raise NotImplementedError
@final
async def internal_async_generate_image(
self,
session: ChatSession,
task: GenImageTask,
) -> GenImageTaskResult:
"""Run a gen image task."""
self.__last_activity = dt_util.utcnow().isoformat()
self.async_write_ha_state()
async with self._async_get_ai_task_chat_log(session, task) as chat_log:
return await self._async_generate_image(task, chat_log)
async def _async_generate_image(
self,
task: GenImageTask,
chat_log: ChatLog,
) -> GenImageTaskResult:
"""Handle a gen image task."""
raise NotImplementedError
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ai_task/entity.py",
"license": "Apache License 2.0",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ai_task/http.py | """HTTP endpoint for AI Task integration."""
from typing import Any
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.core import HomeAssistant, callback
from .const import DATA_PREFERENCES
@callback
def async_setup(hass: HomeAssistant) -> None:
"""Set up the HTTP API for the conversation integration."""
websocket_api.async_register_command(hass, websocket_get_preferences)
websocket_api.async_register_command(hass, websocket_set_preferences)
@websocket_api.websocket_command(
{
vol.Required("type"): "ai_task/preferences/get",
}
)
@callback
def websocket_get_preferences(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Get AI task preferences."""
preferences = hass.data[DATA_PREFERENCES]
connection.send_result(msg["id"], preferences.as_dict())
@websocket_api.websocket_command(
{
vol.Required("type"): "ai_task/preferences/set",
vol.Optional("gen_data_entity_id"): vol.Any(str, None),
vol.Optional("gen_image_entity_id"): vol.Any(str, None),
}
)
@websocket_api.require_admin
@callback
def websocket_set_preferences(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Set AI task preferences."""
preferences = hass.data[DATA_PREFERENCES]
msg.pop("type")
msg_id = msg.pop("id")
preferences.async_set_preferences(**msg)
connection.send_result(msg_id, preferences.as_dict())
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ai_task/http.py",
"license": "Apache License 2.0",
"lines": 45,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ai_task/task.py | """AI tasks to be handled by agents."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta
import io
import mimetypes
from pathlib import Path
import tempfile
from typing import Any
import voluptuous as vol
from homeassistant.components import camera, conversation, image, media_source
from homeassistant.components.http.auth import async_sign_path
from homeassistant.core import HomeAssistant, ServiceResponse, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import llm
from homeassistant.helpers.chat_session import ChatSession, async_get_chat_session
from homeassistant.util import RE_SANITIZE_FILENAME, slugify
from .const import (
DATA_COMPONENT,
DATA_MEDIA_SOURCE,
DATA_PREFERENCES,
DOMAIN,
IMAGE_DIR,
IMAGE_EXPIRY_TIME,
AITaskEntityFeature,
)
def _save_camera_snapshot(image_data: camera.Image | image.Image) -> Path:
"""Save camera snapshot to temp file."""
with tempfile.NamedTemporaryFile(
mode="wb",
suffix=mimetypes.guess_extension(image_data.content_type, False),
delete=False,
) as temp_file:
temp_file.write(image_data.content)
return Path(temp_file.name)
async def _resolve_attachments(
hass: HomeAssistant,
session: ChatSession,
attachments: list[dict] | None = None,
) -> list[conversation.Attachment]:
"""Resolve attachments for a task."""
resolved_attachments: list[conversation.Attachment] = []
created_files: list[Path] = []
for attachment in attachments or []:
media_content_id = attachment["media_content_id"]
# Special case for certain media sources
for integration in camera, image:
media_source_prefix = f"media-source://{integration.DOMAIN}/"
if not media_content_id.startswith(media_source_prefix):
continue
# Extract entity_id from the media content ID
entity_id = media_content_id.removeprefix(media_source_prefix)
# Get snapshot from entity
image_data = await integration.async_get_image(hass, entity_id)
temp_filename = await hass.async_add_executor_job(
_save_camera_snapshot, image_data
)
created_files.append(temp_filename)
resolved_attachments.append(
conversation.Attachment(
media_content_id=media_content_id,
mime_type=image_data.content_type,
path=temp_filename,
)
)
break
else:
# Handle regular media sources
media = await media_source.async_resolve_media(hass, media_content_id, None)
if media.path is None:
raise HomeAssistantError(
"Only local attachments are currently supported"
)
resolved_attachments.append(
conversation.Attachment(
media_content_id=media_content_id,
mime_type=media.mime_type,
path=media.path,
)
)
if not created_files:
return resolved_attachments
def cleanup_files() -> None:
"""Cleanup temporary files."""
for file in created_files:
file.unlink(missing_ok=True)
@callback
def cleanup_files_callback() -> None:
"""Cleanup temporary files."""
hass.async_add_executor_job(cleanup_files)
session.async_on_cleanup(cleanup_files_callback)
return resolved_attachments
async def async_generate_data(
hass: HomeAssistant,
*,
task_name: str,
entity_id: str | None = None,
instructions: str,
structure: vol.Schema | None = None,
attachments: list[dict] | None = None,
llm_api: llm.API | None = None,
) -> GenDataTaskResult:
"""Run a data generation task in the AI Task integration."""
if entity_id is None:
entity_id = hass.data[DATA_PREFERENCES].gen_data_entity_id
if entity_id is None:
raise HomeAssistantError("No entity_id provided and no preferred entity set")
entity = hass.data[DATA_COMPONENT].get_entity(entity_id)
if entity is None:
raise HomeAssistantError(f"AI Task entity {entity_id} not found")
if AITaskEntityFeature.GENERATE_DATA not in entity.supported_features:
raise HomeAssistantError(
f"AI Task entity {entity_id} does not support generating data"
)
if (
attachments
and AITaskEntityFeature.SUPPORT_ATTACHMENTS not in entity.supported_features
):
raise HomeAssistantError(
f"AI Task entity {entity_id} does not support attachments"
)
with async_get_chat_session(hass) as session:
resolved_attachments = await _resolve_attachments(hass, session, attachments)
return await entity.internal_async_generate_data(
session,
GenDataTask(
name=task_name,
instructions=instructions,
structure=structure,
attachments=resolved_attachments or None,
llm_api=llm_api,
),
)
async def async_generate_image(
hass: HomeAssistant,
*,
task_name: str,
entity_id: str | None = None,
instructions: str,
attachments: list[dict] | None = None,
) -> ServiceResponse:
"""Run an image generation task in the AI Task integration."""
if entity_id is None:
entity_id = hass.data[DATA_PREFERENCES].gen_image_entity_id
if entity_id is None:
raise HomeAssistantError("No entity_id provided and no preferred entity set")
entity = hass.data[DATA_COMPONENT].get_entity(entity_id)
if entity is None:
raise HomeAssistantError(f"AI Task entity {entity_id} not found")
if AITaskEntityFeature.GENERATE_IMAGE not in entity.supported_features:
raise HomeAssistantError(
f"AI Task entity {entity_id} does not support generating images"
)
if (
attachments
and AITaskEntityFeature.SUPPORT_ATTACHMENTS not in entity.supported_features
):
raise HomeAssistantError(
f"AI Task entity {entity_id} does not support attachments"
)
with async_get_chat_session(hass) as session:
resolved_attachments = await _resolve_attachments(hass, session, attachments)
task_result = await entity.internal_async_generate_image(
session,
GenImageTask(
name=task_name,
instructions=instructions,
attachments=resolved_attachments or None,
),
)
service_result = task_result.as_dict()
image_data = service_result.pop("image_data")
if service_result.get("revised_prompt") is None:
service_result["revised_prompt"] = instructions
source = hass.data[DATA_MEDIA_SOURCE]
current_time = datetime.now()
ext = mimetypes.guess_extension(task_result.mime_type, False) or ".png"
sanitized_task_name = RE_SANITIZE_FILENAME.sub("", slugify(task_name))
image_file = ImageData(
filename=f"{current_time.strftime('%Y-%m-%d_%H%M%S')}_{sanitized_task_name}{ext}",
file=io.BytesIO(image_data),
content_type=task_result.mime_type,
)
target_folder = media_source.MediaSourceItem.from_uri(
hass, f"media-source://{DOMAIN}/{IMAGE_DIR}", None
)
service_result["media_source_id"] = await source.async_upload_media(
target_folder, image_file
)
item = media_source.MediaSourceItem.from_uri(
hass, service_result["media_source_id"], None
)
service_result["url"] = async_sign_path(
hass,
(await source.async_resolve_media(item)).url,
timedelta(seconds=IMAGE_EXPIRY_TIME),
)
return service_result
@dataclass(slots=True)
class GenDataTask:
"""Gen data task to be processed."""
name: str
"""Name of the task."""
instructions: str
"""Instructions on what needs to be done."""
structure: vol.Schema | None = None
"""Optional structure for the data to be generated."""
attachments: list[conversation.Attachment] | None = None
"""List of attachments to go along the instructions."""
llm_api: llm.API | None = None
"""API to provide to the LLM."""
def __str__(self) -> str:
"""Return task as a string."""
return f"<GenDataTask {self.name}: {id(self)}>"
@dataclass(slots=True)
class GenDataTaskResult:
"""Result of gen data task."""
conversation_id: str
"""Unique identifier for the conversation."""
data: Any
"""Data generated by the task."""
def as_dict(self) -> dict[str, Any]:
"""Return result as a dict."""
return {
"conversation_id": self.conversation_id,
"data": self.data,
}
@dataclass(slots=True)
class GenImageTask:
"""Gen image task to be processed."""
name: str
"""Name of the task."""
instructions: str
"""Instructions on what needs to be done."""
attachments: list[conversation.Attachment] | None = None
"""List of attachments to go along the instructions."""
def __str__(self) -> str:
"""Return task as a string."""
return f"<GenImageTask {self.name}: {id(self)}>"
@dataclass(slots=True)
class GenImageTaskResult:
"""Result of gen image task."""
image_data: bytes
"""Raw image data generated by the model."""
conversation_id: str
"""Unique identifier for the conversation."""
mime_type: str
"""MIME type of the generated image."""
width: int | None = None
"""Width of the generated image, if available."""
height: int | None = None
"""Height of the generated image, if available."""
model: str | None = None
"""Model used to generate the image, if available."""
revised_prompt: str | None = None
"""Revised prompt used to generate the image, if applicable."""
def as_dict(self) -> dict[str, Any]:
"""Return result as a dict."""
return {
"image_data": self.image_data,
"conversation_id": self.conversation_id,
"mime_type": self.mime_type,
"width": self.width,
"height": self.height,
"model": self.model,
"revised_prompt": self.revised_prompt,
}
@dataclass(slots=True)
class ImageData:
"""Implementation of media_source.local_source.UploadedFile protocol."""
filename: str
file: io.IOBase
content_type: str
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ai_task/task.py",
"license": "Apache License 2.0",
"lines": 273,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/airthings/coordinator.py | """The Airthings integration."""
from datetime import timedelta
import logging
from airthings import Airthings, AirthingsDevice, AirthingsError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minutes=6)
type AirthingsConfigEntry = ConfigEntry[AirthingsDataUpdateCoordinator]
class AirthingsDataUpdateCoordinator(DataUpdateCoordinator[dict[str, AirthingsDevice]]):
"""Coordinator for Airthings data updates."""
def __init__(
self,
hass: HomeAssistant,
airthings: Airthings,
config_entry: AirthingsConfigEntry,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=DOMAIN,
update_method=self._update_method,
update_interval=SCAN_INTERVAL,
)
self.airthings = airthings
async def _update_method(self) -> dict[str, AirthingsDevice]:
"""Get the latest data from Airthings."""
try:
return await self.airthings.update_devices() # type: ignore[no-any-return]
except AirthingsError as err:
raise UpdateFailed(f"Unable to fetch data: {err}") from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/airthings/coordinator.py",
"license": "Apache License 2.0",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/alexa_devices/sensor.py | """Support for sensors."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import Final
from aioamazondevices.const.schedules import (
NOTIFICATION_ALARM,
NOTIFICATION_REMINDER,
NOTIFICATION_TIMER,
)
from aioamazondevices.structures import AmazonDevice
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_PARTS_PER_MILLION,
LIGHT_LUX,
PERCENTAGE,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .const import CATEGORY_NOTIFICATIONS, CATEGORY_SENSORS
from .coordinator import AmazonConfigEntry
from .entity import AmazonEntity
from .utils import async_remove_unsupported_notification_sensors
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class AmazonSensorEntityDescription(SensorEntityDescription):
"""Amazon Devices sensor entity description."""
native_unit_of_measurement_fn: Callable[[AmazonDevice, str], str] | None = None
is_available_fn: Callable[[AmazonDevice, str], bool] = lambda device, key: (
device.online
and (sensor := device.sensors.get(key)) is not None
and sensor.error is False
)
category: str = CATEGORY_SENSORS
@dataclass(frozen=True, kw_only=True)
class AmazonNotificationEntityDescription(SensorEntityDescription):
"""Amazon Devices notification entity description."""
native_unit_of_measurement_fn: Callable[[AmazonDevice, str], str] | None = None
is_available_fn: Callable[[AmazonDevice, str], bool] = lambda device, key: (
device.online
and (notification := device.notifications.get(key)) is not None
and notification.next_occurrence is not None
)
category: str = CATEGORY_NOTIFICATIONS
SENSORS: Final = (
AmazonSensorEntityDescription(
key="temperature",
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement_fn=lambda device, key: (
UnitOfTemperature.CELSIUS
if key in device.sensors and device.sensors[key].scale == "CELSIUS"
else UnitOfTemperature.FAHRENHEIT
),
state_class=SensorStateClass.MEASUREMENT,
),
AmazonSensorEntityDescription(
key="illuminance",
device_class=SensorDeviceClass.ILLUMINANCE,
native_unit_of_measurement=LIGHT_LUX,
state_class=SensorStateClass.MEASUREMENT,
),
AmazonSensorEntityDescription(
key="Humidity",
device_class=SensorDeviceClass.HUMIDITY,
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
),
AmazonSensorEntityDescription(
key="PM10",
device_class=SensorDeviceClass.PM10,
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
state_class=SensorStateClass.MEASUREMENT,
),
AmazonSensorEntityDescription(
key="PM25",
device_class=SensorDeviceClass.PM25,
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
state_class=SensorStateClass.MEASUREMENT,
),
AmazonSensorEntityDescription(
key="CO",
device_class=SensorDeviceClass.CO,
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
state_class=SensorStateClass.MEASUREMENT,
),
AmazonSensorEntityDescription(
key="VOC",
# No device class as this is an index not a concentration
state_class=SensorStateClass.MEASUREMENT,
translation_key="voc_index",
),
AmazonSensorEntityDescription(
key="Air Quality",
device_class=SensorDeviceClass.AQI,
state_class=SensorStateClass.MEASUREMENT,
),
)
NOTIFICATIONS: Final = (
AmazonNotificationEntityDescription(
key=NOTIFICATION_ALARM,
translation_key="alarm",
device_class=SensorDeviceClass.TIMESTAMP,
),
AmazonNotificationEntityDescription(
key=NOTIFICATION_REMINDER,
translation_key="reminder",
device_class=SensorDeviceClass.TIMESTAMP,
),
AmazonNotificationEntityDescription(
key=NOTIFICATION_TIMER,
translation_key="timer",
device_class=SensorDeviceClass.TIMESTAMP,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: AmazonConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Amazon Devices sensors based on a config entry."""
coordinator = entry.runtime_data
# Remove notification sensors from unsupported devices
await async_remove_unsupported_notification_sensors(hass, coordinator)
known_devices: set[str] = set()
def _check_device() -> None:
current_devices = set(coordinator.data)
new_devices = current_devices - known_devices
if new_devices:
known_devices.update(new_devices)
sensors_list = [
AmazonSensorEntity(coordinator, serial_num, sensor_desc)
for sensor_desc in SENSORS
for serial_num in new_devices
if coordinator.data[serial_num].sensors.get(sensor_desc.key) is not None
]
notifications_list = [
AmazonSensorEntity(coordinator, serial_num, notification_desc)
for notification_desc in NOTIFICATIONS
for serial_num in new_devices
if coordinator.data[serial_num].notifications_supported
]
async_add_entities(sensors_list + notifications_list)
_check_device()
entry.async_on_unload(coordinator.async_add_listener(_check_device))
class AmazonSensorEntity(AmazonEntity, SensorEntity):
"""Sensor device."""
entity_description: (
AmazonSensorEntityDescription | AmazonNotificationEntityDescription
)
@property
def native_unit_of_measurement(self) -> str | None:
"""Return the unit of measurement of the sensor."""
if self.entity_description.native_unit_of_measurement_fn:
return self.entity_description.native_unit_of_measurement_fn(
self.device, self.entity_description.key
)
return super().native_unit_of_measurement
@property
def native_value(self) -> StateType | datetime:
"""Return the state of the sensor."""
# Sensors
if self.entity_description.category == CATEGORY_SENSORS:
return self.device.sensors[self.entity_description.key].value
# Notifications
return self.device.notifications[self.entity_description.key].next_occurrence
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
self.entity_description.is_available_fn(
self.device, self.entity_description.key
)
and super().available
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/sensor.py",
"license": "Apache License 2.0",
"lines": 184,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/alexa_devices/utils.py | """Utils for Alexa Devices."""
from collections.abc import Awaitable, Callable, Coroutine
from functools import wraps
from typing import Any, Concatenate
from aioamazondevices.const.devices import SPEAKER_GROUP_FAMILY
from aioamazondevices.const.schedules import (
NOTIFICATION_ALARM,
NOTIFICATION_REMINDER,
NOTIFICATION_TIMER,
)
from aioamazondevices.exceptions import CannotConnect, CannotRetrieveData
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.entity_registry as er
from .const import _LOGGER, DOMAIN
from .coordinator import AmazonDevicesCoordinator
from .entity import AmazonEntity
def alexa_api_call[_T: AmazonEntity, **_P](
func: Callable[Concatenate[_T, _P], Awaitable[None]],
) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, None]]:
"""Catch Alexa API call exceptions."""
@wraps(func)
async def cmd_wrapper(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> None:
"""Wrap all command methods."""
try:
await func(self, *args, **kwargs)
except CannotConnect as err:
self.coordinator.last_update_success = False
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="cannot_connect_with_error",
translation_placeholders={"error": repr(err)},
) from err
except CannotRetrieveData as err:
self.coordinator.last_update_success = False
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="cannot_retrieve_data_with_error",
translation_placeholders={"error": repr(err)},
) from err
return cmd_wrapper
async def async_update_unique_id(
hass: HomeAssistant,
coordinator: AmazonDevicesCoordinator,
platform: str,
old_key: str,
new_key: str,
) -> None:
"""Update unique id for entities created with old format."""
entity_registry = er.async_get(hass)
for serial_num in coordinator.data:
unique_id = f"{serial_num}-{old_key}"
if entity_id := entity_registry.async_get_entity_id(
DOMAIN, platform, unique_id
):
_LOGGER.debug("Updating unique_id for %s", entity_id)
new_unique_id = unique_id.replace(old_key, new_key)
# Update the registry with the new unique_id
entity_registry.async_update_entity(entity_id, new_unique_id=new_unique_id)
async def async_remove_dnd_from_virtual_group(
hass: HomeAssistant,
coordinator: AmazonDevicesCoordinator,
key: str,
) -> None:
"""Remove entity DND from virtual group."""
entity_registry = er.async_get(hass)
for serial_num in coordinator.data:
unique_id = f"{serial_num}-{key}"
entity_id = entity_registry.async_get_entity_id(
DOMAIN, SWITCH_DOMAIN, unique_id
)
is_group = coordinator.data[serial_num].device_family == SPEAKER_GROUP_FAMILY
if entity_id and is_group:
entity_registry.async_remove(entity_id)
_LOGGER.debug("Removed DND switch from virtual group %s", entity_id)
async def async_remove_unsupported_notification_sensors(
hass: HomeAssistant,
coordinator: AmazonDevicesCoordinator,
) -> None:
"""Remove notification sensors from unsupported devices."""
entity_registry = er.async_get(hass)
for serial_num in coordinator.data:
for notification_key in (
NOTIFICATION_ALARM,
NOTIFICATION_REMINDER,
NOTIFICATION_TIMER,
):
unique_id = f"{serial_num}-{notification_key}"
entity_id = entity_registry.async_get_entity_id(
DOMAIN, SENSOR_DOMAIN, unique_id=unique_id
)
is_unsupported = not coordinator.data[serial_num].notifications_supported
if entity_id and is_unsupported:
entity_registry.async_remove(entity_id)
_LOGGER.debug("Removed unsupported notification sensor %s", entity_id)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/utils.py",
"license": "Apache License 2.0",
"lines": 97,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/altruist/config_flow.py | """Config flow for the Altruist integration."""
import logging
from typing import Any
from altruistclient import AltruistClient, AltruistDeviceModel, AltruistError
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from .const import CONF_HOST, DOMAIN
_LOGGER = logging.getLogger(__name__)
class AltruistConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Altruist."""
device: AltruistDeviceModel
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
ip_address = ""
if user_input is not None:
ip_address = user_input[CONF_HOST]
try:
client = await AltruistClient.from_ip_address(
async_get_clientsession(self.hass), ip_address
)
except AltruistError:
errors["base"] = "no_device_found"
else:
self.device = client.device
await self.async_set_unique_id(
client.device_id, raise_on_progress=False
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=self.device.id,
data={
CONF_HOST: ip_address,
},
)
data_schema = self.add_suggested_values_to_schema(
vol.Schema({vol.Required(CONF_HOST): str}),
{CONF_HOST: ip_address},
)
return self.async_show_form(
step_id="user",
data_schema=data_schema,
errors=errors,
description_placeholders={
"ip_address": ip_address,
},
)
async def async_step_zeroconf(
self, discovery_info: ZeroconfServiceInfo
) -> ConfigFlowResult:
"""Handle zeroconf discovery."""
_LOGGER.debug("Zeroconf discovery: %s", discovery_info)
try:
client = await AltruistClient.from_ip_address(
async_get_clientsession(self.hass), str(discovery_info.ip_address)
)
except AltruistError:
return self.async_abort(reason="no_device_found")
self.device = client.device
_LOGGER.debug("Zeroconf device: %s", client.device)
await self.async_set_unique_id(client.device_id)
self._abort_if_unique_id_configured()
self.context.update(
{
"title_placeholders": {
"name": self.device.id,
}
}
)
return await self.async_step_discovery_confirm()
async def async_step_discovery_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm discovery."""
if user_input is not None:
return self.async_create_entry(
title=self.device.id,
data={
CONF_HOST: self.device.ip_address,
},
)
self._set_confirm_only()
return self.async_show_form(
step_id="discovery_confirm",
description_placeholders={
"model": self.device.id,
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/altruist/config_flow.py",
"license": "Apache License 2.0",
"lines": 92,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/altruist/coordinator.py | """Coordinator module for Altruist integration in Home Assistant.
This module defines the AltruistDataUpdateCoordinator class, which manages
data updates for Altruist sensors using the AltruistClient.
"""
from datetime import timedelta
import logging
from altruistclient import AltruistClient, AltruistError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_HOST
_LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = timedelta(seconds=15)
type AltruistConfigEntry = ConfigEntry[AltruistDataUpdateCoordinator]
class AltruistDataUpdateCoordinator(DataUpdateCoordinator[dict[str, str]]):
"""Coordinates data updates for Altruist sensors."""
client: AltruistClient
def __init__(
self,
hass: HomeAssistant,
config_entry: AltruistConfigEntry,
) -> None:
"""Initialize the data update coordinator for Altruist sensors."""
device_id = config_entry.unique_id
super().__init__(
hass,
logger=_LOGGER,
config_entry=config_entry,
name=f"Altruist {device_id}",
update_interval=UPDATE_INTERVAL,
)
self._ip_address = config_entry.data[CONF_HOST]
async def _async_setup(self) -> None:
try:
self.client = await AltruistClient.from_ip_address(
async_get_clientsession(self.hass), self._ip_address
)
await self.client.fetch_data()
except AltruistError as e:
raise ConfigEntryNotReady("Error in Altruist setup") from e
async def _async_update_data(self) -> dict[str, str]:
try:
fetched_data = await self.client.fetch_data()
except AltruistError as ex:
raise UpdateFailed(
f"The Altruist {self.client.device_id} is unavailable: {ex}"
) from ex
return {item["value_type"]: item["value"] for item in fetched_data}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/altruist/coordinator.py",
"license": "Apache License 2.0",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/altruist/sensor.py | """Defines the Altruist sensor platform."""
from collections.abc import Callable
from dataclasses import dataclass
import logging
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_PARTS_PER_MILLION,
PERCENTAGE,
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
EntityCategory,
UnitOfPressure,
UnitOfSoundPressure,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import AltruistConfigEntry
from .coordinator import AltruistDataUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True)
class AltruistSensorEntityDescription(SensorEntityDescription):
"""Class to describe a Sensor entity."""
native_value_fn: Callable[[str], float] = float
state_class = SensorStateClass.MEASUREMENT
SENSOR_DESCRIPTIONS = [
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.HUMIDITY,
key="BME280_humidity",
translation_key="humidity",
native_unit_of_measurement=PERCENTAGE,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "BME280"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.PRESSURE,
key="BME280_pressure",
translation_key="pressure",
native_unit_of_measurement=UnitOfPressure.PA,
suggested_unit_of_measurement=UnitOfPressure.MMHG,
suggested_display_precision=0,
translation_placeholders={"sensor_name": "BME280"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.TEMPERATURE,
key="BME280_temperature",
translation_key="temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "BME280"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.HUMIDITY,
key="BME680_humidity",
translation_key="humidity",
native_unit_of_measurement=PERCENTAGE,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "BME680"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.PRESSURE,
key="BME680_pressure",
translation_key="pressure",
native_unit_of_measurement=UnitOfPressure.PA,
suggested_unit_of_measurement=UnitOfPressure.MMHG,
suggested_display_precision=0,
translation_placeholders={"sensor_name": "BME680"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.TEMPERATURE,
key="BME680_temperature",
translation_key="temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "BME680"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.PRESSURE,
key="BMP_pressure",
translation_key="pressure",
native_unit_of_measurement=UnitOfPressure.PA,
suggested_unit_of_measurement=UnitOfPressure.MMHG,
suggested_display_precision=0,
translation_placeholders={"sensor_name": "BMP"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.TEMPERATURE,
key="BMP_temperature",
translation_key="temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "BMP"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.TEMPERATURE,
key="BMP280_temperature",
translation_key="temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "BMP280"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.PRESSURE,
key="BMP280_pressure",
translation_key="pressure",
native_unit_of_measurement=UnitOfPressure.PA,
suggested_unit_of_measurement=UnitOfPressure.MMHG,
suggested_display_precision=0,
translation_placeholders={"sensor_name": "BMP280"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.HUMIDITY,
key="HTU21D_humidity",
translation_key="humidity",
native_unit_of_measurement=PERCENTAGE,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "HTU21D"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.TEMPERATURE,
key="HTU21D_temperature",
translation_key="temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "HTU21D"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.PM10,
translation_key="pm_10",
key="SDS_P1",
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
suggested_display_precision=2,
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.PM25,
translation_key="pm_25",
key="SDS_P2",
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
suggested_display_precision=2,
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.HUMIDITY,
key="SHT3X_humidity",
translation_key="humidity",
native_unit_of_measurement=PERCENTAGE,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "SHT3X"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.TEMPERATURE,
key="SHT3X_temperature",
translation_key="temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
suggested_display_precision=2,
translation_placeholders={"sensor_name": "SHT3X"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.SIGNAL_STRENGTH,
key="signal",
native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
entity_category=EntityCategory.DIAGNOSTIC,
suggested_display_precision=0,
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.SOUND_PRESSURE,
key="PCBA_noiseMax",
translation_key="noise_max",
native_unit_of_measurement=UnitOfSoundPressure.DECIBEL,
suggested_display_precision=0,
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.SOUND_PRESSURE,
key="PCBA_noiseAvg",
translation_key="noise_avg",
native_unit_of_measurement=UnitOfSoundPressure.DECIBEL,
suggested_display_precision=0,
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.CO2,
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
translation_key="co2",
key="CCS_CO2",
suggested_display_precision=2,
translation_placeholders={"sensor_name": "CCS"},
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS,
key="CCS_TVOC",
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
suggested_display_precision=2,
),
AltruistSensorEntityDescription(
key="GC",
native_unit_of_measurement="μR/h",
translation_key="radiation",
suggested_display_precision=2,
),
AltruistSensorEntityDescription(
device_class=SensorDeviceClass.CO2,
translation_key="co2",
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
key="SCD4x_co2",
suggested_display_precision=2,
translation_placeholders={"sensor_name": "SCD4x"},
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: AltruistConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add sensors for passed config_entry in HA."""
coordinator = config_entry.runtime_data
async_add_entities(
AltruistSensor(coordinator, sensor_description)
for sensor_description in SENSOR_DESCRIPTIONS
if sensor_description.key in coordinator.data
)
class AltruistSensor(CoordinatorEntity[AltruistDataUpdateCoordinator], SensorEntity):
"""Implementation of a Altruist sensor."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: AltruistDataUpdateCoordinator,
description: AltruistSensorEntityDescription,
) -> None:
"""Initialize the Altruist sensor."""
super().__init__(coordinator)
self._device = coordinator.client.device
self.entity_description: AltruistSensorEntityDescription = description
self._attr_unique_id = f"{self._device.id}-{description.key}"
self._attr_device_info = DeviceInfo(
connections={(CONNECTION_NETWORK_MAC, self._device.id)},
manufacturer="Robonomics",
model="Altruist",
sw_version=self._device.fw_version,
configuration_url=f"http://{self._device.ip_address}",
serial_number=self._device.id,
)
@property
def available(self) -> bool:
"""Return True if entity is available."""
return (
super().available and self.entity_description.key in self.coordinator.data
)
@property
def native_value(self) -> float | int:
"""Return the native value of the sensor."""
string_value = self.coordinator.data[self.entity_description.key]
return self.entity_description.native_value_fn(string_value)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/altruist/sensor.py",
"license": "Apache License 2.0",
"lines": 257,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/amcrest/services.py | """Support for Amcrest IP cameras."""
from __future__ import annotations
from homeassistant.auth.models import User
from homeassistant.auth.permissions.const import POLICY_CONTROL
from homeassistant.const import ATTR_ENTITY_ID, ENTITY_MATCH_ALL, ENTITY_MATCH_NONE
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import Unauthorized, UnknownUser
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.service import async_extract_entity_ids
from .camera import CAMERA_SERVICES
from .const import CAMERAS, DATA_AMCREST, DOMAIN
from .helpers import service_signal
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up the Amcrest IP Camera services."""
def have_permission(user: User | None, entity_id: str) -> bool:
return not user or user.permissions.check_entity(entity_id, POLICY_CONTROL)
async def async_extract_from_service(call: ServiceCall) -> list[str]:
if call.context.user_id:
user = await hass.auth.async_get_user(call.context.user_id)
if user is None:
raise UnknownUser(context=call.context)
else:
user = None
if call.data.get(ATTR_ENTITY_ID) == ENTITY_MATCH_ALL:
# Return all entity_ids user has permission to control.
return [
entity_id
for entity_id in hass.data[DATA_AMCREST][CAMERAS]
if have_permission(user, entity_id)
]
if call.data.get(ATTR_ENTITY_ID) == ENTITY_MATCH_NONE:
return []
call_ids = await async_extract_entity_ids(call)
entity_ids = []
for entity_id in hass.data[DATA_AMCREST][CAMERAS]:
if entity_id not in call_ids:
continue
if not have_permission(user, entity_id):
raise Unauthorized(
context=call.context, entity_id=entity_id, permission=POLICY_CONTROL
)
entity_ids.append(entity_id)
return entity_ids
async def async_service_handler(call: ServiceCall) -> None:
args = [call.data[arg] for arg in CAMERA_SERVICES[call.service][2]]
for entity_id in await async_extract_from_service(call):
async_dispatcher_send(hass, service_signal(call.service, entity_id), *args)
for service, params in CAMERA_SERVICES.items():
hass.services.async_register(DOMAIN, service, async_service_handler, params[0])
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/amcrest/services.py",
"license": "Apache License 2.0",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/elkm1/services.py | """Support the ElkM1 Gold and ElkM1 EZ8 alarm/integration panels."""
from __future__ import annotations
from elkm1_lib.elk import Elk, Panel
import voluptuous as vol
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.util import dt as dt_util
from .const import DOMAIN
from .models import ELKM1Data
SPEAK_SERVICE_SCHEMA = vol.Schema(
{
vol.Required("number"): vol.All(vol.Coerce(int), vol.Range(min=0, max=999)),
vol.Optional("prefix", default=""): cv.string,
}
)
SET_TIME_SERVICE_SCHEMA = vol.Schema(
{
vol.Optional("prefix", default=""): cv.string,
}
)
def _find_elk_by_prefix(hass: HomeAssistant, prefix: str) -> Elk | None:
"""Search all config entries for a given prefix."""
for entry in hass.config_entries.async_entries(DOMAIN):
if not entry.runtime_data:
continue
elk_data: ELKM1Data = entry.runtime_data
if elk_data.prefix == prefix:
return elk_data.elk
return None
@callback
def _async_get_elk_panel(service: ServiceCall) -> Panel:
"""Get the ElkM1 panel from a service call."""
prefix = service.data["prefix"]
elk = _find_elk_by_prefix(service.hass, prefix)
if elk is None:
raise HomeAssistantError(f"No ElkM1 with prefix '{prefix}' found")
return elk.panel
@callback
def _speak_word_service(service: ServiceCall) -> None:
_async_get_elk_panel(service).speak_word(service.data["number"])
@callback
def _speak_phrase_service(service: ServiceCall) -> None:
_async_get_elk_panel(service).speak_phrase(service.data["number"])
@callback
def _set_time_service(service: ServiceCall) -> None:
_async_get_elk_panel(service).set_time(dt_util.now())
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Create ElkM1 services."""
hass.services.async_register(
DOMAIN, "speak_word", _speak_word_service, SPEAK_SERVICE_SCHEMA
)
hass.services.async_register(
DOMAIN, "speak_phrase", _speak_phrase_service, SPEAK_SERVICE_SCHEMA
)
hass.services.async_register(
DOMAIN, "set_time", _set_time_service, SET_TIME_SERVICE_SCHEMA
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/elkm1/services.py",
"license": "Apache License 2.0",
"lines": 59,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ffmpeg/const.py | """Support for FFmpeg."""
from homeassistant.util.signal_type import SignalType
DOMAIN = "ffmpeg"
SIGNAL_FFMPEG_START = SignalType[list[str] | None]("ffmpeg.start")
SIGNAL_FFMPEG_STOP = SignalType[list[str] | None]("ffmpeg.stop")
SIGNAL_FFMPEG_RESTART = SignalType[list[str] | None]("ffmpeg.restart")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ffmpeg/const.py",
"license": "Apache License 2.0",
"lines": 6,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ffmpeg/services.py | """Support for FFmpeg."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from .const import (
DOMAIN,
SIGNAL_FFMPEG_RESTART,
SIGNAL_FFMPEG_START,
SIGNAL_FFMPEG_STOP,
)
SERVICE_START = "start"
SERVICE_STOP = "stop"
SERVICE_RESTART = "restart"
SERVICE_FFMPEG_SCHEMA = vol.Schema({vol.Optional(ATTR_ENTITY_ID): cv.entity_ids})
async def _async_service_handle(service: ServiceCall) -> None:
"""Handle service ffmpeg process."""
entity_ids: list[str] | None = service.data.get(ATTR_ENTITY_ID)
if service.service == SERVICE_START:
async_dispatcher_send(service.hass, SIGNAL_FFMPEG_START, entity_ids)
elif service.service == SERVICE_STOP:
async_dispatcher_send(service.hass, SIGNAL_FFMPEG_STOP, entity_ids)
else:
async_dispatcher_send(service.hass, SIGNAL_FFMPEG_RESTART, entity_ids)
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register FFmpeg services."""
hass.services.async_register(
DOMAIN, SERVICE_START, _async_service_handle, schema=SERVICE_FFMPEG_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_STOP, _async_service_handle, schema=SERVICE_FFMPEG_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_RESTART, _async_service_handle, schema=SERVICE_FFMPEG_SCHEMA
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ffmpeg/services.py",
"license": "Apache License 2.0",
"lines": 38,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/fritz/helpers.py | """Helpers for AVM FRITZ!Box."""
from __future__ import annotations
from collections.abc import ValuesView
import logging
from .models import FritzDevice
_LOGGER = logging.getLogger(__name__)
def _is_tracked(mac: str, current_devices: ValuesView[set[str]]) -> bool:
"""Check if device is already tracked."""
return any(mac in tracked for tracked in current_devices)
def device_filter_out_from_trackers(
mac: str,
device: FritzDevice,
current_devices: ValuesView[set[str]],
) -> bool:
"""Check if device should be filtered out from trackers."""
reason: str | None = None
if device.ip_address == "":
reason = "Missing IP"
elif _is_tracked(mac, current_devices):
reason = "Already tracked"
if reason:
_LOGGER.debug(
"Skip adding device %s [%s], reason: %s", device.hostname, mac, reason
)
return bool(reason)
def ha_is_stopping(activity: str) -> None:
"""Inform that HA is stopping."""
_LOGGER.warning("Cannot execute %s: HomeAssistant is shutting down", activity)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/fritz/helpers.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/fritz/models.py | """Models for AVM FRITZ!Box."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import NotRequired, TypedDict
from homeassistant.util import dt as dt_util
from .const import MeshRoles
@dataclass
class Device:
"""FRITZ!Box device class."""
connected: bool
connected_to: str
connection_type: str
ip_address: str
name: str
ssid: str | None
wan_access: bool | None = None
class Interface(TypedDict):
"""Interface details."""
device: str
mac: str
op_mode: str
ssid: str | None
type: str
HostAttributes = TypedDict(
"HostAttributes",
{
"Index": int,
"IPAddress": str,
"MACAddress": str,
"Active": bool,
"HostName": str,
"InterfaceType": str,
"X_AVM-DE_Port": int,
"X_AVM-DE_Speed": int,
"X_AVM-DE_UpdateAvailable": bool,
"X_AVM-DE_UpdateSuccessful": str,
"X_AVM-DE_InfoURL": str | None,
"X_AVM-DE_MACAddressList": str | None,
"X_AVM-DE_Model": str | None,
"X_AVM-DE_URL": str | None,
"X_AVM-DE_Guest": bool,
"X_AVM-DE_RequestClient": str,
"X_AVM-DE_VPN": bool,
"X_AVM-DE_WANAccess": NotRequired[str],
"X_AVM-DE_Disallow": bool,
"X_AVM-DE_IsMeshable": str,
"X_AVM-DE_Priority": str,
"X_AVM-DE_FriendlyName": str,
"X_AVM-DE_FriendlyNameIsWriteable": str,
},
)
class HostInfo(TypedDict):
"""FRITZ!Box host info class."""
mac: str
name: str
ip: str
status: bool
class FritzDevice:
"""Representation of a device connected to the FRITZ!Box."""
_connected: bool
_connected_to: str
_connection_type: str
_ip_address: str
_last_activity: datetime | None
_mac: str
_name: str
_ssid: str | None
_wan_access: bool | None
def __init__(self, mac: str, dev_info: Device, consider_home: float) -> None:
"""Initialize device info."""
self._mac = mac
self._last_activity = None
self.update(dev_info, consider_home)
def update(self, dev_info: Device, consider_home: float) -> None:
"""Update device info."""
utc_point_in_time = dt_util.utcnow()
if self._last_activity:
consider_home_evaluated = (
utc_point_in_time - self._last_activity
).total_seconds() < consider_home
else:
consider_home_evaluated = dev_info.connected
self._name = dev_info.name or self._mac.replace(":", "_")
self._connected = dev_info.connected or consider_home_evaluated
if dev_info.connected:
self._last_activity = utc_point_in_time
self._connected_to = dev_info.connected_to
self._connection_type = dev_info.connection_type
self._ip_address = dev_info.ip_address
self._ssid = dev_info.ssid
self._wan_access = dev_info.wan_access
@property
def connected_to(self) -> str:
"""Return connected status."""
return self._connected_to
@property
def connection_type(self) -> str:
"""Return connected status."""
return self._connection_type
@property
def is_connected(self) -> bool:
"""Return connected status."""
return self._connected
@property
def mac_address(self) -> str:
"""Get MAC address."""
return self._mac
@property
def hostname(self) -> str:
"""Get Name."""
return self._name
@property
def ip_address(self) -> str:
"""Get IP address."""
return self._ip_address
@property
def last_activity(self) -> datetime | None:
"""Return device last activity."""
return self._last_activity
@property
def ssid(self) -> str | None:
"""Return device connected SSID."""
return self._ssid
@property
def wan_access(self) -> bool | None:
"""Return device wan access."""
return self._wan_access
@wan_access.setter
def wan_access(self, allowed: bool) -> None:
"""Set device wan access."""
self._wan_access = allowed
class SwitchInfo(TypedDict):
"""FRITZ!Box switch info class."""
description: str
friendly_name: str
icon: str
type: str
callback_update: Callable
callback_switch: Callable
init_state: bool
@dataclass
class ConnectionInfo:
"""Fritz sensor connection information class."""
connection: str
mesh_role: MeshRoles
wan_enabled: bool
ipv6_active: bool
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/fritz/models.py",
"license": "Apache License 2.0",
"lines": 149,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/google_assistant_sdk/services.py | """Services for the Google Assistant SDK integration."""
from __future__ import annotations
import dataclasses
import voluptuous as vol
from homeassistant.core import (
HomeAssistant,
ServiceCall,
ServiceResponse,
SupportsResponse,
callback,
)
from homeassistant.helpers import config_validation as cv
from .const import DOMAIN
from .helpers import async_send_text_commands
SERVICE_SEND_TEXT_COMMAND = "send_text_command"
SERVICE_SEND_TEXT_COMMAND_FIELD_COMMAND = "command"
SERVICE_SEND_TEXT_COMMAND_FIELD_MEDIA_PLAYER = "media_player"
SERVICE_SEND_TEXT_COMMAND_SCHEMA = vol.All(
{
vol.Required(SERVICE_SEND_TEXT_COMMAND_FIELD_COMMAND): vol.All(
cv.ensure_list, [vol.All(str, vol.Length(min=1))]
),
vol.Optional(SERVICE_SEND_TEXT_COMMAND_FIELD_MEDIA_PLAYER): cv.comp_entity_ids,
},
)
async def _send_text_command(call: ServiceCall) -> ServiceResponse:
"""Send a text command to Google Assistant SDK."""
commands: list[str] = call.data[SERVICE_SEND_TEXT_COMMAND_FIELD_COMMAND]
media_players: list[str] | None = call.data.get(
SERVICE_SEND_TEXT_COMMAND_FIELD_MEDIA_PLAYER
)
command_response_list = await async_send_text_commands(
call.hass, commands, media_players
)
if call.return_response:
return {
"responses": [
dataclasses.asdict(command_response)
for command_response in command_response_list
]
}
return None
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Add the services for Google Assistant SDK."""
hass.services.async_register(
DOMAIN,
SERVICE_SEND_TEXT_COMMAND,
_send_text_command,
schema=SERVICE_SEND_TEXT_COMMAND_SCHEMA,
supports_response=SupportsResponse.OPTIONAL,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/google_assistant_sdk/services.py",
"license": "Apache License 2.0",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/google_generative_ai_conversation/entity.py | """Conversation support for the Google Generative AI Conversation integration."""
from __future__ import annotations
import asyncio
import base64
import codecs
from collections.abc import AsyncGenerator, AsyncIterator, Callable
from dataclasses import dataclass, replace
import datetime
import mimetypes
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, cast
from google.genai import Client
from google.genai.errors import APIError, ClientError
from google.genai.types import (
AutomaticFunctionCallingConfig,
Content,
ContentDict,
File,
FileState,
FunctionDeclaration,
GenerateContentConfig,
GenerateContentResponse,
GoogleSearch,
HarmCategory,
Part,
PartUnionDict,
SafetySetting,
Schema,
ThinkingConfig,
Tool,
ToolListUnion,
)
import voluptuous as vol
from voluptuous_openapi import convert
from homeassistant.components import conversation
from homeassistant.config_entries import ConfigSubentry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, llm
from homeassistant.helpers.entity import Entity
from .const import (
CONF_CHAT_MODEL,
CONF_DANGEROUS_BLOCK_THRESHOLD,
CONF_HARASSMENT_BLOCK_THRESHOLD,
CONF_HATE_BLOCK_THRESHOLD,
CONF_MAX_TOKENS,
CONF_SEXUAL_BLOCK_THRESHOLD,
CONF_TEMPERATURE,
CONF_TOP_K,
CONF_TOP_P,
CONF_USE_GOOGLE_SEARCH_TOOL,
DOMAIN,
FILE_POLLING_INTERVAL_SECONDS,
LOGGER,
RECOMMENDED_CHAT_MODEL,
RECOMMENDED_HARM_BLOCK_THRESHOLD,
RECOMMENDED_MAX_TOKENS,
RECOMMENDED_TEMPERATURE,
RECOMMENDED_TOP_K,
RECOMMENDED_TOP_P,
TIMEOUT_MILLIS,
)
if TYPE_CHECKING:
from . import GoogleGenerativeAIConfigEntry
# Max number of back and forth with the LLM to generate a response
MAX_TOOL_ITERATIONS = 10
ERROR_GETTING_RESPONSE = (
"Sorry, I had a problem getting a response from Google Generative AI."
)
SUPPORTED_SCHEMA_KEYS = {
# Gemini API does not support all of the OpenAPI schema
# SoT: https://ai.google.dev/api/caching#Schema
"type",
"format",
"description",
"nullable",
"enum",
"max_items",
"min_items",
"properties",
"required",
"items",
}
def _camel_to_snake(name: str) -> str:
"""Convert camel case to snake case."""
return "".join(["_" + c.lower() if c.isupper() else c for c in name]).lstrip("_")
def _format_schema(schema: dict[str, Any]) -> Schema:
"""Format the schema to be compatible with Gemini API."""
if subschemas := schema.get("allOf"):
for subschema in subschemas: # Gemini API does not support allOf keys
if "type" in subschema: # Fallback to first subschema with 'type' field
return _format_schema(subschema)
return _format_schema(
subschemas[0]
) # Or, if not found, to any of the subschemas
result = {}
for key, val in schema.items():
key = _camel_to_snake(key)
if key not in SUPPORTED_SCHEMA_KEYS:
continue
if key == "type":
val = val.upper()
elif key == "format":
# Gemini API does not support all formats, see: https://ai.google.dev/api/caching#Schema
# formats that are not supported are ignored
if schema.get("type") == "string" and val not in ("enum", "date-time"):
continue
if schema.get("type") == "number" and val not in ("float", "double"):
continue
if schema.get("type") == "integer" and val not in ("int32", "int64"):
continue
if schema.get("type") not in ("string", "number", "integer"):
continue
elif key == "items":
val = _format_schema(val)
elif key == "properties":
val = {k: _format_schema(v) for k, v in val.items()}
result[key] = val
if result.get("enum") and result.get("type") != "STRING":
# enum is only allowed for STRING type. This is safe as long as the schema
# contains vol.Coerce for the respective type, for example:
# vol.All(vol.Coerce(int), vol.In([1, 2, 3]))
result["type"] = "STRING"
result["enum"] = [str(item) for item in result["enum"]]
if result.get("type") == "OBJECT" and not result.get("properties"):
# An object with undefined properties is not supported by Gemini API.
# Fallback to JSON string. This will probably fail for most tools that want it,
# but we don't have a better fallback strategy so far.
result["properties"] = {"json": {"type": "STRING"}}
result["required"] = []
return cast(Schema, result)
def _format_tool(
tool: llm.Tool, custom_serializer: Callable[[Any], Any] | None
) -> Tool:
"""Format tool specification."""
if tool.parameters.schema:
parameters = _format_schema(
convert(tool.parameters, custom_serializer=custom_serializer)
)
else:
parameters = None
return Tool(
function_declarations=[
FunctionDeclaration(
name=tool.name,
description=tool.description,
parameters=parameters,
)
]
)
def _escape_decode(value: Any) -> Any:
"""Recursively call codecs.escape_decode on all values."""
if isinstance(value, str):
return codecs.escape_decode(bytes(value, "utf-8"))[0].decode("utf-8") # type: ignore[attr-defined]
if isinstance(value, list):
return [_escape_decode(item) for item in value]
if isinstance(value, dict):
return {k: _escape_decode(v) for k, v in value.items()}
return value
def _validate_tool_results(value: Any) -> Any:
"""Recursively convert non-json-serializable types."""
if isinstance(value, (datetime.time, datetime.date)):
return value.isoformat()
if isinstance(value, list):
return [_validate_tool_results(item) for item in value]
if isinstance(value, dict):
return {k: _validate_tool_results(v) for k, v in value.items()}
return value
def _create_google_tool_response_parts(
parts: list[conversation.ToolResultContent],
) -> list[Part]:
"""Create Google tool response parts."""
return [
Part.from_function_response(
name=tool_result.tool_name,
response=_validate_tool_results(tool_result.tool_result),
)
for tool_result in parts
]
def _create_google_tool_response_content(
content: list[conversation.ToolResultContent],
) -> Content:
"""Create a Google tool response content."""
return Content(
role="user",
parts=_create_google_tool_response_parts(content),
)
@dataclass(slots=True)
class PartDetails:
"""Additional data for a content part."""
part_type: Literal["text", "thought", "function_call"]
"""The part type for which this data is relevant for."""
index: int
"""Start position or number of the tool."""
length: int = 0
"""Length of the relevant data."""
thought_signature: str | None = None
"""Base64 encoded thought signature, if available."""
@dataclass(slots=True)
class ContentDetails:
"""Native data for AssistantContent."""
part_details: list[PartDetails]
def _convert_content(
content: (
conversation.UserContent
| conversation.AssistantContent
| conversation.SystemContent
),
) -> Content:
"""Convert HA content to Google content."""
if content.role != "assistant":
return Content(
role=content.role,
parts=[Part.from_text(text=content.content or "")],
)
# Handle the Assistant content with tool calls.
assert type(content) is conversation.AssistantContent
parts: list[Part] = []
part_details: list[PartDetails] = (
content.native.part_details
if isinstance(content.native, ContentDetails)
else []
)
details: PartDetails | None = None
if content.content:
index = 0
for details in part_details:
if details.part_type == "text":
if index < details.index:
parts.append(
Part.from_text(text=content.content[index : details.index])
)
index = details.index
parts.append(
Part.from_text(
text=content.content[index : index + details.length],
)
)
if details.thought_signature:
parts[-1].thought_signature = base64.b64decode(
details.thought_signature
)
index += details.length
if index < len(content.content):
parts.append(Part.from_text(text=content.content[index:]))
if content.thinking_content:
index = 0
for details in part_details:
if details.part_type == "thought":
if index < details.index:
parts.append(
Part.from_text(
text=content.thinking_content[index : details.index]
)
)
parts[-1].thought = True
index = details.index
parts.append(
Part.from_text(
text=content.thinking_content[index : index + details.length],
)
)
parts[-1].thought = True
if details.thought_signature:
parts[-1].thought_signature = base64.b64decode(
details.thought_signature
)
index += details.length
if index < len(content.thinking_content):
parts.append(Part.from_text(text=content.thinking_content[index:]))
parts[-1].thought = True
if content.tool_calls:
for index, tool_call in enumerate(content.tool_calls):
parts.append(
Part.from_function_call(
name=tool_call.tool_name,
args=_escape_decode(tool_call.tool_args),
)
)
if details := next(
(
d
for d in part_details
if d.part_type == "function_call" and d.index == index
),
None,
):
if details.thought_signature:
parts[-1].thought_signature = base64.b64decode(
details.thought_signature
)
return Content(role="model", parts=parts)
async def _transform_stream(
result: AsyncIterator[GenerateContentResponse],
) -> AsyncGenerator[conversation.AssistantContentDeltaDict]:
new_message = True
part_details: list[PartDetails] = []
try:
async for response in result:
LOGGER.debug("Received response chunk: %s", response)
if new_message:
if part_details:
yield {"native": ContentDetails(part_details=part_details)}
part_details = []
yield {"role": "assistant"}
new_message = False
content_index = 0
thinking_content_index = 0
tool_call_index = 0
# According to the API docs, this would mean no candidate is returned, so we can safely throw an error here.
if response.prompt_feedback or not response.candidates:
reason = (
response.prompt_feedback.block_reason_message
if response.prompt_feedback
else "unknown"
)
raise HomeAssistantError(
f"The message got blocked due to content violations, reason: {reason}"
)
candidate = response.candidates[0]
if (
candidate.finish_reason is not None
and candidate.finish_reason != "STOP"
):
# The message ended due to a content error as explained in: https://ai.google.dev/api/generate-content#FinishReason
LOGGER.error(
"Error in Google Generative AI response: %s, see: https://ai.google.dev/api/generate-content#FinishReason",
candidate.finish_reason,
)
raise HomeAssistantError(
f"{ERROR_GETTING_RESPONSE} Reason: {candidate.finish_reason}"
)
response_parts = (
candidate.content.parts
if candidate.content is not None and candidate.content.parts is not None
else []
)
for part in response_parts:
chunk: conversation.AssistantContentDeltaDict = {}
if part.text:
if part.thought:
chunk["thinking_content"] = part.text
if part.thought_signature:
part_details.append(
PartDetails(
part_type="thought",
index=thinking_content_index,
length=len(part.text),
thought_signature=base64.b64encode(
part.thought_signature
).decode("utf-8"),
)
)
thinking_content_index += len(part.text)
else:
chunk["content"] = part.text
if part.thought_signature:
part_details.append(
PartDetails(
part_type="text",
index=content_index,
length=len(part.text),
thought_signature=base64.b64encode(
part.thought_signature
).decode("utf-8"),
)
)
content_index += len(part.text)
if part.function_call:
tool_call = part.function_call
tool_name = tool_call.name or ""
tool_args = _escape_decode(tool_call.args)
chunk["tool_calls"] = [
llm.ToolInput(tool_name=tool_name, tool_args=tool_args)
]
if part.thought_signature:
part_details.append(
PartDetails(
part_type="function_call",
index=tool_call_index,
thought_signature=base64.b64encode(
part.thought_signature
).decode("utf-8"),
)
)
yield chunk
if part_details:
yield {"native": ContentDetails(part_details=part_details)}
except (
APIError,
ValueError,
) as err:
LOGGER.error("Error sending message: %s %s", type(err), err)
if isinstance(err, APIError):
message = err.message
else:
message = type(err).__name__
error = f"{ERROR_GETTING_RESPONSE}: {message}"
raise HomeAssistantError(error) from err
class GoogleGenerativeAILLMBaseEntity(Entity):
"""Google Generative AI base entity."""
def __init__(
self,
entry: GoogleGenerativeAIConfigEntry,
subentry: ConfigSubentry,
default_model: str = RECOMMENDED_CHAT_MODEL,
) -> None:
"""Initialize the agent."""
self.entry = entry
self.subentry = subentry
self.default_model = default_model
self._attr_name = subentry.title
self._genai_client = entry.runtime_data
self._attr_unique_id = subentry.subentry_id
self._attr_device_info = dr.DeviceInfo(
identifiers={(DOMAIN, subentry.subentry_id)},
name=subentry.title,
manufacturer="Google",
model=subentry.data.get(CONF_CHAT_MODEL, default_model).split("/")[-1],
entry_type=dr.DeviceEntryType.SERVICE,
)
async def _async_handle_chat_log(
self,
chat_log: conversation.ChatLog,
structure: vol.Schema | None = None,
default_max_tokens: int | None = None,
max_iterations: int = MAX_TOOL_ITERATIONS,
) -> None:
"""Generate an answer for the chat log."""
options = self.subentry.data
tools: ToolListUnion | None = None
if chat_log.llm_api:
tools = [
_format_tool(tool, chat_log.llm_api.custom_serializer)
for tool in chat_log.llm_api.tools
]
# Using search grounding allows the model to retrieve information from the web,
# however, it may interfere with how the model decides to use some tools, or entities
# for example weather entity may be disregarded if the model chooses to Google it.
if options.get(CONF_USE_GOOGLE_SEARCH_TOOL) is True:
tools = tools or []
tools.append(Tool(google_search=GoogleSearch()))
model_name = options.get(CONF_CHAT_MODEL, self.default_model)
# Avoid INVALID_ARGUMENT Developer instruction is not enabled for <model>
supports_system_instruction = (
"gemma" not in model_name
and "gemini-2.0-flash-preview-image-generation" not in model_name
)
prompt_content = cast(
conversation.SystemContent,
chat_log.content[0],
)
if prompt_content.content:
prompt = prompt_content.content
else:
raise HomeAssistantError("Invalid prompt content")
messages: list[Content | ContentDict] = []
# Google groups tool results, we do not. Group them before sending.
tool_results: list[conversation.ToolResultContent] = []
for chat_content in chat_log.content[1:-1]:
if chat_content.role == "tool_result":
tool_results.append(chat_content)
continue
if (
not isinstance(chat_content, conversation.ToolResultContent)
and chat_content.content == ""
):
# Skipping is not possible since the number of function calls need to match the number of function responses
# and skipping one would mean removing the other and hence this would prevent a proper chat log
chat_content = replace(chat_content, content=" ")
if tool_results:
messages.append(_create_google_tool_response_content(tool_results))
tool_results.clear()
messages.append(_convert_content(chat_content))
# The SDK requires the first message to be a user message
# This is not the case if user used `start_conversation`
# Workaround from https://github.com/googleapis/python-genai/issues/529#issuecomment-2740964537
if messages and (
(isinstance(messages[0], Content) and messages[0].role != "user")
or (isinstance(messages[0], dict) and messages[0]["role"] != "user")
):
messages.insert(
0,
Content(role="user", parts=[Part.from_text(text=" ")]),
)
if tool_results:
messages.append(_create_google_tool_response_content(tool_results))
generateContentConfig = self.create_generate_content_config()
generateContentConfig.tools = tools or None
generateContentConfig.system_instruction = (
prompt if supports_system_instruction else None
)
generateContentConfig.automatic_function_calling = (
AutomaticFunctionCallingConfig(disable=True, maximum_remote_calls=None)
)
if structure:
generateContentConfig.response_mime_type = "application/json"
generateContentConfig.response_schema = _format_schema(
convert(
structure,
custom_serializer=(
chat_log.llm_api.custom_serializer
if chat_log.llm_api
else llm.selector_serializer
),
)
)
if not supports_system_instruction:
messages = [
Content(role="user", parts=[Part.from_text(text=prompt)]),
Content(role="model", parts=[Part.from_text(text="Ok")]),
*messages,
]
chat = self._genai_client.aio.chats.create(
model=model_name, history=messages, config=generateContentConfig
)
user_message = chat_log.content[-1]
assert isinstance(user_message, conversation.UserContent)
chat_request: list[PartUnionDict] = [user_message.content]
if user_message.attachments:
chat_request.extend(
await async_prepare_files_for_prompt(
self.hass,
self._genai_client,
[(a.path, a.mime_type) for a in user_message.attachments],
)
)
# To prevent infinite loops, we limit the number of iterations
for _iteration in range(max_iterations):
try:
chat_response_generator = await chat.send_message_stream(
message=chat_request
)
except (
APIError,
ClientError,
ValueError,
) as err:
LOGGER.error("Error sending message: %s %s", type(err), err)
error = ERROR_GETTING_RESPONSE
raise HomeAssistantError(error) from err
chat_request = list(
_create_google_tool_response_parts(
[
content
async for content in chat_log.async_add_delta_content_stream(
self.entity_id,
_transform_stream(chat_response_generator),
)
if isinstance(content, conversation.ToolResultContent)
]
)
)
if not chat_log.unresponded_tool_results:
break
def create_generate_content_config(
self, default_max_tokens: int | None = None
) -> GenerateContentConfig:
"""Create the GenerateContentConfig for the LLM."""
options = self.subentry.data
model = options.get(CONF_CHAT_MODEL, self.default_model)
thinking_config: ThinkingConfig | None = None
if model.startswith("models/gemini-2.5") and not model.endswith(
("tts", "image", "image-preview")
):
thinking_config = ThinkingConfig(include_thoughts=True)
return GenerateContentConfig(
temperature=options.get(CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE),
top_k=options.get(CONF_TOP_K, RECOMMENDED_TOP_K),
top_p=options.get(CONF_TOP_P, RECOMMENDED_TOP_P),
max_output_tokens=options.get(
CONF_MAX_TOKENS,
default_max_tokens
if default_max_tokens is not None
else RECOMMENDED_MAX_TOKENS,
),
safety_settings=[
SafetySetting(
category=HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=options.get(
CONF_HATE_BLOCK_THRESHOLD, RECOMMENDED_HARM_BLOCK_THRESHOLD
),
),
SafetySetting(
category=HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold=options.get(
CONF_HARASSMENT_BLOCK_THRESHOLD,
RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
),
SafetySetting(
category=HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=options.get(
CONF_DANGEROUS_BLOCK_THRESHOLD, RECOMMENDED_HARM_BLOCK_THRESHOLD
),
),
SafetySetting(
category=HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold=options.get(
CONF_SEXUAL_BLOCK_THRESHOLD, RECOMMENDED_HARM_BLOCK_THRESHOLD
),
),
],
thinking_config=thinking_config,
)
async def async_prepare_files_for_prompt(
hass: HomeAssistant, client: Client, files: list[tuple[Path, str | None]]
) -> list[File]:
"""Upload files so they can be attached to a prompt.
Caller needs to ensure that the files are allowed.
"""
def upload_files() -> list[File]:
prompt_parts: list[File] = []
for filename, mimetype in files:
if not filename.exists():
raise HomeAssistantError(f"`{filename}` does not exist")
if mimetype is None:
mimetype = mimetypes.guess_type(filename)[0]
prompt_parts.append(
client.files.upload(
file=filename,
config={
"mime_type": mimetype,
"display_name": filename.name,
},
)
)
return prompt_parts
async def wait_for_file_processing(uploaded_file: File) -> None:
"""Wait for file processing to complete."""
first = True
while uploaded_file.state in (
FileState.STATE_UNSPECIFIED,
FileState.PROCESSING,
):
if first:
first = False
else:
LOGGER.debug(
"Waiting for file `%s` to be processed, current state: %s",
uploaded_file.name,
uploaded_file.state,
)
await asyncio.sleep(FILE_POLLING_INTERVAL_SECONDS)
uploaded_file = await client.aio.files.get(
name=uploaded_file.name or "",
config={"http_options": {"timeout": TIMEOUT_MILLIS}},
)
if uploaded_file.state == FileState.FAILED:
raise HomeAssistantError(
f"File `{uploaded_file.name}` processing failed, reason: {uploaded_file.error.message if uploaded_file.error else 'unknown'}"
)
prompt_parts = await hass.async_add_executor_job(upload_files)
tasks = [
asyncio.create_task(wait_for_file_processing(part))
for part in prompt_parts
if part.state != FileState.ACTIVE
]
async with asyncio.timeout(TIMEOUT_MILLIS / 1000):
await asyncio.gather(*tasks)
return prompt_parts
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/google_generative_ai_conversation/entity.py",
"license": "Apache License 2.0",
"lines": 661,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/google_generative_ai_conversation/helpers.py | """Helper classes for Google Generative AI integration."""
from __future__ import annotations
from contextlib import suppress
import io
import wave
from homeassistant.exceptions import HomeAssistantError
from .const import LOGGER
def convert_to_wav(audio_data: bytes, mime_type: str) -> bytes:
"""Generate a WAV file header for the given audio data and parameters.
Args:
audio_data: The raw audio data as a bytes object.
mime_type: Mime type of the audio data.
Returns:
A bytes object representing the WAV file header.
"""
parameters = _parse_audio_mime_type(mime_type)
wav_buffer = io.BytesIO()
with wave.open(wav_buffer, "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(parameters["bits_per_sample"] // 8)
wf.setframerate(parameters["rate"])
wf.writeframes(audio_data)
return wav_buffer.getvalue()
# Below code is from https://aistudio.google.com/app/generate-speech
# when you select "Get SDK code to generate speech".
def _parse_audio_mime_type(mime_type: str) -> dict[str, int]:
"""Parse bits per sample and rate from an audio MIME type string.
Assumes bits per sample is encoded like "L16" and rate as "rate=xxxxx".
Args:
mime_type: The audio MIME type string (e.g., "audio/L16;rate=24000").
Returns:
A dictionary with "bits_per_sample" and "rate" keys. Values will be
integers if found, otherwise None.
"""
if not mime_type.startswith("audio/L"):
LOGGER.warning("Received unexpected MIME type %s", mime_type)
raise HomeAssistantError(f"Unsupported audio MIME type: {mime_type}")
bits_per_sample = 16
rate = 24000
# Extract rate from parameters
parts = mime_type.split(";")
for param in parts: # Skip the main type part
param = param.strip()
if param.lower().startswith("rate="):
# Handle cases like "rate=" with no value or non-integer value and keep rate as default
with suppress(ValueError, IndexError):
rate_str = param.split("=", 1)[1]
rate = int(rate_str)
elif param.startswith("audio/L"):
# Keep bits_per_sample as default if conversion fails
with suppress(ValueError, IndexError):
bits_per_sample = int(param.split("L", 1)[1])
return {"bits_per_sample": bits_per_sample, "rate": rate}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/google_generative_ai_conversation/helpers.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/google_generative_ai_conversation/tts.py | """Text to speech support for Google Generative AI."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from google.genai import types
from google.genai.errors import APIError, ClientError
from propcache.api import cached_property
from homeassistant.components.tts import (
ATTR_VOICE,
TextToSpeechEntity,
TtsAudioType,
Voice,
)
from homeassistant.config_entries import ConfigEntry, ConfigSubentry
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import CONF_CHAT_MODEL, LOGGER, RECOMMENDED_TTS_MODEL
from .entity import GoogleGenerativeAILLMBaseEntity
from .helpers import convert_to_wav
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up TTS entities."""
for subentry in config_entry.subentries.values():
if subentry.subentry_type != "tts":
continue
async_add_entities(
[GoogleGenerativeAITextToSpeechEntity(config_entry, subentry)],
config_subentry_id=subentry.subentry_id,
)
class GoogleGenerativeAITextToSpeechEntity(
TextToSpeechEntity, GoogleGenerativeAILLMBaseEntity
):
"""Google Generative AI text-to-speech entity."""
_attr_supported_options = [ATTR_VOICE]
# See https://ai.google.dev/gemini-api/docs/speech-generation#languages
# Note the documentation might not be up to date, e.g. el-GR is not listed
# there but is supported.
_attr_supported_languages = [
"af-ZA",
"am-ET",
"ar-EG",
"az-AZ",
"be-BY",
"bg-BG",
"bn-BD",
"ca-ES",
"ceb-PH",
"cmn-CN",
"cs-CZ",
"da-DK",
"de-DE",
"el-GR",
"en-IN",
"en-US",
"es-ES",
"es-US",
"et-EE",
"eu-ES",
"fa-IR",
"fi-FI",
"fil-PH",
"fr-FR",
"gl-ES",
"gu-IN",
"he-IL",
"hi-IN",
"hr-HR",
"ht-HT",
"hu-HU",
"hy-AM",
"id-ID",
"is-IS",
"it-IT",
"ja-JP",
"jv-ID",
"ka-GE",
"kn-IN",
"ko-KR",
"kok-IN",
"la-VA",
"lb-LU",
"lo-LA",
"lt-LT",
"lv-LV",
"mai-IN",
"mg-MG",
"mk-MK",
"ml-IN",
"mn-MN",
"mr-IN",
"ms-MY",
"my-MM",
"nb-NO",
"ne-NP",
"nl-NL",
"nn-NO",
"or-IN",
"pa-IN",
"pl-PL",
"ps-AF",
"pt-BR",
"pt-PT",
"ro-RO",
"ru-RU",
"sd-PK",
"si-LK",
"sk-SK",
"sl-SI",
"sq-AL",
"sr-RS",
"sv-SE",
"sw-KE",
"ta-IN",
"te-IN",
"th-TH",
"tr-TR",
"uk-UA",
"ur-PK",
"vi-VN",
]
# Unused, but required by base class.
# The Gemini TTS models detect the input language automatically.
_attr_default_language = "en-US"
# See https://ai.google.dev/gemini-api/docs/speech-generation#voices
_supported_voices = [
Voice(voice.split(" ", 1)[0].lower(), voice)
for voice in (
"Zephyr (Bright)",
"Puck (Upbeat)",
"Charon (Informative)",
"Kore (Firm)",
"Fenrir (Excitable)",
"Leda (Youthful)",
"Orus (Firm)",
"Aoede (Breezy)",
"Callirrhoe (Easy-going)",
"Autonoe (Bright)",
"Enceladus (Breathy)",
"Iapetus (Clear)",
"Umbriel (Easy-going)",
"Algieba (Smooth)",
"Despina (Smooth)",
"Erinome (Clear)",
"Algenib (Gravelly)",
"Rasalgethi (Informative)",
"Laomedeia (Upbeat)",
"Achernar (Soft)",
"Alnilam (Firm)",
"Schedar (Even)",
"Gacrux (Mature)",
"Pulcherrima (Forward)",
"Achird (Friendly)",
"Zubenelgenubi (Casual)",
"Vindemiatrix (Gentle)",
"Sadachbia (Lively)",
"Sadaltager (Knowledgeable)",
"Sulafat (Warm)",
)
]
def __init__(self, config_entry: ConfigEntry, subentry: ConfigSubentry) -> None:
"""Initialize the TTS entity."""
super().__init__(config_entry, subentry, RECOMMENDED_TTS_MODEL)
@callback
def async_get_supported_voices(self, language: str) -> list[Voice]:
"""Return a list of supported voices for a language."""
return self._supported_voices
@cached_property
def default_options(self) -> Mapping[str, Any]:
"""Return a mapping with the default options."""
return {
ATTR_VOICE: self._supported_voices[0].voice_id,
}
async def async_get_tts_audio(
self, message: str, language: str, options: dict[str, Any]
) -> TtsAudioType:
"""Load tts audio file from the engine."""
config = self.create_generate_content_config()
config.response_modalities = ["AUDIO"]
config.speech_config = types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name=options[ATTR_VOICE]
)
)
)
def _extract_audio_parts(
response: types.GenerateContentResponse,
) -> tuple[bytes, str]:
if (
not response.candidates
or not response.candidates[0].content
or not response.candidates[0].content.parts
or not response.candidates[0].content.parts[0].inline_data
):
raise ValueError("No content returned from TTS generation")
data = response.candidates[0].content.parts[0].inline_data.data
mime_type = response.candidates[0].content.parts[0].inline_data.mime_type
if not isinstance(data, bytes):
raise TypeError(
f"Expected bytes for audio data, got {type(data).__name__}"
)
if not isinstance(mime_type, str):
raise TypeError(
f"Expected str for mime_type, got {type(mime_type).__name__}"
)
return data, mime_type
try:
response = await self._genai_client.aio.models.generate_content(
model=self.subentry.data.get(CONF_CHAT_MODEL, RECOMMENDED_TTS_MODEL),
contents=message,
config=config,
)
data, mime_type = _extract_audio_parts(response)
except (APIError, ClientError, ValueError, TypeError) as exc:
LOGGER.error("Error during TTS: %s", exc, exc_info=True)
raise HomeAssistantError(exc) from exc
return "wav", convert_to_wav(data, mime_type)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/google_generative_ai_conversation/tts.py",
"license": "Apache License 2.0",
"lines": 221,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/google_sheets/services.py | """Support for Google Sheets."""
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from google.auth.exceptions import RefreshError
from google.oauth2.credentials import Credentials
from gspread import Client
from gspread.exceptions import APIError
from gspread.utils import ValueInputOption
import voluptuous as vol
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN
from homeassistant.core import (
HomeAssistant,
ServiceCall,
ServiceResponse,
SupportsResponse,
callback,
)
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, service
from homeassistant.helpers.selector import ConfigEntrySelector
from homeassistant.util.json import JsonObjectType
from .const import DOMAIN
if TYPE_CHECKING:
from . import GoogleSheetsConfigEntry
ADD_CREATED_COLUMN = "add_created_column"
DATA = "data"
DATA_CONFIG_ENTRY = "config_entry"
ROWS = "rows"
WORKSHEET = "worksheet"
SERVICE_APPEND_SHEET = "append_sheet"
SERVICE_GET_SHEET = "get_sheet"
SHEET_SERVICE_SCHEMA = vol.All(
{
vol.Required(DATA_CONFIG_ENTRY): ConfigEntrySelector({"integration": DOMAIN}),
vol.Optional(WORKSHEET): cv.string,
vol.Optional(ADD_CREATED_COLUMN, default=True): cv.boolean,
vol.Required(DATA): vol.Any(cv.ensure_list, [dict]),
},
)
get_SHEET_SERVICE_SCHEMA = vol.All(
{
vol.Required(DATA_CONFIG_ENTRY): ConfigEntrySelector({"integration": DOMAIN}),
vol.Optional(WORKSHEET): cv.string,
vol.Required(ROWS): cv.positive_int,
},
)
def _append_to_sheet(call: ServiceCall, entry: GoogleSheetsConfigEntry) -> None:
"""Run append in the executor."""
client = Client(Credentials(entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN])) # type: ignore[no-untyped-call]
try:
sheet = client.open_by_key(entry.unique_id)
except RefreshError:
entry.async_start_reauth(call.hass)
raise
except APIError as ex:
raise HomeAssistantError("Failed to write data") from ex
worksheet = sheet.worksheet(call.data.get(WORKSHEET, sheet.sheet1.title))
columns: list[str] = next(iter(worksheet.get_values("A1:ZZ1")), [])
add_created_column = call.data[ADD_CREATED_COLUMN]
now = str(datetime.now())
rows = []
for d in call.data[DATA]:
row_data = ({"created": now} | d) if add_created_column else d
row = [row_data.get(column, "") for column in columns]
for key, value in row_data.items():
if key not in columns:
columns.append(key)
worksheet.update_cell(1, len(columns), key)
row.append(value)
rows.append(row)
worksheet.append_rows(rows, value_input_option=ValueInputOption.user_entered)
def _get_from_sheet(
call: ServiceCall, entry: GoogleSheetsConfigEntry
) -> JsonObjectType:
"""Run get in the executor."""
client = Client(Credentials(entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN])) # type: ignore[no-untyped-call]
try:
sheet = client.open_by_key(entry.unique_id)
except RefreshError:
entry.async_start_reauth(call.hass)
raise
except APIError as ex:
raise HomeAssistantError("Failed to retrieve data") from ex
worksheet = sheet.worksheet(call.data.get(WORKSHEET, sheet.sheet1.title))
all_values = worksheet.get_values()
return {"range": all_values[-call.data[ROWS] :]}
async def _async_append_to_sheet(call: ServiceCall) -> None:
"""Append new line of data to a Google Sheets document."""
entry: GoogleSheetsConfigEntry = service.async_get_config_entry(
call.hass, DOMAIN, call.data[DATA_CONFIG_ENTRY]
)
await entry.runtime_data.async_ensure_token_valid()
await call.hass.async_add_executor_job(_append_to_sheet, call, entry)
async def _async_get_from_sheet(call: ServiceCall) -> ServiceResponse:
"""Get lines of data from a Google Sheets document."""
entry: GoogleSheetsConfigEntry = service.async_get_config_entry(
call.hass, DOMAIN, call.data[DATA_CONFIG_ENTRY]
)
await entry.runtime_data.async_ensure_token_valid()
return await call.hass.async_add_executor_job(_get_from_sheet, call, entry)
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Add the services for Google Sheets."""
hass.services.async_register(
DOMAIN,
SERVICE_APPEND_SHEET,
_async_append_to_sheet,
schema=SHEET_SERVICE_SCHEMA,
)
hass.services.async_register(
DOMAIN,
SERVICE_GET_SHEET,
_async_get_from_sheet,
schema=get_SHEET_SERVICE_SCHEMA,
supports_response=SupportsResponse.ONLY,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/google_sheets/services.py",
"license": "Apache License 2.0",
"lines": 117,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/homee/diagnostics.py | """Diagnostics for homee integration."""
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntry
from . import DOMAIN, HomeeConfigEntry
TO_REDACT = [CONF_PASSWORD, CONF_USERNAME, "latitude", "longitude", "wlan_ssid"]
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: HomeeConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return {
"entry_data": async_redact_data(entry.data, TO_REDACT),
"settings": async_redact_data(entry.runtime_data.settings.raw_data, TO_REDACT),
"devices": [{"node": node.raw_data} for node in entry.runtime_data.nodes],
}
async def async_get_device_diagnostics(
hass: HomeAssistant, entry: HomeeConfigEntry, device: DeviceEntry
) -> dict[str, Any]:
"""Return diagnostics for a device."""
# Extract node_id from the device identifiers
split_uid = next(
identifier[1] for identifier in device.identifiers if identifier[0] == DOMAIN
).split("-")
# Homee hub itself only has MAC as identifier and a node_id of -1
node_id = -1 if len(split_uid) < 2 else split_uid[1]
node = entry.runtime_data.get_node_by_id(int(node_id))
assert node is not None
return {
"homee node": node.raw_data,
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homee/diagnostics.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/homee/siren.py | """The homee siren platform."""
from typing import Any
from pyHomee.const import AttributeType
from pyHomee.model import HomeeNode
from homeassistant.components.siren import SirenEntity, SirenEntityFeature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import HomeeConfigEntry
from .entity import HomeeEntity
from .helpers import setup_homee_platform
PARALLEL_UPDATES = 0
async def add_siren_entities(
config_entry: HomeeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
nodes: list[HomeeNode],
) -> None:
"""Add homee siren entities."""
async_add_entities(
HomeeSiren(attribute, config_entry)
for node in nodes
for attribute in node.attributes
if attribute.type == AttributeType.SIREN
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: HomeeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add siren entities for homee."""
await setup_homee_platform(add_siren_entities, async_add_entities, config_entry)
class HomeeSiren(HomeeEntity, SirenEntity):
"""Representation of a homee siren device."""
_attr_name = None
_attr_supported_features = SirenEntityFeature.TURN_ON | SirenEntityFeature.TURN_OFF
@property
def is_on(self) -> bool:
"""Return the state of the siren."""
return self._attribute.current_value == 1.0
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the siren on."""
await self.async_set_homee_value(1)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the siren off."""
await self.async_set_homee_value(0)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homee/siren.py",
"license": "Apache License 2.0",
"lines": 44,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/homewizard/select.py | """Support for HomeWizard select platform."""
from __future__ import annotations
from homewizard_energy.models import Batteries
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import HomeWizardConfigEntry, HWEnergyDeviceUpdateCoordinator
from .entity import HomeWizardEntity
from .helpers import homewizard_exception_handler
PARALLEL_UPDATES = 1
async def async_setup_entry(
hass: HomeAssistant,
entry: HomeWizardConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up HomeWizard select based on a config entry."""
if entry.runtime_data.data.device.supports_batteries():
async_add_entities(
[
HomeWizardBatteryModeSelectEntity(
coordinator=entry.runtime_data,
)
]
)
class HomeWizardBatteryModeSelectEntity(HomeWizardEntity, SelectEntity):
"""Defines a HomeWizard select entity."""
entity_description: SelectEntityDescription
def __init__(
self,
coordinator: HWEnergyDeviceUpdateCoordinator,
) -> None:
"""Initialize the switch."""
super().__init__(coordinator)
batteries = coordinator.data.batteries
battery_count = batteries.battery_count if batteries is not None else None
entity_registry_enabled_default = (
battery_count is not None and battery_count > 0
)
description = SelectEntityDescription(
key="battery_group_mode",
translation_key="battery_group_mode",
entity_category=EntityCategory.CONFIG,
entity_registry_enabled_default=entity_registry_enabled_default,
options=[
str(mode)
for mode in (coordinator.data.device.supported_battery_modes() or [])
],
)
self.entity_description = description
self._attr_unique_id = f"{coordinator.config_entry.unique_id}_{description.key}"
@property
def current_option(self) -> str | None:
"""Return the selected entity option to represent the entity state."""
return (
self.coordinator.data.batteries.mode
if self.coordinator.data.batteries and self.coordinator.data.batteries.mode
else None
)
@homewizard_exception_handler
async def async_select_option(self, option: str) -> None:
"""Change the selected option."""
await self.coordinator.api.batteries(Batteries.Mode(option))
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homewizard/select.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/imeon_inverter/entity.py | """Imeon inverter base class for entities."""
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import InverterCoordinator
type InverterConfigEntry = ConfigEntry[InverterCoordinator]
class InverterEntity(CoordinatorEntity[InverterCoordinator]):
"""Common elements for all entities."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: InverterCoordinator,
entry: InverterConfigEntry,
entity_description: EntityDescription,
) -> None:
"""Pass coordinator to CoordinatorEntity."""
super().__init__(coordinator)
self.entity_description = entity_description
self._inverter = coordinator.api.inverter
self.data_key = entity_description.key
assert entry.unique_id
self._attr_unique_id = f"{entry.unique_id}_{self.data_key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, entry.unique_id)},
name="Imeon inverter",
manufacturer="Imeon Energy",
model=self._inverter.get("inverter"),
sw_version=self._inverter.get("software"),
serial_number=self._inverter.get("serial"),
configuration_url=self._inverter.get("url"),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/imeon_inverter/entity.py",
"license": "Apache License 2.0",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/immich/update.py | """Update platform for the Immich integration."""
from __future__ import annotations
from homeassistant.components.update import UpdateEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import ImmichConfigEntry, ImmichDataUpdateCoordinator
from .entity import ImmichEntity
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: ImmichConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add immich server update entity."""
coordinator = entry.runtime_data
if coordinator.data.server_version_check is not None:
async_add_entities([ImmichUpdateEntity(coordinator)])
class ImmichUpdateEntity(ImmichEntity, UpdateEntity):
"""Define Immich update entity."""
_attr_translation_key = "update"
def __init__(
self,
coordinator: ImmichDataUpdateCoordinator,
) -> None:
"""Initialize."""
super().__init__(coordinator)
self._attr_unique_id = f"{coordinator.config_entry.unique_id}_update"
@property
def installed_version(self) -> str:
"""Current installed immich server version."""
return self.coordinator.data.server_about.version
@property
def latest_version(self) -> str | None:
"""Available new immich server version."""
assert self.coordinator.data.server_version_check
return self.coordinator.data.server_version_check.release_version
@property
def release_url(self) -> str | None:
"""URL to the full release notes of the new immich server version."""
return (
f"https://github.com/immich-app/immich/releases/tag/{self.latest_version}"
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/immich/update.py",
"license": "Apache License 2.0",
"lines": 43,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/insteon/services.py | """Utilities used by insteon component."""
from __future__ import annotations
import asyncio
import logging
from pyinsteon import devices
from pyinsteon.address import Address
from pyinsteon.managers.link_manager import (
async_enter_linking_mode,
async_enter_unlinking_mode,
)
from pyinsteon.managers.scene_manager import (
async_trigger_scene_off,
async_trigger_scene_on,
)
from pyinsteon.managers.x10_manager import (
async_x10_all_lights_off,
async_x10_all_lights_on,
async_x10_all_units_off,
)
from pyinsteon.x10_address import create as create_x10_address
from homeassistant.const import (
CONF_ADDRESS,
CONF_ENTITY_ID,
CONF_PLATFORM,
ENTITY_MATCH_ALL,
)
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
dispatcher_send,
)
from .const import (
CONF_CAT,
CONF_DIM_STEPS,
CONF_HOUSECODE,
CONF_SUBCAT,
CONF_UNITCODE,
DOMAIN,
SIGNAL_ADD_DEFAULT_LINKS,
SIGNAL_ADD_DEVICE_OVERRIDE,
SIGNAL_ADD_X10_DEVICE,
SIGNAL_LOAD_ALDB,
SIGNAL_PRINT_ALDB,
SIGNAL_REMOVE_DEVICE_OVERRIDE,
SIGNAL_REMOVE_ENTITY,
SIGNAL_REMOVE_HA_DEVICE,
SIGNAL_REMOVE_INSTEON_DEVICE,
SIGNAL_REMOVE_X10_DEVICE,
SIGNAL_SAVE_DEVICES,
SRV_ADD_ALL_LINK,
SRV_ADD_DEFAULT_LINKS,
SRV_ALL_LINK_GROUP,
SRV_ALL_LINK_MODE,
SRV_CONTROLLER,
SRV_DEL_ALL_LINK,
SRV_HOUSECODE,
SRV_LOAD_ALDB,
SRV_LOAD_DB_RELOAD,
SRV_PRINT_ALDB,
SRV_PRINT_IM_ALDB,
SRV_SCENE_OFF,
SRV_SCENE_ON,
SRV_X10_ALL_LIGHTS_OFF,
SRV_X10_ALL_LIGHTS_ON,
SRV_X10_ALL_UNITS_OFF,
)
from .schemas import (
ADD_ALL_LINK_SCHEMA,
ADD_DEFAULT_LINKS_SCHEMA,
DEL_ALL_LINK_SCHEMA,
LOAD_ALDB_SCHEMA,
PRINT_ALDB_SCHEMA,
TRIGGER_SCENE_SCHEMA,
X10_HOUSECODE_SCHEMA,
)
from .utils import print_aldb_to_log
_LOGGER = logging.getLogger(__name__)
@callback
def async_setup_services(hass: HomeAssistant) -> None: # noqa: C901
"""Register services used by insteon component."""
save_lock = asyncio.Lock()
async def async_srv_add_all_link(service: ServiceCall) -> None:
"""Add an INSTEON All-Link between two devices."""
group = service.data[SRV_ALL_LINK_GROUP]
mode = service.data[SRV_ALL_LINK_MODE]
link_mode = mode.lower() == SRV_CONTROLLER
await async_enter_linking_mode(link_mode, group)
async def async_srv_del_all_link(service: ServiceCall) -> None:
"""Delete an INSTEON All-Link between two devices."""
group = service.data.get(SRV_ALL_LINK_GROUP)
await async_enter_unlinking_mode(group)
async def async_srv_load_aldb(service: ServiceCall) -> None:
"""Load the device All-Link database."""
entity_id = service.data[CONF_ENTITY_ID]
reload = service.data[SRV_LOAD_DB_RELOAD]
if entity_id.lower() == ENTITY_MATCH_ALL:
await async_srv_load_aldb_all(reload)
else:
signal = f"{entity_id}_{SIGNAL_LOAD_ALDB}"
async_dispatcher_send(hass, signal, reload)
async def async_srv_load_aldb_all(reload):
"""Load the All-Link database for all devices."""
# Cannot be done concurrently due to issues with the underlying protocol.
for address in devices:
device = devices[address]
if device != devices.modem and device.cat != 0x03:
await device.aldb.async_load(refresh=reload)
await async_srv_save_devices()
async def async_srv_save_devices():
"""Write the Insteon device configuration to file."""
async with save_lock:
_LOGGER.debug("Saving Insteon devices")
await devices.async_save(hass.config.config_dir)
def print_aldb(service: ServiceCall) -> None:
"""Print the All-Link Database for a device."""
# For now this sends logs to the log file.
# Future direction is to create an INSTEON control panel.
entity_id = service.data[CONF_ENTITY_ID]
signal = f"{entity_id}_{SIGNAL_PRINT_ALDB}"
dispatcher_send(hass, signal)
def print_im_aldb(service: ServiceCall) -> None:
"""Print the All-Link Database for a device."""
# For now this sends logs to the log file.
# Future direction is to create an INSTEON control panel.
print_aldb_to_log(devices.modem.aldb)
async def async_srv_x10_all_units_off(service: ServiceCall) -> None:
"""Send the X10 All Units Off command."""
housecode = service.data.get(SRV_HOUSECODE)
await async_x10_all_units_off(housecode)
async def async_srv_x10_all_lights_off(service: ServiceCall) -> None:
"""Send the X10 All Lights Off command."""
housecode = service.data.get(SRV_HOUSECODE)
await async_x10_all_lights_off(housecode)
async def async_srv_x10_all_lights_on(service: ServiceCall) -> None:
"""Send the X10 All Lights On command."""
housecode = service.data.get(SRV_HOUSECODE)
await async_x10_all_lights_on(housecode)
async def async_srv_scene_on(service: ServiceCall) -> None:
"""Trigger an INSTEON scene ON."""
group = service.data.get(SRV_ALL_LINK_GROUP)
await async_trigger_scene_on(group)
async def async_srv_scene_off(service: ServiceCall) -> None:
"""Trigger an INSTEON scene ON."""
group = service.data.get(SRV_ALL_LINK_GROUP)
await async_trigger_scene_off(group)
@callback
def async_add_default_links(service: ServiceCall) -> None:
"""Add the default All-Link entries to a device."""
entity_id = service.data[CONF_ENTITY_ID]
signal = f"{entity_id}_{SIGNAL_ADD_DEFAULT_LINKS}"
async_dispatcher_send(hass, signal)
async def async_add_device_override(override):
"""Remove an Insten device and associated entities."""
address = Address(override[CONF_ADDRESS])
await async_remove_ha_device(address)
devices.set_id(address, override[CONF_CAT], override[CONF_SUBCAT], 0)
await async_srv_save_devices()
async def async_remove_device_override(address):
"""Remove an Insten device and associated entities."""
address = Address(address)
await async_remove_ha_device(address)
devices.set_id(address, None, None, None)
await devices.async_identify_device(address)
await async_srv_save_devices()
@callback
def async_add_x10_device(x10_config):
"""Add X10 device."""
housecode = x10_config[CONF_HOUSECODE]
unitcode = x10_config[CONF_UNITCODE]
platform = x10_config[CONF_PLATFORM]
steps = x10_config.get(CONF_DIM_STEPS, 22)
x10_type = "on_off"
if platform == "light":
x10_type = "dimmable"
elif platform == "binary_sensor":
x10_type = "sensor"
_LOGGER.debug(
"Adding X10 device to Insteon: %s %d %s", housecode, unitcode, x10_type
)
# This must be run in the event loop
devices.add_x10_device(housecode, unitcode, x10_type, steps)
async def async_remove_x10_device(housecode, unitcode):
"""Remove an X10 device and associated entities."""
address = create_x10_address(housecode, unitcode)
devices.pop(address)
await async_remove_ha_device(address)
async def async_remove_ha_device(address: Address, remove_all_refs: bool = False):
"""Remove the device and all entities from hass."""
signal = f"{address.id}_{SIGNAL_REMOVE_ENTITY}"
async_dispatcher_send(hass, signal)
dev_registry = dr.async_get(hass)
device = dev_registry.async_get_device(identifiers={(DOMAIN, str(address))})
if device:
dev_registry.async_remove_device(device.id)
async def async_remove_insteon_device(
address: Address, remove_all_refs: bool = False
):
"""Remove the underlying Insteon device from the network."""
await devices.async_remove_device(
address=address, force=False, remove_all_refs=remove_all_refs
)
await async_srv_save_devices()
hass.services.async_register(
DOMAIN, SRV_ADD_ALL_LINK, async_srv_add_all_link, schema=ADD_ALL_LINK_SCHEMA
)
hass.services.async_register(
DOMAIN, SRV_DEL_ALL_LINK, async_srv_del_all_link, schema=DEL_ALL_LINK_SCHEMA
)
hass.services.async_register(
DOMAIN, SRV_LOAD_ALDB, async_srv_load_aldb, schema=LOAD_ALDB_SCHEMA
)
hass.services.async_register(
DOMAIN, SRV_PRINT_ALDB, print_aldb, schema=PRINT_ALDB_SCHEMA
)
hass.services.async_register(DOMAIN, SRV_PRINT_IM_ALDB, print_im_aldb, schema=None)
hass.services.async_register(
DOMAIN,
SRV_X10_ALL_UNITS_OFF,
async_srv_x10_all_units_off,
schema=X10_HOUSECODE_SCHEMA,
)
hass.services.async_register(
DOMAIN,
SRV_X10_ALL_LIGHTS_OFF,
async_srv_x10_all_lights_off,
schema=X10_HOUSECODE_SCHEMA,
)
hass.services.async_register(
DOMAIN,
SRV_X10_ALL_LIGHTS_ON,
async_srv_x10_all_lights_on,
schema=X10_HOUSECODE_SCHEMA,
)
hass.services.async_register(
DOMAIN, SRV_SCENE_ON, async_srv_scene_on, schema=TRIGGER_SCENE_SCHEMA
)
hass.services.async_register(
DOMAIN, SRV_SCENE_OFF, async_srv_scene_off, schema=TRIGGER_SCENE_SCHEMA
)
hass.services.async_register(
DOMAIN,
SRV_ADD_DEFAULT_LINKS,
async_add_default_links,
schema=ADD_DEFAULT_LINKS_SCHEMA,
)
async_dispatcher_connect(hass, SIGNAL_SAVE_DEVICES, async_srv_save_devices)
async_dispatcher_connect(
hass, SIGNAL_ADD_DEVICE_OVERRIDE, async_add_device_override
)
async_dispatcher_connect(
hass, SIGNAL_REMOVE_DEVICE_OVERRIDE, async_remove_device_override
)
async_dispatcher_connect(hass, SIGNAL_ADD_X10_DEVICE, async_add_x10_device)
async_dispatcher_connect(hass, SIGNAL_REMOVE_X10_DEVICE, async_remove_x10_device)
async_dispatcher_connect(hass, SIGNAL_REMOVE_HA_DEVICE, async_remove_ha_device)
async_dispatcher_connect(
hass, SIGNAL_REMOVE_INSTEON_DEVICE, async_remove_insteon_device
)
_LOGGER.debug("Insteon Services registered")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/insteon/services.py",
"license": "Apache License 2.0",
"lines": 261,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/kmtronic/coordinator.py | """The kmtronic integration."""
import asyncio
from datetime import timedelta
import logging
from aiohttp.client_exceptions import ClientConnectorError, ClientResponseError
from pykmtronic.hub import KMTronicHubAPI
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import MANUFACTURER
PLATFORMS = [Platform.SWITCH]
_LOGGER = logging.getLogger(__name__)
type KMTronicConfigEntry = ConfigEntry[KMtronicCoordinator]
class KMtronicCoordinator(DataUpdateCoordinator[None]):
"""Coordinator for KMTronic."""
entry: KMTronicConfigEntry
def __init__(
self, hass: HomeAssistant, entry: KMTronicConfigEntry, hub: KMTronicHubAPI
) -> None:
"""Initialize the KMTronic coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=entry,
name=f"{MANUFACTURER} {hub.name}",
update_interval=timedelta(seconds=30),
)
self.hub = hub
async def _async_update_data(self) -> None:
"""Fetch the latest data from the source."""
try:
async with asyncio.timeout(10):
await self.hub.async_update_relays()
except ClientResponseError as err:
raise UpdateFailed(f"Wrong credentials: {err}") from err
except ClientConnectorError as err:
raise UpdateFailed(f"Error communicating with API: {err}") from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/kmtronic/coordinator.py",
"license": "Apache License 2.0",
"lines": 38,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/lametric/update.py | """LaMetric Update platform."""
from awesomeversion import AwesomeVersion
from homeassistant.components.update import UpdateDeviceClass, UpdateEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import LaMetricConfigEntry, LaMetricDataUpdateCoordinator
from .entity import LaMetricEntity
async def async_setup_entry(
hass: HomeAssistant,
config_entry: LaMetricConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up LaMetric update platform."""
coordinator = config_entry.runtime_data
if coordinator.data.os_version >= AwesomeVersion("2.3.0"):
async_add_entities([LaMetricUpdate(coordinator)])
class LaMetricUpdate(LaMetricEntity, UpdateEntity):
"""Representation of LaMetric Update."""
_attr_device_class = UpdateDeviceClass.FIRMWARE
def __init__(self, coordinator: LaMetricDataUpdateCoordinator) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self._attr_unique_id = f"{coordinator.data.serial_number}-update"
@property
def installed_version(self) -> str:
"""Return the installed version of the entity."""
return self.coordinator.data.os_version
@property
def latest_version(self) -> str | None:
"""Return the latest version of the entity."""
if not self.coordinator.data.update:
return self.coordinator.data.os_version
return self.coordinator.data.update.version
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/lametric/update.py",
"license": "Apache License 2.0",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/luftdaten/coordinator.py | """Support for Sensor.Community stations.
Sensor.Community was previously called Luftdaten, hence the domain differs from
the integration name.
"""
from __future__ import annotations
import logging
from luftdaten import Luftdaten
from luftdaten.exceptions import LuftdatenError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
_LOGGER = logging.getLogger(__name__)
type LuftdatenConfigEntry = ConfigEntry[LuftdatenDataUpdateCoordinator]
class LuftdatenDataUpdateCoordinator(DataUpdateCoordinator[dict[str, float | int]]):
"""Data update coordinator for Sensor.Community."""
config_entry: LuftdatenConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: LuftdatenConfigEntry,
sensor_community: Luftdaten,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=f"{DOMAIN}_{sensor_community.sensor_id}",
update_interval=DEFAULT_SCAN_INTERVAL,
)
self._sensor_community = sensor_community
async def _async_update_data(self) -> dict[str, float | int]:
"""Update sensor/binary sensor data."""
try:
await self._sensor_community.get_data()
except LuftdatenError as err:
raise UpdateFailed("Unable to retrieve data from Sensor.Community") from err
if not self._sensor_community.values:
raise UpdateFailed("Did not receive sensor data from Sensor.Community")
data: dict[str, float | int] = self._sensor_community.values
data.update(self._sensor_community.meta)
return data
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/luftdaten/coordinator.py",
"license": "Apache License 2.0",
"lines": 43,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/lyric/coordinator.py | """The Honeywell Lyric integration."""
from __future__ import annotations
import asyncio
from datetime import timedelta
from http import HTTPStatus
import logging
from aiohttp.client_exceptions import ClientResponseError
from aiolyric import Lyric
from aiolyric.exceptions import LyricAuthenticationException, LyricException
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .api import OAuth2SessionLyric
_LOGGER = logging.getLogger(__name__)
type LyricConfigEntry = ConfigEntry[LyricDataUpdateCoordinator]
class LyricDataUpdateCoordinator(DataUpdateCoordinator[Lyric]):
"""Data update coordinator for Honeywell Lyric."""
config_entry: LyricConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: LyricConfigEntry,
oauth_session: OAuth2SessionLyric,
lyric: Lyric,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name="lyric_coordinator",
update_interval=timedelta(seconds=300),
)
self.oauth_session = oauth_session
self.lyric = lyric
async def _async_update_data(self) -> Lyric:
"""Fetch data from Lyric."""
return await self._run_update(False)
async def _run_update(self, force_refresh_token: bool) -> Lyric:
"""Fetch data from Lyric."""
try:
if not force_refresh_token:
await self.oauth_session.async_ensure_token_valid()
else:
await self.oauth_session.force_refresh_token()
except ClientResponseError as exception:
if exception.status in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN):
raise ConfigEntryAuthFailed from exception
raise UpdateFailed(exception) from exception
try:
async with asyncio.timeout(60):
await self.lyric.get_locations()
await asyncio.gather(
*(
self.lyric.get_thermostat_rooms(
location.location_id, device.device_id
)
for location in self.lyric.locations
for device in location.devices
if device.device_class == "Thermostat"
and device.device_id.startswith("LCC")
)
)
except LyricAuthenticationException as exception:
# Attempt to refresh the token before failing.
# Honeywell appear to have issues keeping tokens saved.
_LOGGER.debug("Authentication failed. Attempting to refresh token")
if not force_refresh_token:
return await self._run_update(True)
raise ConfigEntryAuthFailed from exception
except (LyricException, ClientResponseError) as exception:
raise UpdateFailed(exception) from exception
return self.lyric
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/lyric/coordinator.py",
"license": "Apache License 2.0",
"lines": 74,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/matrix/services.py | """The Matrix bot component."""
from __future__ import annotations
from typing import TYPE_CHECKING
import voluptuous as vol
from homeassistant.components.notify import ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import config_validation as cv
from .const import (
ATTR_FORMAT,
ATTR_IMAGES,
ATTR_MESSAGE_ID,
ATTR_REACTION,
ATTR_ROOM,
ATTR_THREAD_ID,
CONF_ROOMS_REGEX,
DOMAIN,
FORMAT_HTML,
FORMAT_TEXT,
SERVICE_REACT,
SERVICE_SEND_MESSAGE,
)
if TYPE_CHECKING:
from . import MatrixBot
MESSAGE_FORMATS = [FORMAT_HTML, FORMAT_TEXT]
DEFAULT_MESSAGE_FORMAT = FORMAT_TEXT
SERVICE_SCHEMA_SEND_MESSAGE = vol.Schema(
{
vol.Required(ATTR_MESSAGE): cv.string,
vol.Optional(ATTR_DATA, default={}): {
vol.Optional(ATTR_FORMAT, default=DEFAULT_MESSAGE_FORMAT): vol.In(
MESSAGE_FORMATS
),
vol.Optional(ATTR_IMAGES): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(ATTR_THREAD_ID): cv.string,
},
vol.Required(ATTR_TARGET): vol.All(
cv.ensure_list, [cv.matches_regex(CONF_ROOMS_REGEX)]
),
}
)
SERVICE_SCHEMA_REACT = vol.Schema(
{
vol.Required(ATTR_REACTION): cv.string,
vol.Required(ATTR_ROOM): cv.matches_regex(CONF_ROOMS_REGEX),
vol.Required(ATTR_MESSAGE_ID): cv.string,
}
)
async def _handle_send_message(call: ServiceCall) -> None:
"""Handle the send_message service call."""
matrix_bot: MatrixBot = call.hass.data[DOMAIN]
await matrix_bot.handle_send_message(call)
async def _handle_react(call: ServiceCall) -> None:
"""Handle the react service call."""
matrix_bot: MatrixBot = call.hass.data[DOMAIN]
await matrix_bot.handle_send_reaction(call)
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up the Matrix bot component."""
hass.services.async_register(
DOMAIN,
SERVICE_SEND_MESSAGE,
_handle_send_message,
schema=SERVICE_SCHEMA_SEND_MESSAGE,
)
hass.services.async_register(
DOMAIN,
SERVICE_REACT,
_handle_react,
schema=SERVICE_SCHEMA_REACT,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/matrix/services.py",
"license": "Apache License 2.0",
"lines": 70,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/meater/coordinator.py | """Meater Coordinator."""
import asyncio
from datetime import timedelta
import logging
from meater.MeaterApi import (
AuthenticationError,
MeaterApi,
MeaterProbe,
ServiceUnavailableError,
TooManyRequestsError,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
_LOGGER = logging.getLogger(__name__)
type MeaterConfigEntry = ConfigEntry[MeaterCoordinator]
class MeaterCoordinator(DataUpdateCoordinator[dict[str, MeaterProbe]]):
"""Meater Coordinator."""
config_entry: MeaterConfigEntry
def __init__(
self,
hass: HomeAssistant,
entry: MeaterConfigEntry,
) -> None:
"""Initialize the Meater Coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=entry,
name=f"Meater {entry.title}",
update_interval=timedelta(seconds=30),
)
session = async_get_clientsession(hass)
self.client = MeaterApi(session)
self.found_probes: set[str] = set()
async def _async_setup(self) -> None:
"""Set up the Meater Coordinator."""
try:
_LOGGER.debug("Authenticating with the Meater API")
await self.client.authenticate(
self.config_entry.data[CONF_USERNAME],
self.config_entry.data[CONF_PASSWORD],
)
except (ServiceUnavailableError, TooManyRequestsError) as err:
raise UpdateFailed from err
except AuthenticationError as err:
raise ConfigEntryAuthFailed(
f"Unable to authenticate with the Meater API: {err}"
) from err
async def _async_update_data(self) -> dict[str, MeaterProbe]:
"""Fetch data from API endpoint."""
try:
# Note: TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator.
async with asyncio.timeout(10):
devices: list[MeaterProbe] = await self.client.get_all_devices()
except AuthenticationError as err:
raise ConfigEntryAuthFailed("The API call wasn't authenticated") from err
except TooManyRequestsError as err:
raise UpdateFailed(
"Too many requests have been made to the API, rate limiting is in place"
) from err
res = {device.id: device for device in devices}
self.found_probes.update(set(res.keys()))
return res
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/meater/coordinator.py",
"license": "Apache License 2.0",
"lines": 68,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/meater/diagnostics.py | """Diagnostics support for the Meater integration."""
from __future__ import annotations
from typing import Any
from homeassistant.core import HomeAssistant
from . import MeaterConfigEntry
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: MeaterConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = config_entry.runtime_data
return {
identifier: {
"id": probe.id,
"internal_temperature": probe.internal_temperature,
"ambient_temperature": probe.ambient_temperature,
"time_updated": probe.time_updated.isoformat(),
"cook": (
{
"id": probe.cook.id,
"name": probe.cook.name,
"state": probe.cook.state,
"target_temperature": (
probe.cook.target_temperature
if hasattr(probe.cook, "target_temperature")
else None
),
"peak_temperature": (
probe.cook.peak_temperature
if hasattr(probe.cook, "peak_temperature")
else None
),
"time_remaining": (
probe.cook.time_remaining
if hasattr(probe.cook, "time_remaining")
else None
),
"time_elapsed": (
probe.cook.time_elapsed
if hasattr(probe.cook, "time_elapsed")
else None
),
}
if probe.cook
else None
),
}
for identifier, probe in coordinator.data.items()
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/meater/diagnostics.py",
"license": "Apache License 2.0",
"lines": 48,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/music_assistant/button.py | """Music Assistant Button platform."""
from __future__ import annotations
from homeassistant.components.button import ButtonEntity, ButtonEntityDescription
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import MusicAssistantConfigEntry
from .entity import MusicAssistantEntity
from .helpers import catch_musicassistant_error
async def async_setup_entry(
hass: HomeAssistant,
entry: MusicAssistantConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Music Assistant MediaPlayer(s) from Config Entry."""
mass = entry.runtime_data.mass
def add_player(player_id: str) -> None:
"""Handle add player."""
async_add_entities(
[
# Add button entity to favorite the currently playing item on the player
MusicAssistantFavoriteButton(mass, player_id)
]
)
# register callback to add players when they are discovered
entry.runtime_data.platform_handlers.setdefault(Platform.BUTTON, add_player)
class MusicAssistantFavoriteButton(MusicAssistantEntity, ButtonEntity):
"""Representation of a Button entity to favorite the currently playing item on a player."""
entity_description = ButtonEntityDescription(
key="favorite_now_playing",
translation_key="favorite_now_playing",
)
@catch_musicassistant_error
async def async_press(self) -> None:
"""Handle the button press command."""
await self.mass.players.add_currently_playing_to_favorites(self.player_id)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/music_assistant/button.py",
"license": "Apache License 2.0",
"lines": 36,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/music_assistant/helpers.py | """Helpers for the Music Assistant integration."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
import functools
from typing import TYPE_CHECKING, Any
from music_assistant_models.errors import MusicAssistantError
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
if TYPE_CHECKING:
from music_assistant_client import MusicAssistantClient
from . import MusicAssistantConfigEntry
def catch_musicassistant_error[**_P, _R](
func: Callable[_P, Coroutine[Any, Any, _R]],
) -> Callable[_P, Coroutine[Any, Any, _R]]:
"""Check and convert commands to players."""
@functools.wraps(func)
async def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
"""Catch Music Assistant errors and convert to Home Assistant error."""
try:
return await func(*args, **kwargs)
except MusicAssistantError as err:
error_msg = str(err) or err.__class__.__name__
raise HomeAssistantError(error_msg) from err
return wrapper
@callback
def get_music_assistant_client(
hass: HomeAssistant, config_entry_id: str
) -> MusicAssistantClient:
"""Get the Music Assistant client for the given config entry."""
entry: MusicAssistantConfigEntry | None
if not (entry := hass.config_entries.async_get_entry(config_entry_id)):
raise ServiceValidationError("Entry not found")
if entry.state is not ConfigEntryState.LOADED:
raise ServiceValidationError("Entry not loaded")
return entry.runtime_data.mass
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/music_assistant/helpers.py",
"license": "Apache License 2.0",
"lines": 36,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/nextdns/entity.py | """Define NextDNS entities."""
from nextdns.model import NextDnsData
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import NextDnsUpdateCoordinator
class NextDnsEntity[CoordinatorDataT: NextDnsData](
CoordinatorEntity[NextDnsUpdateCoordinator[CoordinatorDataT]]
):
"""Define NextDNS entity."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: NextDnsUpdateCoordinator[CoordinatorDataT],
description: EntityDescription,
) -> None:
"""Initialize."""
super().__init__(coordinator)
self._attr_device_info = DeviceInfo(
configuration_url=f"https://my.nextdns.io/{coordinator.profile_id}/setup",
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, str(coordinator.profile_id))},
manufacturer="NextDNS Inc.",
name=coordinator.nextdns.get_profile_name(coordinator.profile_id),
)
self._attr_unique_id = f"{coordinator.profile_id}_{description.key}"
self.entity_description = description
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/nextdns/entity.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ntfy/coordinator.py | """DataUpdateCoordinator for ntfy integration."""
from __future__ import annotations
from abc import abstractmethod
from dataclasses import dataclass
from datetime import timedelta
import logging
from aiontfy import Account as NtfyAccount, Ntfy, Version
from aiontfy.exceptions import (
NtfyConnectionError,
NtfyHTTPError,
NtfyNotFoundPageError,
NtfyTimeoutError,
NtfyUnauthorizedAuthenticationError,
)
from aiontfy.update import LatestRelease, UpdateChecker, UpdateCheckerError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
type NtfyConfigEntry = ConfigEntry[NtfyRuntimeData]
@dataclass
class NtfyRuntimeData:
"""Holds ntfy runtime data."""
account: NtfyDataUpdateCoordinator
version: NtfyVersionDataUpdateCoordinator
class BaseDataUpdateCoordinator[_DataT](DataUpdateCoordinator[_DataT]):
"""Ntfy base coordinator."""
config_entry: NtfyConfigEntry
update_interval: timedelta
def __init__(
self, hass: HomeAssistant, config_entry: NtfyConfigEntry, ntfy: Ntfy
) -> None:
"""Initialize the ntfy data update coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=DOMAIN,
update_interval=self.update_interval,
)
self.ntfy = ntfy
@abstractmethod
async def async_update_data(self) -> _DataT:
"""Fetch the latest data from the source."""
async def _async_update_data(self) -> _DataT:
"""Fetch the latest data from the source."""
try:
return await self.async_update_data()
except NtfyHTTPError as e:
_LOGGER.debug("Error %s: %s [%s]", e.code, e.error, e.link)
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="server_error",
translation_placeholders={"error_msg": str(e.error)},
) from e
except NtfyConnectionError as e:
_LOGGER.debug("Error", exc_info=True)
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="connection_error",
) from e
except NtfyTimeoutError as e:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="timeout_error",
) from e
class NtfyDataUpdateCoordinator(BaseDataUpdateCoordinator[NtfyAccount]):
"""Ntfy data update coordinator."""
update_interval = timedelta(minutes=15)
async def async_update_data(self) -> NtfyAccount:
"""Fetch account data from ntfy."""
try:
return await self.ntfy.account()
except NtfyUnauthorizedAuthenticationError as e:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="authentication_error",
) from e
class NtfyVersionDataUpdateCoordinator(BaseDataUpdateCoordinator[Version | None]):
"""Ntfy data update coordinator."""
update_interval = timedelta(hours=3)
async def async_update_data(self) -> Version | None:
"""Fetch version data from ntfy."""
try:
version = await self.ntfy.version()
except NtfyUnauthorizedAuthenticationError, NtfyNotFoundPageError:
# /v1/version endpoint is only accessible to admins and
# available in ntfy since version 2.17.0
return None
return version
class NtfyLatestReleaseUpdateCoordinator(DataUpdateCoordinator[LatestRelease]):
"""Ntfy latest release update coordinator."""
def __init__(self, hass: HomeAssistant, update_checker: UpdateChecker) -> None:
"""Initialize coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=None,
name=DOMAIN,
update_interval=timedelta(hours=3),
)
self.update_checker = update_checker
async def _async_update_data(self) -> LatestRelease:
"""Fetch latest release data."""
try:
return await self.update_checker.latest_release()
except UpdateCheckerError as e:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_check_failed",
) from e
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ntfy/coordinator.py",
"license": "Apache License 2.0",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/ntfy/sensor.py | """Sensor platform for ntfy integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from enum import StrEnum
from aiontfy import Account as NtfyAccount
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import EntityCategory, UnitOfInformation, UnitOfTime
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .coordinator import NtfyConfigEntry, NtfyDataUpdateCoordinator
from .entity import NtfyCommonBaseEntity
PARALLEL_UPDATES = 0
@dataclass(kw_only=True, frozen=True)
class NtfySensorEntityDescription(SensorEntityDescription):
"""Ntfy Sensor Description."""
value_fn: Callable[[NtfyAccount], StateType]
class NtfySensor(StrEnum):
"""Ntfy sensors."""
MESSAGES = "messages"
MESSAGES_REMAINING = "messages_remaining"
MESSAGES_LIMIT = "messages_limit"
MESSAGES_EXPIRY_DURATION = "messages_expiry_duration"
EMAILS = "emails"
EMAILS_REMAINING = "emails_remaining"
EMAILS_LIMIT = "emails_limit"
CALLS = "calls"
CALLS_REMAINING = "calls_remaining"
CALLS_LIMIT = "calls_limit"
RESERVATIONS = "reservations"
RESERVATIONS_REMAINING = "reservations_remaining"
RESERVATIONS_LIMIT = "reservations_limit"
ATTACHMENT_TOTAL_SIZE = "attachment_total_size"
ATTACHMENT_TOTAL_SIZE_REMAINING = "attachment_total_size_remaining"
ATTACHMENT_TOTAL_SIZE_LIMIT = "attachment_total_size_limit"
ATTACHMENT_EXPIRY_DURATION = "attachment_expiry_duration"
ATTACHMENT_BANDWIDTH = "attachment_bandwidth"
ATTACHMENT_FILE_SIZE = "attachment_file_size"
TIER = "tier"
SENSOR_DESCRIPTIONS: tuple[NtfySensorEntityDescription, ...] = (
NtfySensorEntityDescription(
key=NtfySensor.MESSAGES,
translation_key=NtfySensor.MESSAGES,
value_fn=lambda account: account.stats.messages,
),
NtfySensorEntityDescription(
key=NtfySensor.MESSAGES_REMAINING,
translation_key=NtfySensor.MESSAGES_REMAINING,
value_fn=lambda account: account.stats.messages_remaining,
entity_registry_enabled_default=False,
),
NtfySensorEntityDescription(
key=NtfySensor.MESSAGES_LIMIT,
translation_key=NtfySensor.MESSAGES_LIMIT,
value_fn=lambda account: account.limits.messages if account.limits else None,
entity_category=EntityCategory.DIAGNOSTIC,
),
NtfySensorEntityDescription(
key=NtfySensor.MESSAGES_EXPIRY_DURATION,
translation_key=NtfySensor.MESSAGES_EXPIRY_DURATION,
value_fn=(
lambda account: (
account.limits.messages_expiry_duration if account.limits else None
)
),
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
suggested_unit_of_measurement=UnitOfTime.HOURS,
),
NtfySensorEntityDescription(
key=NtfySensor.EMAILS,
translation_key=NtfySensor.EMAILS,
value_fn=lambda account: account.stats.emails,
),
NtfySensorEntityDescription(
key=NtfySensor.EMAILS_REMAINING,
translation_key=NtfySensor.EMAILS_REMAINING,
value_fn=lambda account: account.stats.emails_remaining,
entity_registry_enabled_default=False,
),
NtfySensorEntityDescription(
key=NtfySensor.EMAILS_LIMIT,
translation_key=NtfySensor.EMAILS_LIMIT,
value_fn=lambda account: account.limits.emails if account.limits else None,
entity_category=EntityCategory.DIAGNOSTIC,
),
NtfySensorEntityDescription(
key=NtfySensor.CALLS,
translation_key=NtfySensor.CALLS,
value_fn=lambda account: account.stats.calls,
),
NtfySensorEntityDescription(
key=NtfySensor.CALLS_REMAINING,
translation_key=NtfySensor.CALLS_REMAINING,
value_fn=lambda account: account.stats.calls_remaining,
entity_registry_enabled_default=False,
),
NtfySensorEntityDescription(
key=NtfySensor.CALLS_LIMIT,
translation_key=NtfySensor.CALLS_LIMIT,
value_fn=lambda account: account.limits.calls if account.limits else None,
entity_category=EntityCategory.DIAGNOSTIC,
),
NtfySensorEntityDescription(
key=NtfySensor.RESERVATIONS,
translation_key=NtfySensor.RESERVATIONS,
value_fn=lambda account: account.stats.reservations,
),
NtfySensorEntityDescription(
key=NtfySensor.RESERVATIONS_REMAINING,
translation_key=NtfySensor.RESERVATIONS_REMAINING,
value_fn=lambda account: account.stats.reservations_remaining,
entity_registry_enabled_default=False,
),
NtfySensorEntityDescription(
key=NtfySensor.RESERVATIONS_LIMIT,
translation_key=NtfySensor.RESERVATIONS_LIMIT,
value_fn=(
lambda account: account.limits.reservations if account.limits else None
),
entity_category=EntityCategory.DIAGNOSTIC,
),
NtfySensorEntityDescription(
key=NtfySensor.ATTACHMENT_EXPIRY_DURATION,
translation_key=NtfySensor.ATTACHMENT_EXPIRY_DURATION,
value_fn=(
lambda account: (
account.limits.attachment_expiry_duration if account.limits else None
)
),
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
suggested_unit_of_measurement=UnitOfTime.HOURS,
),
NtfySensorEntityDescription(
key=NtfySensor.ATTACHMENT_TOTAL_SIZE,
translation_key=NtfySensor.ATTACHMENT_TOTAL_SIZE,
value_fn=lambda account: account.stats.attachment_total_size,
device_class=SensorDeviceClass.DATA_SIZE,
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES,
suggested_display_precision=2,
),
NtfySensorEntityDescription(
key=NtfySensor.ATTACHMENT_TOTAL_SIZE_REMAINING,
translation_key=NtfySensor.ATTACHMENT_TOTAL_SIZE_REMAINING,
value_fn=lambda account: account.stats.attachment_total_size_remaining,
device_class=SensorDeviceClass.DATA_SIZE,
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES,
suggested_display_precision=2,
entity_registry_enabled_default=False,
),
NtfySensorEntityDescription(
key=NtfySensor.ATTACHMENT_TOTAL_SIZE_LIMIT,
translation_key=NtfySensor.ATTACHMENT_TOTAL_SIZE_LIMIT,
value_fn=(
lambda account: (
account.limits.attachment_total_size if account.limits else None
)
),
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.DATA_SIZE,
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES,
suggested_display_precision=0,
),
NtfySensorEntityDescription(
key=NtfySensor.ATTACHMENT_FILE_SIZE,
translation_key=NtfySensor.ATTACHMENT_FILE_SIZE,
value_fn=(
lambda account: (
account.limits.attachment_file_size if account.limits else None
)
),
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.DATA_SIZE,
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES,
suggested_display_precision=0,
),
NtfySensorEntityDescription(
key=NtfySensor.ATTACHMENT_BANDWIDTH,
translation_key=NtfySensor.ATTACHMENT_BANDWIDTH,
value_fn=(
lambda account: (
account.limits.attachment_bandwidth if account.limits else None
)
),
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.DATA_SIZE,
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES,
suggested_display_precision=0,
),
NtfySensorEntityDescription(
key=NtfySensor.TIER,
translation_key=NtfySensor.TIER,
value_fn=lambda account: account.tier.name if account.tier else "free",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: NtfyConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the sensor platform."""
coordinator = config_entry.runtime_data.account
async_add_entities(
NtfySensorEntity(coordinator, description)
for description in SENSOR_DESCRIPTIONS
)
class NtfySensorEntity(NtfyCommonBaseEntity, SensorEntity):
"""Representation of a ntfy sensor entity."""
entity_description: NtfySensorEntityDescription
coordinator: NtfyDataUpdateCoordinator
@property
def native_value(self) -> StateType:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.coordinator.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ntfy/sensor.py",
"license": "Apache License 2.0",
"lines": 229,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/nzbget/services.py | """The NZBGet integration."""
import voluptuous as vol
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import config_validation as cv
from .const import (
ATTR_SPEED,
DATA_COORDINATOR,
DEFAULT_SPEED_LIMIT,
DOMAIN,
SERVICE_PAUSE,
SERVICE_RESUME,
SERVICE_SET_SPEED,
)
from .coordinator import NZBGetDataUpdateCoordinator
SPEED_LIMIT_SCHEMA = vol.Schema(
{vol.Optional(ATTR_SPEED, default=DEFAULT_SPEED_LIMIT): cv.positive_int}
)
def _get_coordinator(call: ServiceCall) -> NZBGetDataUpdateCoordinator:
"""Service call to pause downloads in NZBGet."""
entries = call.hass.config_entries.async_loaded_entries(DOMAIN)
if not entries:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_config_entry",
)
return call.hass.data[DOMAIN][entries[0].entry_id][DATA_COORDINATOR]
def pause(call: ServiceCall) -> None:
"""Service call to pause downloads in NZBGet."""
_get_coordinator(call).nzbget.pausedownload()
def resume(call: ServiceCall) -> None:
"""Service call to resume downloads in NZBGet."""
_get_coordinator(call).nzbget.resumedownload()
def set_speed(call: ServiceCall) -> None:
"""Service call to rate limit speeds in NZBGet."""
_get_coordinator(call).nzbget.rate(call.data[ATTR_SPEED])
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register integration-level services."""
hass.services.async_register(DOMAIN, SERVICE_PAUSE, pause, schema=vol.Schema({}))
hass.services.async_register(DOMAIN, SERVICE_RESUME, resume, schema=vol.Schema({}))
hass.services.async_register(
DOMAIN, SERVICE_SET_SPEED, set_speed, schema=SPEED_LIMIT_SCHEMA
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/nzbget/services.py",
"license": "Apache License 2.0",
"lines": 44,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ollama/entity.py | """Base entity for the Ollama integration."""
from __future__ import annotations
from collections.abc import AsyncGenerator, AsyncIterator, Callable
import json
import logging
from typing import Any
import ollama
import voluptuous as vol
from voluptuous_openapi import convert
from homeassistant.components import conversation
from homeassistant.config_entries import ConfigSubentry
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, llm
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.json import json_dumps
from . import OllamaConfigEntry
from .const import (
CONF_KEEP_ALIVE,
CONF_MAX_HISTORY,
CONF_MODEL,
CONF_NUM_CTX,
CONF_THINK,
DEFAULT_KEEP_ALIVE,
DEFAULT_MAX_HISTORY,
DEFAULT_NUM_CTX,
DOMAIN,
)
from .models import MessageHistory, MessageRole
# Max number of back and forth with the LLM to generate a response
MAX_TOOL_ITERATIONS = 10
_LOGGER = logging.getLogger(__name__)
def _format_tool(
tool: llm.Tool, custom_serializer: Callable[[Any], Any] | None
) -> dict[str, Any]:
"""Format tool specification."""
tool_spec = {
"name": tool.name,
"parameters": convert(tool.parameters, custom_serializer=custom_serializer),
}
if tool.description:
tool_spec["description"] = tool.description
return {"type": "function", "function": tool_spec}
def _fix_invalid_arguments(value: Any) -> Any:
"""Attempt to repair incorrectly formatted json function arguments.
Small models (for example llama3.1 8B) may produce invalid argument values
which we attempt to repair here.
"""
if not isinstance(value, str):
return value
if (value.startswith("[") and value.endswith("]")) or (
value.startswith("{") and value.endswith("}")
):
try:
return json.loads(value)
except json.decoder.JSONDecodeError:
pass
return value
def _parse_tool_args(arguments: dict[str, Any]) -> dict[str, Any]:
"""Rewrite ollama tool arguments.
This function improves tool use quality by fixing common mistakes made by
small local tool use models. This will repair invalid json arguments and
omit unnecessary arguments with empty values that will fail intent parsing.
"""
return {
k: _fix_invalid_arguments(v)
for k, v in arguments.items()
if v is not None and v != ""
}
def _convert_content(
chat_content: (
conversation.Content
| conversation.ToolResultContent
| conversation.AssistantContent
),
) -> ollama.Message:
"""Create tool response content."""
if isinstance(chat_content, conversation.ToolResultContent):
return ollama.Message(
role=MessageRole.TOOL.value,
content=json_dumps(chat_content.tool_result),
)
if isinstance(chat_content, conversation.AssistantContent):
return ollama.Message(
role=MessageRole.ASSISTANT.value,
content=chat_content.content,
thinking=chat_content.thinking_content,
tool_calls=[
ollama.Message.ToolCall(
function=ollama.Message.ToolCall.Function(
name=tool_call.tool_name,
arguments=tool_call.tool_args,
)
)
for tool_call in chat_content.tool_calls or ()
]
or None,
)
if isinstance(chat_content, conversation.UserContent):
images: list[ollama.Image] = []
for attachment in chat_content.attachments or ():
if not attachment.mime_type.startswith("image/"):
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="unsupported_attachment_type",
)
images.append(ollama.Image(value=attachment.path))
return ollama.Message(
role=MessageRole.USER.value,
content=chat_content.content,
images=images or None,
)
if isinstance(chat_content, conversation.SystemContent):
return ollama.Message(
role=MessageRole.SYSTEM.value,
content=chat_content.content,
)
raise TypeError(f"Unexpected content type: {type(chat_content)}")
async def _transform_stream(
result: AsyncIterator[ollama.ChatResponse],
) -> AsyncGenerator[conversation.AssistantContentDeltaDict]:
"""Transform the response stream into HA format.
An Ollama streaming response may come in chunks like this:
response: message=Message(role="assistant", content="Paris")
response: message=Message(role="assistant", content=".")
response: message=Message(role="assistant", content=""), done: True, done_reason: "stop"
response: message=Message(role="assistant", tool_calls=[...])
response: message=Message(role="assistant", content=""), done: True, done_reason: "stop"
This generator conforms to the chatlog delta stream expectations in that it
yields deltas, then the role only once the response is done.
"""
new_msg = True
async for response in result:
_LOGGER.debug("Received response: %s", response)
response_message = response["message"]
chunk: conversation.AssistantContentDeltaDict = {}
if new_msg:
new_msg = False
chunk["role"] = "assistant"
if (tool_calls := response_message.get("tool_calls")) is not None:
chunk["tool_calls"] = [
llm.ToolInput(
tool_name=tool_call["function"]["name"],
tool_args=_parse_tool_args(tool_call["function"]["arguments"]),
)
for tool_call in tool_calls
]
if (content := response_message.get("content")) is not None:
chunk["content"] = content
if (thinking := response_message.get("thinking")) is not None:
chunk["thinking_content"] = thinking
if response_message.get("done"):
new_msg = True
yield chunk
class OllamaBaseLLMEntity(Entity):
"""Ollama base LLM entity."""
_attr_has_entity_name = True
_attr_name = None
def __init__(self, entry: OllamaConfigEntry, subentry: ConfigSubentry) -> None:
"""Initialize the entity."""
self.entry = entry
self.subentry = subentry
self._attr_unique_id = subentry.subentry_id
model, _, version = subentry.data[CONF_MODEL].partition(":")
self._attr_device_info = dr.DeviceInfo(
identifiers={(DOMAIN, subentry.subentry_id)},
name=subentry.title,
manufacturer="Ollama",
model=model,
sw_version=version or "latest",
entry_type=dr.DeviceEntryType.SERVICE,
)
async def _async_handle_chat_log(
self,
chat_log: conversation.ChatLog,
structure: vol.Schema | None = None,
) -> None:
"""Generate an answer for the chat log."""
settings = {**self.entry.data, **self.subentry.data}
client = self.entry.runtime_data
model = settings[CONF_MODEL]
tools: list[dict[str, Any]] | None = None
if chat_log.llm_api:
tools = [
_format_tool(tool, chat_log.llm_api.custom_serializer)
for tool in chat_log.llm_api.tools
]
message_history: MessageHistory = MessageHistory(
[_convert_content(content) for content in chat_log.content]
)
max_messages = int(settings.get(CONF_MAX_HISTORY, DEFAULT_MAX_HISTORY))
self._trim_history(message_history, max_messages)
output_format: dict[str, Any] | None = None
if structure:
output_format = convert(
structure,
custom_serializer=(
chat_log.llm_api.custom_serializer
if chat_log.llm_api
else llm.selector_serializer
),
)
# Get response
# To prevent infinite loops, we limit the number of iterations
for _iteration in range(MAX_TOOL_ITERATIONS):
try:
response_generator = await client.chat(
model=model,
# Make a copy of the messages because we mutate the list later
messages=list(message_history.messages),
tools=tools,
stream=True,
# keep_alive requires specifying unit. In this case, seconds
keep_alive=f"{settings.get(CONF_KEEP_ALIVE, DEFAULT_KEEP_ALIVE)}s",
options={CONF_NUM_CTX: settings.get(CONF_NUM_CTX, DEFAULT_NUM_CTX)},
think=settings.get(CONF_THINK),
format=output_format,
)
except (ollama.RequestError, ollama.ResponseError) as err:
_LOGGER.error("Unexpected error talking to Ollama server: %s", err)
raise HomeAssistantError(
f"Sorry, I had a problem talking to the Ollama server: {err}"
) from err
message_history.messages.extend(
[
_convert_content(content)
async for content in chat_log.async_add_delta_content_stream(
self.entity_id, _transform_stream(response_generator)
)
]
)
if not chat_log.unresponded_tool_results:
break
def _trim_history(self, message_history: MessageHistory, max_messages: int) -> None:
"""Trims excess messages from a single history.
This sets the max history to allow a configurable size history may take
up in the context window.
Note that some messages in the history may not be from ollama only, and
may come from other anents, so the assumptions here may not strictly hold,
but generally should be effective.
"""
if max_messages < 1:
# Keep all messages
return
# Ignore the in progress user message
num_previous_rounds = message_history.num_user_messages - 1
if num_previous_rounds >= max_messages:
# Trim history but keep system prompt (first message).
# Every other message should be an assistant message, so keep 2x
# message objects. Also keep the last in progress user message
num_keep = 2 * max_messages + 1
drop_index = len(message_history.messages) - num_keep
message_history.messages = [
message_history.messages[0],
*message_history.messages[drop_index:],
]
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ollama/entity.py",
"license": "Apache License 2.0",
"lines": 255,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/opentherm_gw/services.py | """Support for OpenTherm Gateway devices."""
from __future__ import annotations
from datetime import date, datetime
from typing import TYPE_CHECKING
import pyotgw.vars as gw_vars
import voluptuous as vol
from homeassistant.const import (
ATTR_DATE,
ATTR_ID,
ATTR_MODE,
ATTR_TEMPERATURE,
ATTR_TIME,
)
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import config_validation as cv
from .const import (
ATTR_CH_OVRD,
ATTR_DHW_OVRD,
ATTR_GW_ID,
ATTR_LEVEL,
ATTR_TRANSP_ARG,
ATTR_TRANSP_CMD,
DATA_GATEWAYS,
DATA_OPENTHERM_GW,
DOMAIN,
SERVICE_RESET_GATEWAY,
SERVICE_SEND_TRANSP_CMD,
SERVICE_SET_CH_OVRD,
SERVICE_SET_CLOCK,
SERVICE_SET_CONTROL_SETPOINT,
SERVICE_SET_GPIO_MODE,
SERVICE_SET_HOT_WATER_OVRD,
SERVICE_SET_HOT_WATER_SETPOINT,
SERVICE_SET_LED_MODE,
SERVICE_SET_MAX_MOD,
SERVICE_SET_OAT,
SERVICE_SET_SB_TEMP,
)
if TYPE_CHECKING:
from . import OpenThermGatewayHub
def _get_gateway(call: ServiceCall) -> OpenThermGatewayHub:
gw_id: str = call.data[ATTR_GW_ID]
gw_hub: OpenThermGatewayHub | None = (
call.hass.data.get(DATA_OPENTHERM_GW, {}).get(DATA_GATEWAYS, {}).get(gw_id)
)
if gw_hub is None:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_gateway_id",
translation_placeholders={"gw_id": gw_id},
)
return gw_hub
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register services for the component."""
service_reset_schema = vol.Schema({vol.Required(ATTR_GW_ID): vol.All(cv.string)})
service_set_central_heating_ovrd_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_CH_OVRD): cv.boolean,
}
)
service_set_clock_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Optional(ATTR_DATE, default=date.today): cv.date,
vol.Optional(ATTR_TIME, default=lambda: datetime.now().time()): cv.time,
}
)
service_set_control_setpoint_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_TEMPERATURE): vol.All(
vol.Coerce(float), vol.Range(min=0, max=90)
),
}
)
service_set_hot_water_setpoint_schema = service_set_control_setpoint_schema
service_set_hot_water_ovrd_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_DHW_OVRD): vol.Any(
vol.Equal("A"), vol.All(vol.Coerce(int), vol.Range(min=0, max=1))
),
}
)
service_set_gpio_mode_schema = vol.Schema(
vol.Any(
vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_ID): vol.Equal("A"),
vol.Required(ATTR_MODE): vol.All(
vol.Coerce(int), vol.Range(min=0, max=6)
),
}
),
vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_ID): vol.Equal("B"),
vol.Required(ATTR_MODE): vol.All(
vol.Coerce(int), vol.Range(min=0, max=7)
),
}
),
)
)
service_set_led_mode_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_ID): vol.In("ABCDEF"),
vol.Required(ATTR_MODE): vol.In("RXTBOFHWCEMP"),
}
)
service_set_max_mod_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_LEVEL): vol.All(
vol.Coerce(int), vol.Range(min=-1, max=100)
),
}
)
service_set_oat_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_TEMPERATURE): vol.All(
vol.Coerce(float), vol.Range(min=-40, max=99)
),
}
)
service_set_sb_temp_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_TEMPERATURE): vol.All(
vol.Coerce(float), vol.Range(min=0, max=30)
),
}
)
service_send_transp_cmd_schema = vol.Schema(
{
vol.Required(ATTR_GW_ID): vol.All(cv.string),
vol.Required(ATTR_TRANSP_CMD): vol.All(
cv.string, vol.Length(min=2, max=2), vol.Coerce(str.upper)
),
vol.Required(ATTR_TRANSP_ARG): vol.All(
cv.string, vol.Length(min=1, max=12)
),
}
)
async def reset_gateway(call: ServiceCall) -> None:
"""Reset the OpenTherm Gateway."""
gw_hub = _get_gateway(call)
mode_rst = gw_vars.OTGW_MODE_RESET
await gw_hub.gateway.set_mode(mode_rst)
hass.services.async_register(
DOMAIN, SERVICE_RESET_GATEWAY, reset_gateway, service_reset_schema
)
async def set_ch_ovrd(call: ServiceCall) -> None:
"""Set the central heating override on the OpenTherm Gateway."""
gw_hub = _get_gateway(call)
await gw_hub.gateway.set_ch_enable_bit(1 if call.data[ATTR_CH_OVRD] else 0)
hass.services.async_register(
DOMAIN,
SERVICE_SET_CH_OVRD,
set_ch_ovrd,
service_set_central_heating_ovrd_schema,
)
async def set_control_setpoint(call: ServiceCall) -> None:
"""Set the control setpoint on the OpenTherm Gateway."""
gw_hub = _get_gateway(call)
await gw_hub.gateway.set_control_setpoint(call.data[ATTR_TEMPERATURE])
hass.services.async_register(
DOMAIN,
SERVICE_SET_CONTROL_SETPOINT,
set_control_setpoint,
service_set_control_setpoint_schema,
)
async def set_dhw_ovrd(call: ServiceCall) -> None:
"""Set the domestic hot water override on the OpenTherm Gateway."""
gw_hub = _get_gateway(call)
await gw_hub.gateway.set_hot_water_ovrd(call.data[ATTR_DHW_OVRD])
hass.services.async_register(
DOMAIN,
SERVICE_SET_HOT_WATER_OVRD,
set_dhw_ovrd,
service_set_hot_water_ovrd_schema,
)
async def set_dhw_setpoint(call: ServiceCall) -> None:
"""Set the domestic hot water setpoint on the OpenTherm Gateway."""
gw_hub = _get_gateway(call)
await gw_hub.gateway.set_dhw_setpoint(call.data[ATTR_TEMPERATURE])
hass.services.async_register(
DOMAIN,
SERVICE_SET_HOT_WATER_SETPOINT,
set_dhw_setpoint,
service_set_hot_water_setpoint_schema,
)
async def set_device_clock(call: ServiceCall) -> None:
"""Set the clock on the OpenTherm Gateway."""
gw_hub = _get_gateway(call)
attr_date = call.data[ATTR_DATE]
attr_time = call.data[ATTR_TIME]
await gw_hub.gateway.set_clock(datetime.combine(attr_date, attr_time))
hass.services.async_register(
DOMAIN, SERVICE_SET_CLOCK, set_device_clock, service_set_clock_schema
)
async def set_gpio_mode(call: ServiceCall) -> None:
"""Set the OpenTherm Gateway GPIO modes."""
gw_hub = _get_gateway(call)
gpio_id = call.data[ATTR_ID]
gpio_mode = call.data[ATTR_MODE]
await gw_hub.gateway.set_gpio_mode(gpio_id, gpio_mode)
hass.services.async_register(
DOMAIN,
SERVICE_SET_GPIO_MODE,
set_gpio_mode,
service_set_gpio_mode_schema,
description_placeholders={
"gpio_modes_documentation_url": "https://www.home-assistant.io/integrations/opentherm_gw/#gpio-modes"
},
)
async def set_led_mode(call: ServiceCall) -> None:
"""Set the OpenTherm Gateway LED modes."""
gw_hub = _get_gateway(call)
led_id = call.data[ATTR_ID]
led_mode = call.data[ATTR_MODE]
await gw_hub.gateway.set_led_mode(led_id, led_mode)
hass.services.async_register(
DOMAIN,
SERVICE_SET_LED_MODE,
set_led_mode,
service_set_led_mode_schema,
description_placeholders={
"led_modes_documentation_url": "https://www.home-assistant.io/integrations/opentherm_gw/#led-modes"
},
)
async def set_max_mod(call: ServiceCall) -> None:
"""Set the max modulation level."""
gw_hub = _get_gateway(call)
level = call.data[ATTR_LEVEL]
if level == -1:
# Backend only clears setting on non-numeric values.
level = "-"
await gw_hub.gateway.set_max_relative_mod(level)
hass.services.async_register(
DOMAIN, SERVICE_SET_MAX_MOD, set_max_mod, service_set_max_mod_schema
)
async def set_outside_temp(call: ServiceCall) -> None:
"""Provide the outside temperature to the OpenTherm Gateway."""
gw_hub = _get_gateway(call)
await gw_hub.gateway.set_outside_temp(call.data[ATTR_TEMPERATURE])
hass.services.async_register(
DOMAIN, SERVICE_SET_OAT, set_outside_temp, service_set_oat_schema
)
async def set_setback_temp(call: ServiceCall) -> None:
"""Set the OpenTherm Gateway SetBack temperature."""
gw_hub = _get_gateway(call)
await gw_hub.gateway.set_setback_temp(call.data[ATTR_TEMPERATURE])
hass.services.async_register(
DOMAIN, SERVICE_SET_SB_TEMP, set_setback_temp, service_set_sb_temp_schema
)
async def send_transparent_cmd(call: ServiceCall) -> None:
"""Send a transparent OpenTherm Gateway command."""
gw_hub = _get_gateway(call)
transp_cmd = call.data[ATTR_TRANSP_CMD]
transp_arg = call.data[ATTR_TRANSP_ARG]
await gw_hub.gateway.send_transparent_command(transp_cmd, transp_arg)
hass.services.async_register(
DOMAIN,
SERVICE_SEND_TRANSP_CMD,
send_transparent_cmd,
service_send_transp_cmd_schema,
description_placeholders={
"opentherm_gateway_firmware_url": "https://otgw.tclcode.com/firmware.html"
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/opentherm_gw/services.py",
"license": "Apache License 2.0",
"lines": 278,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/paperless_ngx/update.py | """Update platform for Paperless-ngx."""
from __future__ import annotations
from datetime import timedelta
from pypaperless.exceptions import PaperlessConnectionError
from homeassistant.components.update import (
UpdateDeviceClass,
UpdateEntity,
UpdateEntityDescription,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import LOGGER
from .coordinator import PaperlessConfigEntry, PaperlessStatusCoordinator
from .entity import PaperlessEntity
PAPERLESS_CHANGELOGS = "https://docs.paperless-ngx.com/changelog/"
PARALLEL_UPDATES = 1
SCAN_INTERVAL = timedelta(hours=24)
async def async_setup_entry(
hass: HomeAssistant,
entry: PaperlessConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Paperless-ngx update entities."""
description = UpdateEntityDescription(
key="paperless_update",
translation_key="paperless_update",
device_class=UpdateDeviceClass.FIRMWARE,
)
async_add_entities(
[
PaperlessUpdate(
coordinator=entry.runtime_data.status,
description=description,
)
],
update_before_add=True,
)
class PaperlessUpdate(PaperlessEntity[PaperlessStatusCoordinator], UpdateEntity):
"""Defines a Paperless-ngx update entity."""
release_url = PAPERLESS_CHANGELOGS
@property
def should_poll(self) -> bool:
"""Return True because we need to poll the latest version."""
return True
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._attr_available
@property
def installed_version(self) -> str | None:
"""Return the installed version."""
return self.coordinator.api.host_version
async def async_update(self) -> None:
"""Update the entity."""
remote_version = None
try:
remote_version = await self.coordinator.api.remote_version()
except PaperlessConnectionError as err:
if self._attr_available:
LOGGER.warning("Could not fetch remote version: %s", err)
self._attr_available = False
return
if remote_version.version is None or remote_version.version == "0.0.0":
if self._attr_available:
LOGGER.warning("Remote version is not available or invalid")
self._attr_available = False
return
self._attr_latest_version = remote_version.version.lstrip("v")
self._attr_available = True
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/paperless_ngx/update.py",
"license": "Apache License 2.0",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/playstation_network/config_flow.py | """Config flow for the PlayStation Network integration."""
from collections.abc import Mapping
import logging
from typing import Any
from psnawp_api.core.psnawp_exceptions import (
PSNAWPAuthenticationError,
PSNAWPError,
PSNAWPInvalidTokenError,
PSNAWPNotFoundError,
)
from psnawp_api.utils.misc import parse_npsso_token
import voluptuous as vol
from homeassistant.config_entries import (
SOURCE_REAUTH,
ConfigEntry,
ConfigEntryState,
ConfigFlow,
ConfigFlowResult,
ConfigSubentryFlow,
SubentryFlowResult,
)
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
from homeassistant.helpers.selector import (
SelectOptionDict,
SelectSelector,
SelectSelectorConfig,
)
from .const import CONF_ACCOUNT_ID, CONF_NPSSO, DOMAIN, NPSSO_LINK, PSN_LINK
from .coordinator import PlaystationNetworkConfigEntry
from .helpers import PlaystationNetwork
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_NPSSO): str})
class PlaystationNetworkConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Playstation Network."""
@classmethod
@callback
def async_get_supported_subentry_types(
cls, config_entry: ConfigEntry
) -> dict[str, type[ConfigSubentryFlow]]:
"""Return subentries supported by this integration."""
return {"friend": FriendSubentryFlowHandler}
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
npsso: str | None = None
if user_input is not None:
try:
npsso = parse_npsso_token(user_input[CONF_NPSSO])
except PSNAWPInvalidTokenError:
errors["base"] = "invalid_account"
else:
psn = PlaystationNetwork(self.hass, npsso)
try:
user = await psn.get_user()
except PSNAWPAuthenticationError:
errors["base"] = "invalid_auth"
except PSNAWPNotFoundError:
errors["base"] = "invalid_account"
except PSNAWPError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(user.account_id)
self._abort_if_unique_id_configured()
config_entries = self.hass.config_entries.async_entries(DOMAIN)
for entry in config_entries:
if user.account_id in {
subentry.unique_id for subentry in entry.subentries.values()
}:
return self.async_abort(
reason="already_configured_as_subentry"
)
return self.async_create_entry(
title=user.online_id,
data={CONF_NPSSO: npsso},
)
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
description_placeholders={
"npsso_link": NPSSO_LINK,
"psn_link": PSN_LINK,
},
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauth upon an API authentication error."""
return await self.async_step_reauth_confirm()
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Reconfigure flow for PlayStation Network integration."""
return await self.async_step_reauth_confirm(user_input)
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauthentication dialog."""
errors: dict[str, str] = {}
entry = (
self._get_reauth_entry()
if self.source == SOURCE_REAUTH
else self._get_reconfigure_entry()
)
if user_input is not None:
try:
npsso = parse_npsso_token(user_input[CONF_NPSSO])
psn = PlaystationNetwork(self.hass, npsso)
user = await psn.get_user()
except PSNAWPAuthenticationError:
errors["base"] = "invalid_auth"
except PSNAWPNotFoundError, PSNAWPInvalidTokenError:
errors["base"] = "invalid_account"
except PSNAWPError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(user.account_id)
self._abort_if_unique_id_mismatch(
description_placeholders={
"wrong_account": user.online_id,
CONF_NAME: entry.title,
}
)
return self.async_update_reload_and_abort(
entry,
data_updates={CONF_NPSSO: npsso},
)
return self.async_show_form(
step_id="reauth_confirm" if self.source == SOURCE_REAUTH else "reconfigure",
data_schema=self.add_suggested_values_to_schema(
data_schema=STEP_USER_DATA_SCHEMA, suggested_values=user_input
),
errors=errors,
description_placeholders={
"npsso_link": NPSSO_LINK,
"psn_link": PSN_LINK,
},
)
class FriendSubentryFlowHandler(ConfigSubentryFlow):
"""Handle subentry flow for adding a friend."""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""Subentry user flow."""
config_entry: PlaystationNetworkConfigEntry = self._get_entry()
if config_entry.state is not ConfigEntryState.LOADED:
return self.async_abort(reason="config_entry_disabled")
friends_list = config_entry.runtime_data.user_data.psn.friends_list
if user_input is not None:
config_entries = self.hass.config_entries.async_entries(DOMAIN)
if user_input[CONF_ACCOUNT_ID] in {
entry.unique_id for entry in config_entries
}:
return self.async_abort(reason="already_configured_as_entry")
for entry in config_entries:
if user_input[CONF_ACCOUNT_ID] in {
subentry.unique_id for subentry in entry.subentries.values()
}:
return self.async_abort(reason="already_configured")
return self.async_create_entry(
title=friends_list[user_input[CONF_ACCOUNT_ID]].online_id,
data={},
unique_id=user_input[CONF_ACCOUNT_ID],
)
if not friends_list:
return self.async_abort(reason="no_friends")
options = [
SelectOptionDict(
value=friend.account_id,
label=friend.online_id,
)
for friend in friends_list.values()
]
return self.async_show_form(
step_id="user",
data_schema=self.add_suggested_values_to_schema(
vol.Schema(
{
vol.Required(CONF_ACCOUNT_ID): SelectSelector(
SelectSelectorConfig(options=options)
)
}
),
user_input,
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/config_flow.py",
"license": "Apache License 2.0",
"lines": 195,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/playstation_network/const.py | """Constants for the Playstation Network integration."""
from typing import Final
from psnawp_api.models.trophies import PlatformType
DOMAIN = "playstation_network"
CONF_NPSSO: Final = "npsso"
CONF_ACCOUNT_ID: Final = "account_id"
SUPPORTED_PLATFORMS = {
PlatformType.PS_VITA,
PlatformType.PS3,
PlatformType.PS4,
PlatformType.PS5,
PlatformType.PSPC,
}
NPSSO_LINK: Final = "https://ca.account.sony.com/api/v1/ssocookie"
PSN_LINK: Final = "https://playstation.com"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/const.py",
"license": "Apache License 2.0",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/playstation_network/coordinator.py | """Coordinator for the PlayStation Network Integration."""
from __future__ import annotations
from abc import abstractmethod
from dataclasses import dataclass
from datetime import timedelta
import logging
from typing import TYPE_CHECKING, Any
from psnawp_api.core.psnawp_exceptions import (
PSNAWPAuthenticationError,
PSNAWPClientError,
PSNAWPError,
PSNAWPForbiddenError,
PSNAWPNotFoundError,
PSNAWPServerError,
)
from psnawp_api.models import User
from psnawp_api.models.group.group_datatypes import GroupDetails
from psnawp_api.models.trophies import TrophyTitle
from homeassistant.config_entries import ConfigEntry, ConfigSubentry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryError,
ConfigEntryNotReady,
)
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
from .helpers import PlaystationNetwork, PlaystationNetworkData
_LOGGER = logging.getLogger(__name__)
type PlaystationNetworkConfigEntry = ConfigEntry[PlaystationNetworkRuntimeData]
@dataclass
class PlaystationNetworkRuntimeData:
"""Dataclass holding PSN runtime data."""
user_data: PlaystationNetworkUserDataCoordinator
trophy_titles: PlaystationNetworkTrophyTitlesCoordinator
groups: PlaystationNetworkGroupsUpdateCoordinator
friends: dict[str, PlaystationNetworkFriendDataCoordinator]
friends_list: PlaystationNetworkFriendlistCoordinator
class PlayStationNetworkBaseCoordinator[_DataT](DataUpdateCoordinator[_DataT]):
"""Base coordinator for PSN."""
config_entry: PlaystationNetworkConfigEntry
_update_inverval: timedelta
def __init__(
self,
hass: HomeAssistant,
psn: PlaystationNetwork,
config_entry: PlaystationNetworkConfigEntry,
) -> None:
"""Initialize the Coordinator."""
super().__init__(
hass,
name=DOMAIN,
logger=_LOGGER,
config_entry=config_entry,
update_interval=self._update_interval,
)
self.psn = psn
@abstractmethod
async def update_data(self) -> _DataT:
"""Update coordinator data."""
async def _async_update_data(self) -> _DataT:
"""Get the latest data from the PSN."""
try:
return await self.update_data()
except PSNAWPAuthenticationError as error:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="not_ready",
) from error
except (PSNAWPServerError, PSNAWPClientError) as error:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_failed",
) from error
class PlaystationNetworkUserDataCoordinator(
PlayStationNetworkBaseCoordinator[PlaystationNetworkData]
):
"""Data update coordinator for PSN."""
_update_interval = timedelta(seconds=30)
async def _async_setup(self) -> None:
"""Set up the coordinator."""
try:
await self.psn.async_setup()
except PSNAWPAuthenticationError as error:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="not_ready",
) from error
except (PSNAWPServerError, PSNAWPClientError) as error:
raise ConfigEntryNotReady(
translation_domain=DOMAIN,
translation_key="update_failed",
) from error
async def update_data(self) -> PlaystationNetworkData:
"""Get the latest data from the PSN."""
return await self.psn.get_data()
class PlaystationNetworkTrophyTitlesCoordinator(
PlayStationNetworkBaseCoordinator[list[TrophyTitle]]
):
"""Trophy titles data update coordinator for PSN."""
_update_interval = timedelta(days=1)
async def update_data(self) -> list[TrophyTitle]:
"""Update trophy titles data."""
self.psn.trophy_titles = await self.hass.async_add_executor_job(
lambda: list(self.psn.user.trophy_titles(page_size=500))
)
await self.config_entry.runtime_data.user_data.async_request_refresh()
return self.psn.trophy_titles
class PlaystationNetworkFriendlistCoordinator(
PlayStationNetworkBaseCoordinator[dict[str, User]]
):
"""Friend list data update coordinator for PSN."""
_update_interval = timedelta(hours=3)
async def update_data(self) -> dict[str, User]:
"""Update trophy titles data."""
self.psn.friends_list = await self.hass.async_add_executor_job(
lambda: {
friend.account_id: friend for friend in self.psn.user.friends_list()
}
)
await self.config_entry.runtime_data.user_data.async_request_refresh()
return self.psn.friends_list
class PlaystationNetworkGroupsUpdateCoordinator(
PlayStationNetworkBaseCoordinator[dict[str, GroupDetails]]
):
"""Groups data update coordinator for PSN."""
_update_interval = timedelta(hours=3)
async def update_data(self) -> dict[str, GroupDetails]:
"""Update groups data."""
try:
return await self.hass.async_add_executor_job(
lambda: {
group_info.group_id: group_info.get_group_information()
for group_info in self.psn.client.get_groups()
if not group_info.group_id.startswith("~")
}
)
except PSNAWPForbiddenError as e:
ir.async_create_issue(
self.hass,
DOMAIN,
f"group_chat_forbidden_{self.config_entry.entry_id}",
is_fixable=False,
issue_domain=DOMAIN,
severity=ir.IssueSeverity.ERROR,
translation_key="group_chat_forbidden",
translation_placeholders={
CONF_NAME: self.config_entry.title,
"error_message": e.message or "",
},
)
await self.async_shutdown()
return {}
class PlaystationNetworkFriendDataCoordinator(
PlayStationNetworkBaseCoordinator[PlaystationNetworkData]
):
"""Friend status data update coordinator for PSN."""
user: User
profile: dict[str, Any]
def __init__(
self,
hass: HomeAssistant,
psn: PlaystationNetwork,
config_entry: PlaystationNetworkConfigEntry,
subentry: ConfigSubentry,
) -> None:
"""Initialize the Coordinator."""
self._update_interval = timedelta(
seconds=max(9 * len(config_entry.subentries), 180)
)
super().__init__(hass, psn, config_entry)
self.subentry = subentry
def _setup(self) -> None:
"""Set up the coordinator."""
if TYPE_CHECKING:
assert self.subentry.unique_id
self.user = self.psn.friends_list.get(
self.subentry.unique_id
) or self.psn.psn.user(account_id=self.subentry.unique_id)
self.profile = self.user.profile()
async def _async_setup(self) -> None:
"""Set up the coordinator."""
try:
await self.hass.async_add_executor_job(self._setup)
except PSNAWPNotFoundError as error:
raise ConfigEntryError(
translation_domain=DOMAIN,
translation_key="user_not_found",
translation_placeholders={"user": self.subentry.title},
) from error
except PSNAWPAuthenticationError as error:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="not_ready",
) from error
except (PSNAWPServerError, PSNAWPClientError) as error:
_LOGGER.debug("Update failed", exc_info=True)
raise ConfigEntryNotReady(
translation_domain=DOMAIN,
translation_key="update_failed",
) from error
def _update_data(self) -> PlaystationNetworkData:
"""Update friend status data."""
try:
presence = self.user.get_presence()
except PSNAWPForbiddenError as error:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="user_profile_private",
translation_placeholders={"user": self.subentry.title},
) from error
except PSNAWPError:
raise
try:
trophy_summary = self.user.trophy_summary()
except PSNAWPForbiddenError:
trophy_summary = None
return PlaystationNetworkData(
username=self.user.online_id,
account_id=self.user.account_id,
profile=self.profile,
presence=presence,
trophy_summary=trophy_summary,
)
async def update_data(self) -> PlaystationNetworkData:
"""Update friend status data."""
return await self.hass.async_add_executor_job(self._update_data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/coordinator.py",
"license": "Apache License 2.0",
"lines": 229,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/playstation_network/diagnostics.py | """Diagnostics support for PlayStation Network."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from psnawp_api.models.trophies import PlatformType
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.core import HomeAssistant
from .coordinator import PlaystationNetworkConfigEntry
TO_REDACT = {
"account_id",
"firstName",
"lastName",
"middleName",
"onlineId",
"url",
"username",
"onlineId",
"accountId",
"members",
"body",
"shareable_profile_link",
}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: PlaystationNetworkConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = entry.runtime_data.user_data
groups = entry.runtime_data.groups
return {
"data": async_redact_data(
_serialize_platform_types(asdict(coordinator.data)), TO_REDACT
),
"groups": async_redact_data(groups.data, TO_REDACT),
}
def _serialize_platform_types(data: Any) -> Any:
"""Recursively convert PlatformType enums to strings in dicts and sets."""
if isinstance(data, dict):
return {
(
platform.value if isinstance(platform, PlatformType) else platform
): _serialize_platform_types(record)
for platform, record in data.items()
}
if isinstance(data, set):
return sorted(
[
record.value if isinstance(record, PlatformType) else record
for record in data
]
)
if isinstance(data, PlatformType):
return data.value
return data
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/diagnostics.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/playstation_network/helpers.py | """Helper methods for common PlayStation Network integration operations."""
from __future__ import annotations
from dataclasses import dataclass, field
from functools import partial
from typing import Any
from psnawp_api import PSNAWP
from psnawp_api.models.client import Client
from psnawp_api.models.trophies import PlatformType, TrophySummary, TrophyTitle
from psnawp_api.models.user import User
from pyrate_limiter import Duration, Rate
from homeassistant.core import HomeAssistant
from .const import SUPPORTED_PLATFORMS
LEGACY_PLATFORMS = {PlatformType.PS3, PlatformType.PS4, PlatformType.PS_VITA}
@dataclass
class SessionData:
"""Dataclass representing console session data."""
platform: PlatformType = PlatformType.UNKNOWN
title_id: str | None = None
title_name: str | None = None
format: PlatformType | None = None
media_image_url: str | None = None
status: str = ""
@dataclass
class PlaystationNetworkData:
"""Dataclass representing data retrieved from the Playstation Network api."""
presence: dict[str, Any] = field(default_factory=dict)
username: str = ""
account_id: str = ""
active_sessions: dict[PlatformType, SessionData] = field(default_factory=dict)
registered_platforms: set[PlatformType] = field(default_factory=set)
trophy_summary: TrophySummary | None = None
profile: dict[str, Any] = field(default_factory=dict)
shareable_profile_link: dict[str, str] = field(default_factory=dict)
class PlaystationNetwork:
"""Helper Class to return playstation network data in an easy to use structure."""
shareable_profile_link: dict[str, str]
def __init__(self, hass: HomeAssistant, npsso: str) -> None:
"""Initialize the class with the npsso token."""
rate = Rate(300, Duration.MINUTE * 15)
self.psn = PSNAWP(npsso, rate_limit=rate)
self.client: Client
self.hass = hass
self.user: User
self.legacy_profile: dict[str, Any] | None = None
self.trophy_titles: list[TrophyTitle] = []
self._title_icon_urls: dict[str, str] = {}
self.friends_list: dict[str, User] = {}
def _setup(self) -> None:
"""Setup PSN."""
self.user = self.psn.user(online_id="me")
self.client = self.psn.me()
self.shareable_profile_link = self.client.get_shareable_profile_link()
self.trophy_titles = list(self.user.trophy_titles(page_size=500))
self.friends_list = {
friend.account_id: friend for friend in self.user.friends_list()
}
async def async_setup(self) -> None:
"""Setup PSN."""
await self.hass.async_add_executor_job(self._setup)
async def get_user(self) -> User:
"""Get the user object from the PlayStation Network."""
self.user = await self.hass.async_add_executor_job(
partial(self.psn.user, online_id="me")
)
return self.user
def retrieve_psn_data(self) -> PlaystationNetworkData:
"""Bundle api calls to retrieve data from the PlayStation Network."""
data = PlaystationNetworkData()
data.registered_platforms = {
PlatformType(device["deviceType"])
for device in self.client.get_account_devices()
} & SUPPORTED_PLATFORMS
data.presence = self.user.get_presence()
data.trophy_summary = self.client.trophy_summary()
data.profile = self.user.profile()
# check legacy platforms if owned
if LEGACY_PLATFORMS & data.registered_platforms:
self.legacy_profile = self.client.get_profile_legacy()
return data
async def get_data(self) -> PlaystationNetworkData:
"""Get title data from the PlayStation Network."""
data = await self.hass.async_add_executor_job(self.retrieve_psn_data)
data.username = self.user.online_id
data.account_id = self.user.account_id
data.shareable_profile_link = self.shareable_profile_link
if "platform" in data.presence["basicPresence"]["primaryPlatformInfo"]:
primary_platform = PlatformType(
data.presence["basicPresence"]["primaryPlatformInfo"]["platform"]
)
game_title_info: dict[str, Any] = next(
iter(
data.presence.get("basicPresence", {}).get("gameTitleInfoList", [])
),
{},
)
status = data.presence.get("basicPresence", {}).get("primaryPlatformInfo")[
"onlineStatus"
]
title_format = (
PlatformType(fmt) if (fmt := game_title_info.get("format")) else None
)
data.active_sessions[primary_platform] = SessionData(
platform=primary_platform,
status=status,
title_id=game_title_info.get("npTitleId"),
title_name=game_title_info.get("titleName"),
format=title_format,
media_image_url=(
game_title_info.get("conceptIconUrl")
or game_title_info.get("npTitleIconUrl")
),
)
if self.legacy_profile:
presence = self.legacy_profile["profile"].get("presences", [])
if (game_title_info := presence[0] if presence else {}) and game_title_info[
"onlineStatus"
] != "offline":
platform = PlatformType(game_title_info["platform"])
if platform is PlatformType.PS4:
media_image_url = game_title_info.get("npTitleIconUrl")
elif platform is PlatformType.PS3 and game_title_info.get("npTitleId"):
media_image_url = self.psn.game_title(
game_title_info["npTitleId"],
platform=PlatformType.PS3,
account_id="me",
np_communication_id="",
).get_title_icon_url()
elif platform is PlatformType.PS_VITA and game_title_info.get(
"npTitleId"
):
media_image_url = self.get_psvita_title_icon_url(game_title_info)
else:
media_image_url = None
data.active_sessions[platform] = SessionData(
platform=platform,
title_id=game_title_info.get("npTitleId"),
title_name=game_title_info.get("titleName"),
format=platform,
media_image_url=media_image_url,
status=game_title_info["onlineStatus"],
)
return data
def get_psvita_title_icon_url(self, game_title_info: dict[str, Any]) -> str | None:
"""Look up title_icon_url from trophy titles data."""
if url := self._title_icon_urls.get(game_title_info["npTitleId"]):
return url
url = next(
(
title.title_icon_url
for title in self.trophy_titles
if game_title_info["titleName"]
== normalize_title(title.title_name or "")
and next(iter(title.title_platform)) == PlatformType.PS_VITA
),
None,
)
if url is not None:
self._title_icon_urls[game_title_info["npTitleId"]] = url
return url
def normalize_title(name: str) -> str:
"""Normalize trophy title."""
return name.removesuffix("Trophies").removesuffix("Trophy Set").strip()
def get_game_title_info(presence: dict[str, Any]) -> dict[str, Any]:
"""Retrieve title info from presence."""
return (
next((title for title in game_title_info), {})
if (
game_title_info := presence.get("basicPresence", {}).get(
"gameTitleInfoList"
)
)
else {}
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/helpers.py",
"license": "Apache License 2.0",
"lines": 173,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/playstation_network/media_player.py | """Media player entity for the PlayStation Network Integration."""
import logging
from typing import TYPE_CHECKING
from psnawp_api.models.trophies import PlatformType
from homeassistant.components.media_player import (
MediaPlayerDeviceClass,
MediaPlayerEntity,
MediaPlayerState,
MediaType,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import (
PlaystationNetworkConfigEntry,
PlaystationNetworkTrophyTitlesCoordinator,
PlaystationNetworkUserDataCoordinator,
)
from .const import DOMAIN, SUPPORTED_PLATFORMS
_LOGGER = logging.getLogger(__name__)
PLATFORM_MAP = {
PlatformType.PS_VITA: "PlayStation Vita",
PlatformType.PS5: "PlayStation 5",
PlatformType.PS4: "PlayStation 4",
PlatformType.PS3: "PlayStation 3",
PlatformType.PSPC: "PlayStation PC",
}
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
config_entry: PlaystationNetworkConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Media Player Entity Setup."""
coordinator = config_entry.runtime_data.user_data
trophy_titles = config_entry.runtime_data.trophy_titles
devices_added: set[PlatformType] = set()
device_reg = dr.async_get(hass)
entities = []
@callback
def add_entities() -> None:
nonlocal devices_added
if not SUPPORTED_PLATFORMS - devices_added:
remove_listener()
new_platforms = (
set(coordinator.data.active_sessions.keys()) & SUPPORTED_PLATFORMS
) - devices_added
if new_platforms:
async_add_entities(
PsnMediaPlayerEntity(coordinator, platform_type, trophy_titles)
for platform_type in new_platforms
)
devices_added |= new_platforms
for platform in SUPPORTED_PLATFORMS:
if device_reg.async_get_device(
identifiers={
(DOMAIN, f"{coordinator.config_entry.unique_id}_{platform.value}")
}
):
entities.append(PsnMediaPlayerEntity(coordinator, platform, trophy_titles))
devices_added.add(platform)
if entities:
async_add_entities(entities)
remove_listener = coordinator.async_add_listener(add_entities)
add_entities()
class PsnMediaPlayerEntity(
CoordinatorEntity[PlaystationNetworkUserDataCoordinator], MediaPlayerEntity
):
"""Media player entity representing currently playing game."""
_attr_media_image_remotely_accessible = True
_attr_media_content_type = MediaType.GAME
_attr_device_class = MediaPlayerDeviceClass.RECEIVER
_attr_translation_key = "playstation"
_attr_has_entity_name = True
_attr_name = None
def __init__(
self,
coordinator: PlaystationNetworkUserDataCoordinator,
platform: PlatformType,
trophy_titles: PlaystationNetworkTrophyTitlesCoordinator,
) -> None:
"""Initialize PSN MediaPlayer."""
super().__init__(coordinator)
if TYPE_CHECKING:
assert coordinator.config_entry.unique_id
self._attr_unique_id = f"{coordinator.config_entry.unique_id}_{platform.value}"
self.key = platform
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self._attr_unique_id)},
name=PLATFORM_MAP[platform],
manufacturer="Sony Interactive Entertainment",
model=PLATFORM_MAP[platform],
via_device=(DOMAIN, coordinator.config_entry.unique_id),
)
self.trophy_titles = trophy_titles
@property
def state(self) -> MediaPlayerState:
"""Media Player state getter."""
session = self.coordinator.data.active_sessions.get(self.key)
if session:
if session.status == "online":
return (
MediaPlayerState.PLAYING
if session.title_id is not None
else MediaPlayerState.ON
)
return MediaPlayerState.OFF
@property
def media_title(self) -> str | None:
"""Media title getter."""
session = self.coordinator.data.active_sessions.get(self.key)
return session.title_name if session else None
@property
def media_content_id(self) -> str | None:
"""Content ID of current playing media."""
session = self.coordinator.data.active_sessions.get(self.key)
return session.title_id if session else None
@property
def media_image_url(self) -> str | None:
"""Media image url getter."""
session = self.coordinator.data.active_sessions.get(self.key)
return session.media_image_url if session else None
async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass."""
await super().async_added_to_hass()
if self.key is PlatformType.PS_VITA:
self.async_on_remove(
self.trophy_titles.async_add_listener(self._handle_coordinator_update)
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/media_player.py",
"license": "Apache License 2.0",
"lines": 131,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/playstation_network/sensor.py | """Sensor platform for PlayStation Network integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import PERCENTAGE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.util import dt as dt_util
from .coordinator import (
PlayStationNetworkBaseCoordinator,
PlaystationNetworkConfigEntry,
PlaystationNetworkData,
PlaystationNetworkFriendDataCoordinator,
PlaystationNetworkUserDataCoordinator,
)
from .entity import PlaystationNetworkServiceEntity
from .helpers import get_game_title_info
PARALLEL_UPDATES = 0
@dataclass(kw_only=True, frozen=True)
class PlaystationNetworkSensorEntityDescription(SensorEntityDescription):
"""PlayStation Network sensor description."""
value_fn: Callable[[PlaystationNetworkData], StateType | datetime]
available_fn: Callable[[PlaystationNetworkData], bool] = lambda _: True
class PlaystationNetworkSensor(StrEnum):
"""PlayStation Network sensors."""
TROPHY_LEVEL = "trophy_level"
TROPHY_LEVEL_PROGRESS = "trophy_level_progress"
EARNED_TROPHIES_PLATINUM = "earned_trophies_platinum"
EARNED_TROPHIES_GOLD = "earned_trophies_gold"
EARNED_TROPHIES_SILVER = "earned_trophies_silver"
EARNED_TROPHIES_BRONZE = "earned_trophies_bronze"
ONLINE_ID = "online_id"
LAST_ONLINE = "last_online"
ONLINE_STATUS = "online_status"
NOW_PLAYING = "now_playing"
SENSOR_DESCRIPTIONS: tuple[PlaystationNetworkSensorEntityDescription, ...] = (
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.TROPHY_LEVEL,
translation_key=PlaystationNetworkSensor.TROPHY_LEVEL,
value_fn=(
lambda psn: psn.trophy_summary.trophy_level if psn.trophy_summary else None
),
state_class=SensorStateClass.MEASUREMENT,
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.TROPHY_LEVEL_PROGRESS,
translation_key=PlaystationNetworkSensor.TROPHY_LEVEL_PROGRESS,
value_fn=(
lambda psn: psn.trophy_summary.progress if psn.trophy_summary else None
),
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.EARNED_TROPHIES_PLATINUM,
translation_key=PlaystationNetworkSensor.EARNED_TROPHIES_PLATINUM,
value_fn=(
lambda psn: (
psn.trophy_summary.earned_trophies.platinum
if psn.trophy_summary
else None
)
),
state_class=SensorStateClass.MEASUREMENT,
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.EARNED_TROPHIES_GOLD,
translation_key=PlaystationNetworkSensor.EARNED_TROPHIES_GOLD,
value_fn=(
lambda psn: (
psn.trophy_summary.earned_trophies.gold if psn.trophy_summary else None
)
),
state_class=SensorStateClass.MEASUREMENT,
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.EARNED_TROPHIES_SILVER,
translation_key=PlaystationNetworkSensor.EARNED_TROPHIES_SILVER,
value_fn=(
lambda psn: (
psn.trophy_summary.earned_trophies.silver
if psn.trophy_summary
else None
)
),
state_class=SensorStateClass.MEASUREMENT,
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.EARNED_TROPHIES_BRONZE,
translation_key=PlaystationNetworkSensor.EARNED_TROPHIES_BRONZE,
value_fn=(
lambda psn: (
psn.trophy_summary.earned_trophies.bronze
if psn.trophy_summary
else None
)
),
state_class=SensorStateClass.MEASUREMENT,
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.ONLINE_ID,
translation_key=PlaystationNetworkSensor.ONLINE_ID,
value_fn=lambda psn: psn.username,
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.LAST_ONLINE,
translation_key=PlaystationNetworkSensor.LAST_ONLINE,
value_fn=(
lambda psn: dt_util.parse_datetime(
psn.presence["basicPresence"]["lastAvailableDate"]
)
),
available_fn=lambda psn: "lastAvailableDate" in psn.presence["basicPresence"],
device_class=SensorDeviceClass.TIMESTAMP,
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.ONLINE_STATUS,
translation_key=PlaystationNetworkSensor.ONLINE_STATUS,
value_fn=(
lambda psn: (
psn.presence["basicPresence"]["availability"]
.lower()
.replace("unavailable", "offline")
)
),
device_class=SensorDeviceClass.ENUM,
options=["offline", "availabletoplay", "availabletocommunicate", "busy"],
),
PlaystationNetworkSensorEntityDescription(
key=PlaystationNetworkSensor.NOW_PLAYING,
translation_key=PlaystationNetworkSensor.NOW_PLAYING,
value_fn=lambda psn: get_game_title_info(psn.presence).get("titleName"),
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: PlaystationNetworkConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the sensor platform."""
coordinator = config_entry.runtime_data.user_data
async_add_entities(
PlaystationNetworkSensorEntity(coordinator, description)
for description in SENSOR_DESCRIPTIONS
)
for (
subentry_id,
friend_data_coordinator,
) in config_entry.runtime_data.friends.items():
async_add_entities(
[
PlaystationNetworkFriendSensorEntity(
friend_data_coordinator,
description,
config_entry.subentries[subentry_id],
)
for description in SENSOR_DESCRIPTIONS
],
config_subentry_id=subentry_id,
)
class PlaystationNetworkSensorBaseEntity(
PlaystationNetworkServiceEntity,
SensorEntity,
):
"""Base sensor entity."""
entity_description: PlaystationNetworkSensorEntityDescription
coordinator: PlayStationNetworkBaseCoordinator
@property
def native_value(self) -> StateType | datetime:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.coordinator.data)
@property
def entity_picture(self) -> str | None:
"""Return the entity picture to use in the frontend, if any."""
if self.entity_description.key is PlaystationNetworkSensor.ONLINE_ID and (
profile_pictures := self.coordinator.data.profile.get(
"personalDetail", {}
).get("profilePictures")
):
return next(
(pic.get("url") for pic in profile_pictures if pic.get("size") == "xl"),
None,
)
return super().entity_picture
@property
def available(self) -> bool:
"""Return True if entity is available."""
return super().available and self.entity_description.available_fn(
self.coordinator.data
)
class PlaystationNetworkSensorEntity(PlaystationNetworkSensorBaseEntity):
"""Representation of a PlayStation Network sensor entity."""
coordinator: PlaystationNetworkUserDataCoordinator
class PlaystationNetworkFriendSensorEntity(PlaystationNetworkSensorBaseEntity):
"""Representation of a PlayStation Network sensor entity."""
coordinator: PlaystationNetworkFriendDataCoordinator
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/sensor.py",
"license": "Apache License 2.0",
"lines": 205,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/qbus/cover.py | """Support for Qbus cover."""
from typing import Any
from qbusmqttapi.const import (
KEY_PROPERTIES_SHUTTER_POSITION,
KEY_PROPERTIES_SLAT_POSITION,
)
from qbusmqttapi.discovery import QbusMqttOutput
from qbusmqttapi.state import QbusMqttShutterState, StateType
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
CoverDeviceClass,
CoverEntity,
CoverEntityFeature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import QbusConfigEntry
from .entity import QbusEntity, create_new_entities
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: QbusConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up cover entities."""
coordinator = entry.runtime_data
added_outputs: list[QbusMqttOutput] = []
def _check_outputs() -> None:
entities = create_new_entities(
coordinator,
added_outputs,
lambda output: output.type == "shutter",
QbusCover,
)
async_add_entities(entities)
_check_outputs()
entry.async_on_unload(coordinator.async_add_listener(_check_outputs))
class QbusCover(QbusEntity, CoverEntity):
"""Representation of a Qbus cover entity."""
_state_cls = QbusMqttShutterState
_attr_name = None
_attr_supported_features: CoverEntityFeature
_attr_device_class = CoverDeviceClass.BLIND
def __init__(self, mqtt_output: QbusMqttOutput) -> None:
"""Initialize cover entity."""
super().__init__(mqtt_output)
self._attr_assumed_state = False
self._attr_current_cover_position = 0
self._attr_current_cover_tilt_position = 0
self._attr_is_closed = True
self._attr_supported_features = (
CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE
)
if "shutterStop" in mqtt_output.actions:
self._attr_supported_features |= CoverEntityFeature.STOP
self._attr_assumed_state = True
if KEY_PROPERTIES_SHUTTER_POSITION in mqtt_output.properties:
self._attr_supported_features |= CoverEntityFeature.SET_POSITION
if KEY_PROPERTIES_SLAT_POSITION in mqtt_output.properties:
self._attr_supported_features |= CoverEntityFeature.SET_TILT_POSITION
self._attr_supported_features |= CoverEntityFeature.OPEN_TILT
self._attr_supported_features |= CoverEntityFeature.CLOSE_TILT
self._target_shutter_position: int | None = None
self._target_slat_position: int | None = None
self._target_state: str | None = None
self._previous_state: str | None = None
async def async_open_cover(self, **kwargs: Any) -> None:
"""Open the cover."""
state = QbusMqttShutterState(id=self._mqtt_output.id, type=StateType.STATE)
if self._attr_supported_features & CoverEntityFeature.SET_POSITION:
state.write_position(100)
else:
state.write_state("up")
await self._async_publish_output_state(state)
async def async_close_cover(self, **kwargs: Any) -> None:
"""Close the cover."""
state = QbusMqttShutterState(id=self._mqtt_output.id, type=StateType.STATE)
if self._attr_supported_features & CoverEntityFeature.SET_POSITION:
state.write_position(0)
if self._attr_supported_features & CoverEntityFeature.SET_TILT_POSITION:
state.write_slat_position(0)
else:
state.write_state("down")
await self._async_publish_output_state(state)
async def async_stop_cover(self, **kwargs: Any) -> None:
"""Stop the cover."""
state = QbusMqttShutterState(id=self._mqtt_output.id, type=StateType.STATE)
state.write_state("stop")
await self._async_publish_output_state(state)
async def async_set_cover_position(self, **kwargs: Any) -> None:
"""Move the cover to a specific position."""
state = QbusMqttShutterState(id=self._mqtt_output.id, type=StateType.STATE)
state.write_position(int(kwargs[ATTR_POSITION]))
await self._async_publish_output_state(state)
async def async_open_cover_tilt(self, **kwargs: Any) -> None:
"""Open the cover tilt."""
state = QbusMqttShutterState(id=self._mqtt_output.id, type=StateType.STATE)
state.write_slat_position(50)
await self._async_publish_output_state(state)
async def async_close_cover_tilt(self, **kwargs: Any) -> None:
"""Close the cover tilt."""
state = QbusMqttShutterState(id=self._mqtt_output.id, type=StateType.STATE)
state.write_slat_position(0)
await self._async_publish_output_state(state)
async def async_set_cover_tilt_position(self, **kwargs: Any) -> None:
"""Move the cover tilt to a specific position."""
state = QbusMqttShutterState(id=self._mqtt_output.id, type=StateType.STATE)
state.write_slat_position(int(kwargs[ATTR_TILT_POSITION]))
await self._async_publish_output_state(state)
async def _handle_state_received(self, state: QbusMqttShutterState) -> None:
output_state = state.read_state()
shutter_position = state.read_position()
slat_position = state.read_slat_position()
if output_state is not None:
self._previous_state = self._target_state
self._target_state = output_state
if shutter_position is not None:
self._target_shutter_position = shutter_position
if slat_position is not None:
self._target_slat_position = slat_position
self._update_is_closed()
self._update_cover_position()
self._update_tilt_position()
def _update_is_closed(self) -> None:
if self._attr_supported_features & CoverEntityFeature.SET_POSITION:
if self._attr_supported_features & CoverEntityFeature.SET_TILT_POSITION:
self._attr_is_closed = (
self._target_shutter_position == 0
and self._target_slat_position in (0, 100)
)
else:
self._attr_is_closed = self._target_shutter_position == 0
else:
self._attr_is_closed = (
self._previous_state == "down" and self._target_state == "stop"
)
def _update_cover_position(self) -> None:
self._attr_current_cover_position = (
self._target_shutter_position
if self._attr_supported_features & CoverEntityFeature.SET_POSITION
else None
)
def _update_tilt_position(self) -> None:
self._attr_current_cover_tilt_position = (
self._target_slat_position
if self._attr_supported_features & CoverEntityFeature.SET_TILT_POSITION
else None
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/qbus/cover.py",
"license": "Apache License 2.0",
"lines": 149,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/russound_rio/number.py | """Support for Russound number entities."""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from aiorussound.rio import Controller, ZoneControlSurface
from homeassistant.components.number import NumberEntity, NumberEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import RussoundConfigEntry
from .entity import RussoundBaseEntity, command
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class RussoundZoneNumberEntityDescription(NumberEntityDescription):
"""Describes Russound number entities."""
value_fn: Callable[[ZoneControlSurface], float]
set_value_fn: Callable[[ZoneControlSurface, float], Awaitable[None]]
CONTROL_ENTITIES: tuple[RussoundZoneNumberEntityDescription, ...] = (
RussoundZoneNumberEntityDescription(
key="balance",
translation_key="balance",
native_min_value=-10,
native_max_value=10,
native_step=1,
entity_category=EntityCategory.CONFIG,
value_fn=lambda zone: zone.balance,
set_value_fn=lambda zone, value: zone.set_balance(int(value)),
),
RussoundZoneNumberEntityDescription(
key="bass",
translation_key="bass",
native_min_value=-10,
native_max_value=10,
native_step=1,
entity_category=EntityCategory.CONFIG,
value_fn=lambda zone: zone.bass,
set_value_fn=lambda zone, value: zone.set_bass(int(value)),
),
RussoundZoneNumberEntityDescription(
key="treble",
translation_key="treble",
native_min_value=-10,
native_max_value=10,
native_step=1,
entity_category=EntityCategory.CONFIG,
value_fn=lambda zone: zone.treble,
set_value_fn=lambda zone, value: zone.set_treble(int(value)),
),
RussoundZoneNumberEntityDescription(
key="turn_on_volume",
translation_key="turn_on_volume",
native_min_value=0,
native_max_value=100,
native_step=2,
entity_category=EntityCategory.CONFIG,
value_fn=lambda zone: zone.turn_on_volume * 2,
set_value_fn=lambda zone, value: zone.set_turn_on_volume(int(value / 2)),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: RussoundConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Russound number entities based on a config entry."""
client = entry.runtime_data
async_add_entities(
RussoundNumberEntity(controller, zone_id, description)
for controller in client.controllers.values()
for zone_id in controller.zones
for description in CONTROL_ENTITIES
)
class RussoundNumberEntity(RussoundBaseEntity, NumberEntity):
"""Defines a Russound number entity."""
entity_description: RussoundZoneNumberEntityDescription
def __init__(
self,
controller: Controller,
zone_id: int,
description: RussoundZoneNumberEntityDescription,
) -> None:
"""Initialize a Russound number entity."""
super().__init__(controller, zone_id)
self.entity_description = description
self._attr_unique_id = (
f"{self._primary_mac_address}-{self._zone.device_str}-{description.key}"
)
@property
def native_value(self) -> float:
"""Return the native value of the entity."""
return float(self.entity_description.value_fn(self._zone))
@command
async def async_set_native_value(self, value: float) -> None:
"""Set the value."""
await self.entity_description.set_value_fn(self._zone, value)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/russound_rio/number.py",
"license": "Apache License 2.0",
"lines": 94,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/russound_rio/switch.py | """Support for Russound RIO switch entities."""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any
from aiorussound.rio import Controller, ZoneControlSurface
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import RussoundConfigEntry
from .entity import RussoundBaseEntity, command
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class RussoundZoneSwitchEntityDescription(SwitchEntityDescription):
"""Describes Russound RIO switch entity description."""
value_fn: Callable[[ZoneControlSurface], bool]
set_value_fn: Callable[[ZoneControlSurface, bool], Awaitable[None]]
CONTROL_ENTITIES: tuple[RussoundZoneSwitchEntityDescription, ...] = (
RussoundZoneSwitchEntityDescription(
key="loudness",
translation_key="loudness",
entity_category=EntityCategory.CONFIG,
value_fn=lambda zone: zone.loudness,
set_value_fn=lambda zone, value: zone.set_loudness(value),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: RussoundConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Russound RIO switch entities based on a config entry."""
client = entry.runtime_data
async_add_entities(
RussoundSwitchEntity(controller, zone_id, description)
for controller in client.controllers.values()
for zone_id in controller.zones
for description in CONTROL_ENTITIES
)
class RussoundSwitchEntity(RussoundBaseEntity, SwitchEntity):
"""Defines a Russound RIO switch entity."""
entity_description: RussoundZoneSwitchEntityDescription
def __init__(
self,
controller: Controller,
zone_id: int,
description: RussoundZoneSwitchEntityDescription,
) -> None:
"""Initialize Russound RIO switch."""
super().__init__(controller, zone_id)
self.entity_description = description
self._attr_unique_id = (
f"{self._primary_mac_address}-{self._zone.device_str}-{description.key}"
)
@property
def is_on(self) -> bool:
"""Return the state of the switch."""
return self.entity_description.value_fn(self._zone)
@command
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
await self.entity_description.set_value_fn(self._zone, True)
@command
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
await self.entity_description.set_value_fn(self._zone, False)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/russound_rio/switch.py",
"license": "Apache License 2.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/smarla/number.py | """Support for the Swing2Sleep Smarla number entities."""
from dataclasses import dataclass
from pysmarlaapi.federwiege.services.classes import Property
from homeassistant.components.number import (
NumberEntity,
NumberEntityDescription,
NumberMode,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import FederwiegeConfigEntry
from .entity import SmarlaBaseEntity, SmarlaEntityDescription
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class SmarlaNumberEntityDescription(SmarlaEntityDescription, NumberEntityDescription):
"""Class describing Swing2Sleep Smarla number entities."""
NUMBERS: list[SmarlaNumberEntityDescription] = [
SmarlaNumberEntityDescription(
key="intensity",
translation_key="intensity",
service="babywiege",
property="intensity",
native_max_value=100,
native_min_value=0,
native_step=1,
mode=NumberMode.SLIDER,
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: FederwiegeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Smarla numbers from config entry."""
federwiege = config_entry.runtime_data
async_add_entities(SmarlaNumber(federwiege, desc) for desc in NUMBERS)
class SmarlaNumber(SmarlaBaseEntity, NumberEntity):
"""Representation of Smarla number."""
entity_description: SmarlaNumberEntityDescription
_property: Property[int]
@property
def native_value(self) -> float | None:
"""Return the entity value to represent the entity state."""
v = self._property.get()
return float(v) if v is not None else None
def set_native_value(self, value: float) -> None:
"""Update to the smarla device."""
self._property.set(int(value))
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smarla/number.py",
"license": "Apache License 2.0",
"lines": 48,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sun/binary_sensor.py | """Binary Sensor platform for Sun integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from homeassistant.components.binary_sensor import (
DOMAIN as BINARY_SENSOR_DOMAIN,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN, SIGNAL_EVENTS_CHANGED
from .entity import Sun, SunConfigEntry
ENTITY_ID_BINARY_SENSOR_FORMAT = BINARY_SENSOR_DOMAIN + ".sun_{}"
@dataclass(kw_only=True, frozen=True)
class SunBinarySensorEntityDescription(BinarySensorEntityDescription):
"""Describes a Sun binary sensor entity."""
value_fn: Callable[[Sun], bool | None]
signal: str
BINARY_SENSOR_TYPES: tuple[SunBinarySensorEntityDescription, ...] = (
SunBinarySensorEntityDescription(
key="solar_rising",
translation_key="solar_rising",
value_fn=lambda data: data.rising,
entity_registry_enabled_default=False,
signal=SIGNAL_EVENTS_CHANGED,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: SunConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Sun binary sensor platform."""
sun = entry.runtime_data
async_add_entities(
[
SunBinarySensor(sun, description, entry.entry_id)
for description in BINARY_SENSOR_TYPES
]
)
class SunBinarySensor(BinarySensorEntity):
"""Representation of a Sun binary sensor."""
_attr_has_entity_name = True
_attr_should_poll = False
_attr_entity_category = EntityCategory.DIAGNOSTIC
entity_description: SunBinarySensorEntityDescription
def __init__(
self,
sun: Sun,
entity_description: SunBinarySensorEntityDescription,
entry_id: str,
) -> None:
"""Initiate Sun Binary Sensor."""
self.entity_description = entity_description
self.entity_id = ENTITY_ID_BINARY_SENSOR_FORMAT.format(entity_description.key)
self._attr_unique_id = f"{entry_id}-{entity_description.key}"
self.sun = sun
self._attr_device_info = DeviceInfo(
name="Sun",
identifiers={(DOMAIN, entry_id)},
entry_type=DeviceEntryType.SERVICE,
)
@property
def is_on(self) -> bool | None:
"""Return value of binary sensor."""
return self.entity_description.value_fn(self.sun)
async def async_added_to_hass(self) -> None:
"""Register signal listener when added to hass."""
await super().async_added_to_hass()
self.async_on_remove(
async_dispatcher_connect(
self.hass,
self.entity_description.signal,
self.async_write_ha_state,
)
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sun/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/synology_dsm/services.py | """The Synology DSM component."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, cast
from synology_dsm.exceptions import SynologyDSMException
from homeassistant.core import HomeAssistant, ServiceCall, callback
from .const import CONF_SERIAL, DOMAIN, SERVICE_REBOOT, SERVICE_SHUTDOWN, SERVICES
from .coordinator import SynologyDSMConfigEntry
LOGGER = logging.getLogger(__name__)
async def _service_handler(call: ServiceCall) -> None:
"""Handle service call."""
serial: str | None = call.data.get(CONF_SERIAL)
entries: list[SynologyDSMConfigEntry] = (
call.hass.config_entries.async_loaded_entries(DOMAIN)
)
dsm_devices = {cast(str, entry.unique_id): entry.runtime_data for entry in entries}
if serial:
entry: SynologyDSMConfigEntry | None = (
call.hass.config_entries.async_entry_for_domain_unique_id(DOMAIN, serial)
)
if TYPE_CHECKING:
assert entry
dsm_device = entry.runtime_data
elif len(dsm_devices) == 1:
dsm_device = next(iter(dsm_devices.values()))
serial = next(iter(dsm_devices))
else:
LOGGER.error(
"More than one DSM configured, must specify one of serials %s",
sorted(dsm_devices),
)
return
if not dsm_device:
LOGGER.error("DSM with specified serial %s not found", serial)
return
if call.service in [SERVICE_REBOOT, SERVICE_SHUTDOWN]:
if serial not in dsm_devices:
LOGGER.error("DSM with specified serial %s not found", serial)
return
LOGGER.debug("%s DSM with serial %s", call.service, serial)
LOGGER.warning(
(
"The %s service is deprecated and will be removed in future"
" release. Please use the corresponding button entity"
),
call.service,
)
dsm_device = dsm_devices[serial]
dsm_api = dsm_device.api
try:
await getattr(dsm_api, f"async_{call.service}")()
except SynologyDSMException as ex:
LOGGER.error(
"%s of DSM with serial %s not possible, because of %s",
call.service,
serial,
ex,
)
return
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Service handler setup."""
for service in SERVICES:
hass.services.async_register(DOMAIN, service, _service_handler)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/synology_dsm/services.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/telegram_bot/bot.py | """Telegram bot classes and utilities."""
from abc import abstractmethod
import asyncio
from collections.abc import Awaitable, Callable, Sequence
import io
import logging
import os
from pathlib import Path
from ssl import SSLContext
from types import MappingProxyType
from typing import Any, cast
import httpx
from telegram import (
Bot,
CallbackQuery,
File,
InlineKeyboardButton,
InlineKeyboardMarkup,
InputMedia,
InputMediaAnimation,
InputMediaAudio,
InputMediaDocument,
InputMediaPhoto,
InputMediaVideo,
InputPollOption,
Message,
PhotoSize,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
Update,
User,
)
from telegram.constants import InputMediaType, ParseMode
from telegram.error import TelegramError
from telegram.ext import CallbackContext, filters
from telegram.request import HTTPXRequest
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_COMMAND,
CONF_API_KEY,
HTTP_BASIC_AUTHENTICATION,
HTTP_BEARER_AUTHENTICATION,
HTTP_DIGEST_AUTHENTICATION,
)
from homeassistant.core import Context, HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.util.json import JsonValueType
from homeassistant.util.ssl import get_default_context, get_default_no_verify_context
from .const import (
ATTR_ARGS,
ATTR_AUTHENTICATION,
ATTR_CAPTION,
ATTR_CHAT_ID,
ATTR_CHAT_INSTANCE,
ATTR_DATA,
ATTR_DATE,
ATTR_DISABLE_NOTIF,
ATTR_DISABLE_WEB_PREV,
ATTR_FILE,
ATTR_FILE_ID,
ATTR_FILE_MIME_TYPE,
ATTR_FILE_NAME,
ATTR_FILE_PATH,
ATTR_FILE_SIZE,
ATTR_FROM_FIRST,
ATTR_FROM_LAST,
ATTR_INLINE_MESSAGE_ID,
ATTR_KEYBOARD,
ATTR_KEYBOARD_INLINE,
ATTR_MESSAGE,
ATTR_MESSAGE_ID,
ATTR_MESSAGE_TAG,
ATTR_MESSAGE_THREAD_ID,
ATTR_MSG,
ATTR_MSGID,
ATTR_ONE_TIME_KEYBOARD,
ATTR_OPEN_PERIOD,
ATTR_PARSER,
ATTR_PASSWORD,
ATTR_REPLY_TO_MSGID,
ATTR_REPLYMARKUP,
ATTR_RESIZE_KEYBOARD,
ATTR_STICKER_ID,
ATTR_TEXT,
ATTR_TIMEOUT,
ATTR_TITLE,
ATTR_URL,
ATTR_USER_ID,
ATTR_USERNAME,
ATTR_VERIFY_SSL,
CONF_API_ENDPOINT,
CONF_CHAT_ID,
CONF_PROXY_URL,
DEFAULT_TIMEOUT_SECONDS,
DOMAIN,
EVENT_TELEGRAM_ATTACHMENT,
EVENT_TELEGRAM_CALLBACK,
EVENT_TELEGRAM_COMMAND,
EVENT_TELEGRAM_SENT,
EVENT_TELEGRAM_TEXT,
PARSER_HTML,
PARSER_MD,
PARSER_MD2,
PARSER_PLAIN_TEXT,
SERVICE_EDIT_CAPTION,
SERVICE_EDIT_MESSAGE,
SERVICE_SEND_DOCUMENT,
SERVICE_SEND_PHOTO,
SERVICE_SEND_STICKER,
SERVICE_SEND_VIDEO,
SERVICE_SEND_VOICE,
)
from .helpers import signal
_FILE_TYPES = ("animation", "document", "photo", "sticker", "video", "voice")
_LOGGER = logging.getLogger(__name__)
type TelegramBotConfigEntry = ConfigEntry[TelegramNotificationService]
def _get_bot_info(bot: Bot, config_entry: ConfigEntry) -> dict[str, Any]:
return {
"config_entry_id": config_entry.entry_id,
"id": bot.id,
"first_name": bot.first_name,
"last_name": bot.last_name,
"username": bot.username,
}
class BaseTelegramBot:
"""The base class for the telegram bot."""
def __init__(
self, hass: HomeAssistant, config: TelegramBotConfigEntry, bot: Bot
) -> None:
"""Initialize the bot base class."""
self.hass = hass
self.config = config
self._bot = bot
@abstractmethod
async def shutdown(self) -> None:
"""Shutdown the bot application."""
async def handle_update(self, update: Update, context: CallbackContext) -> bool:
"""Handle updates from bot application set up by the respective platform."""
_LOGGER.debug("Handling update %s", update)
if not self.authorize_update(update):
return False
# establish event type: text, command or callback_query
if update.callback_query:
# NOTE: Check for callback query first since effective message will be populated with the message
# in .callback_query (python-telegram-bot docs are wrong)
event_type, event_data = self._get_callback_query_event_data(
update.callback_query
)
elif update.effective_message:
event_type, event_data = self._get_message_event_data(
update.effective_message
)
else:
_LOGGER.warning("Unhandled update: %s", update)
return True
event_data["bot"] = _get_bot_info(self._bot, self.config)
event_context = Context()
_LOGGER.debug("Firing event %s: %s", event_type, event_data)
self.hass.bus.async_fire(event_type, event_data, context=event_context)
async_dispatcher_send(self.hass, signal(self._bot), event_type, event_data)
return True
@staticmethod
def _get_command_event_data(command_text: str | None) -> dict[str, str | list]:
if not command_text or not command_text.startswith("/"):
return {}
command_parts = command_text.split()
command = command_parts[0]
args = command_parts[1:]
return {ATTR_COMMAND: command, ATTR_ARGS: args}
def _get_message_event_data(self, message: Message) -> tuple[str, dict[str, Any]]:
event_data: dict[str, Any] = {
ATTR_MSGID: message.message_id,
ATTR_CHAT_ID: message.chat.id,
ATTR_DATE: message.date,
ATTR_MESSAGE_THREAD_ID: message.message_thread_id,
}
if filters.COMMAND.filter(message):
# This is a command message - set event type to command and split data into command and args
event_type = EVENT_TELEGRAM_COMMAND
event_data.update(self._get_command_event_data(message.text))
elif filters.ATTACHMENT.filter(message):
event_type = EVENT_TELEGRAM_ATTACHMENT
event_data[ATTR_TEXT] = message.caption
event_data.update(self._get_file_id_event_data(message))
else:
event_type = EVENT_TELEGRAM_TEXT
event_data[ATTR_TEXT] = message.text
if message.from_user:
event_data.update(self._get_user_event_data(message.from_user))
return event_type, event_data
def _get_file_id_event_data(self, message: Message) -> dict[str, Any]:
"""Extract file_id from a message attachment, if any."""
if filters.PHOTO.filter(message):
photos = cast(Sequence[PhotoSize], message.effective_attachment)
return {
ATTR_FILE_ID: photos[-1].file_id,
ATTR_FILE_MIME_TYPE: "image/jpeg", # telegram always uses jpeg for photos
ATTR_FILE_SIZE: photos[-1].file_size,
}
return {
k: getattr(message.effective_attachment, v)
for k, v in (
(ATTR_FILE_ID, "file_id"),
(ATTR_FILE_NAME, "file_name"),
(ATTR_FILE_MIME_TYPE, "mime_type"),
(ATTR_FILE_SIZE, "file_size"),
)
if hasattr(message.effective_attachment, v)
}
def _get_user_event_data(self, user: User) -> dict[str, Any]:
return {
ATTR_USER_ID: user.id,
ATTR_FROM_FIRST: user.first_name,
ATTR_FROM_LAST: user.last_name,
}
def _get_callback_query_event_data(
self, callback_query: CallbackQuery
) -> tuple[str, dict[str, Any]]:
event_type = EVENT_TELEGRAM_CALLBACK
event_data: dict[str, Any] = {
ATTR_MSGID: callback_query.id,
ATTR_CHAT_INSTANCE: callback_query.chat_instance,
ATTR_DATA: callback_query.data,
ATTR_MSG: None,
ATTR_CHAT_ID: None,
}
if callback_query.message:
event_data[ATTR_MSG] = callback_query.message.to_dict()
event_data[ATTR_CHAT_ID] = callback_query.message.chat.id
if callback_query.from_user:
event_data.update(self._get_user_event_data(callback_query.from_user))
# Split data into command and args if possible
event_data.update(self._get_command_event_data(callback_query.data))
return event_type, event_data
def authorize_update(self, update: Update) -> bool:
"""Make sure either user or chat is in allowed_chat_ids."""
from_user = update.effective_user.id if update.effective_user else None
from_chat = update.effective_chat.id if update.effective_chat else None
allowed_chat_ids: list[int] = [
subentry.data[CONF_CHAT_ID] for subentry in self.config.subentries.values()
]
if from_user in allowed_chat_ids or from_chat in allowed_chat_ids:
return True
_LOGGER.error(
(
"Unauthorized update - neither user id %s nor chat id %s is in allowed"
" chats: %s"
),
from_user,
from_chat,
allowed_chat_ids,
)
return False
class TelegramNotificationService:
"""Implement the notification services for the Telegram Bot domain."""
def __init__(
self,
hass: HomeAssistant,
app: BaseTelegramBot | None,
bot: Bot,
config: TelegramBotConfigEntry,
parser: str,
) -> None:
"""Initialize the service."""
self.app = app
self.config = config
self._parsers: dict[str, str | None] = {
PARSER_HTML: ParseMode.HTML,
PARSER_MD: ParseMode.MARKDOWN,
PARSER_MD2: ParseMode.MARKDOWN_V2,
PARSER_PLAIN_TEXT: None,
}
self.parse_mode = self._parsers[parser]
self.bot = bot
self.hass = hass
self._last_message_id: dict[int, int] = {}
def _get_msg_ids(
self, msg_data: dict[str, Any], chat_id: int
) -> tuple[Any | None, int | None]:
"""Get the message id to edit.
This can be one of (message_id, inline_message_id) from a msg dict,
returning a tuple.
**You can use 'last' as message_id** to edit
the message last sent in the chat_id.
"""
message_id: Any | None = None
inline_message_id: int | None = None
if ATTR_MESSAGE_ID in msg_data:
message_id = msg_data[ATTR_MESSAGE_ID]
if (
isinstance(message_id, str)
and (message_id == "last")
and (chat_id in self._last_message_id)
):
message_id = self._last_message_id[chat_id]
else:
inline_message_id = msg_data[ATTR_INLINE_MESSAGE_ID]
return message_id, inline_message_id
def _get_msg_kwargs(self, data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters in message data kwargs."""
def _make_row_inline_keyboard(row_keyboard: Any) -> list[InlineKeyboardButton]:
"""Make a list of InlineKeyboardButtons.
It can accept:
- a list of tuples like:
`[(text_b1, data_callback_b1),
(text_b2, data_callback_b2), ...]
- a string like: `/cmd1, /cmd2, /cmd3`
- or a string like: `text_b1:/cmd1, text_b2:/cmd2`
- also supports urls instead of callback commands
"""
buttons = []
if isinstance(row_keyboard, str):
for key in row_keyboard.split(","):
if ":/" in key:
# check if command or URL
if "https://" in key:
label = key.split(":")[0]
url = key[len(label) + 1 :]
buttons.append(InlineKeyboardButton(label, url=url))
else:
# commands like: 'Label:/cmd' become ('Label', '/cmd')
label = key.split(":/")[0]
command = key[len(label) + 1 :]
buttons.append(
InlineKeyboardButton(label, callback_data=command)
)
else:
# commands like: '/cmd' become ('CMD', '/cmd')
label = key.strip()[1:].upper()
buttons.append(InlineKeyboardButton(label, callback_data=key))
elif isinstance(row_keyboard, list):
for entry in row_keyboard:
text_btn, data_btn = entry
if data_btn.startswith("https://"):
buttons.append(InlineKeyboardButton(text_btn, url=data_btn))
else:
buttons.append(
InlineKeyboardButton(text_btn, callback_data=data_btn)
)
else:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_inline_keyboard",
)
return buttons
# Defaults
params: dict[str, Any] = {
ATTR_PARSER: self.parse_mode,
ATTR_DISABLE_NOTIF: False,
ATTR_DISABLE_WEB_PREV: None,
ATTR_REPLY_TO_MSGID: None,
ATTR_REPLYMARKUP: None,
ATTR_TIMEOUT: None,
ATTR_MESSAGE_TAG: None,
ATTR_MESSAGE_THREAD_ID: None,
}
if data is not None:
if ATTR_PARSER in data:
params[ATTR_PARSER] = data[ATTR_PARSER]
if ATTR_TIMEOUT in data:
params[ATTR_TIMEOUT] = data[ATTR_TIMEOUT]
if ATTR_DISABLE_NOTIF in data:
params[ATTR_DISABLE_NOTIF] = data[ATTR_DISABLE_NOTIF]
if ATTR_DISABLE_WEB_PREV in data:
params[ATTR_DISABLE_WEB_PREV] = data[ATTR_DISABLE_WEB_PREV]
if ATTR_REPLY_TO_MSGID in data:
params[ATTR_REPLY_TO_MSGID] = data[ATTR_REPLY_TO_MSGID]
if ATTR_MESSAGE_TAG in data:
params[ATTR_MESSAGE_TAG] = data[ATTR_MESSAGE_TAG]
if ATTR_MESSAGE_THREAD_ID in data:
params[ATTR_MESSAGE_THREAD_ID] = data[ATTR_MESSAGE_THREAD_ID]
# Keyboards:
if ATTR_KEYBOARD in data:
keys = data[ATTR_KEYBOARD]
keys = keys if isinstance(keys, list) else [keys]
if keys:
params[ATTR_REPLYMARKUP] = ReplyKeyboardMarkup(
[[key.strip() for key in row.split(",")] for row in keys],
resize_keyboard=data.get(ATTR_RESIZE_KEYBOARD, False),
one_time_keyboard=data.get(ATTR_ONE_TIME_KEYBOARD, False),
)
else:
params[ATTR_REPLYMARKUP] = ReplyKeyboardRemove(True)
elif ATTR_KEYBOARD_INLINE in data:
keys = data.get(ATTR_KEYBOARD_INLINE)
keys = keys if isinstance(keys, list) else [keys]
params[ATTR_REPLYMARKUP] = InlineKeyboardMarkup(
[_make_row_inline_keyboard(row) for row in keys]
)
if params[ATTR_PARSER] == PARSER_PLAIN_TEXT:
params[ATTR_PARSER] = None
return params
async def _send_msg_formatted(
self,
func_send: Callable[..., Awaitable[Message]],
message_tag: str | None,
*args_msg: Any,
context: Context | None = None,
**kwargs_msg: Any,
) -> dict[str, JsonValueType]:
"""Sends a message and formats the response.
:return: dict with chat_id keys and message_id values for successful sends
"""
chat_id: int = kwargs_msg.pop(ATTR_CHAT_ID)
_LOGGER.debug("%s to chat ID %s", func_send.__name__, chat_id)
response: Message = await self._send_msg(
func_send,
message_tag,
chat_id,
*args_msg,
context=context,
**kwargs_msg,
)
return {str(chat_id): response.id}
async def _send_msg(
self,
func_send: Callable[..., Awaitable[Any]],
message_tag: str | None,
*args_msg: Any,
context: Context | None = None,
**kwargs_msg: Any,
) -> Any:
"""Send one message."""
out = await func_send(*args_msg, **kwargs_msg)
if isinstance(out, Message):
chat_id = out.chat_id
message_id = out.message_id
self._last_message_id[chat_id] = message_id
_LOGGER.debug(
"Last message ID: %s (from chat_id %s)",
self._last_message_id,
chat_id,
)
event_data: dict[str, Any] = {
ATTR_CHAT_ID: chat_id,
ATTR_MESSAGE_ID: message_id,
}
if message_tag is not None:
event_data[ATTR_MESSAGE_TAG] = message_tag
if kwargs_msg.get(ATTR_MESSAGE_THREAD_ID) is not None:
event_data[ATTR_MESSAGE_THREAD_ID] = kwargs_msg[ATTR_MESSAGE_THREAD_ID]
event_data["bot"] = _get_bot_info(self.bot, self.config)
self.hass.bus.async_fire(EVENT_TELEGRAM_SENT, event_data, context=context)
async_dispatcher_send(
self.hass, signal(self.bot), EVENT_TELEGRAM_SENT, event_data
)
return out
async def send_message(
self,
message: str,
chat_id: int,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> dict[str, JsonValueType]:
"""Send a message to one or multiple pre-allowed chat IDs."""
title = kwargs.get(ATTR_TITLE)
text = f"{title}\n{message}" if title else message
params = self._get_msg_kwargs(kwargs)
return await self._send_msg_formatted(
self.bot.send_message,
params[ATTR_MESSAGE_TAG],
text,
chat_id=chat_id,
parse_mode=params[ATTR_PARSER],
disable_web_page_preview=params[ATTR_DISABLE_WEB_PREV],
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
async def delete_message(
self,
chat_id: int,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> bool:
"""Delete a previously sent message."""
message_id, _ = self._get_msg_ids(kwargs, chat_id)
_LOGGER.debug("Delete message %s in chat ID %s", message_id, chat_id)
deleted: bool = await self._send_msg(
self.bot.delete_message,
None,
chat_id,
message_id,
context=context,
)
# reduce message_id anyway:
if chat_id in self._last_message_id:
# change last msg_id for deque(n_msgs)?
self._last_message_id[chat_id] -= 1
return deleted
async def edit_message_media(
self,
media_type: str,
chat_id: int,
context: Context | None = None,
**kwargs: Any,
) -> Any:
"Edit message media of a previously sent message."
message_id, inline_message_id = self._get_msg_ids(kwargs, chat_id)
params = self._get_msg_kwargs(kwargs)
_LOGGER.debug(
"Edit message media %s in chat ID %s with params: %s",
message_id or inline_message_id,
chat_id,
params,
)
file_content = await load_data(
self.hass,
url=kwargs.get(ATTR_URL),
filepath=kwargs.get(ATTR_FILE),
username=kwargs.get(ATTR_USERNAME, ""),
password=kwargs.get(ATTR_PASSWORD, ""),
authentication=kwargs.get(ATTR_AUTHENTICATION),
verify_ssl=(
get_default_context()
if kwargs.get(ATTR_VERIFY_SSL, False)
else get_default_no_verify_context()
),
)
media: InputMedia
if media_type == InputMediaType.ANIMATION:
media = InputMediaAnimation(
file_content,
caption=kwargs.get(ATTR_CAPTION),
parse_mode=params[ATTR_PARSER],
)
elif media_type == InputMediaType.AUDIO:
media = InputMediaAudio(
file_content,
caption=kwargs.get(ATTR_CAPTION),
parse_mode=params[ATTR_PARSER],
)
elif media_type == InputMediaType.DOCUMENT:
media = InputMediaDocument(
file_content,
caption=kwargs.get(ATTR_CAPTION),
parse_mode=params[ATTR_PARSER],
)
elif media_type == InputMediaType.PHOTO:
media = InputMediaPhoto(
file_content,
caption=kwargs.get(ATTR_CAPTION),
parse_mode=params[ATTR_PARSER],
)
else:
media = InputMediaVideo(
file_content,
caption=kwargs.get(ATTR_CAPTION),
parse_mode=params[ATTR_PARSER],
)
return await self._send_msg(
self.bot.edit_message_media,
params[ATTR_MESSAGE_TAG],
media=media,
chat_id=chat_id,
message_id=message_id,
inline_message_id=inline_message_id,
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
context=context,
)
async def edit_message(
self,
type_edit: str,
chat_id: int,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> Any:
"""Edit a previously sent message."""
message_id, inline_message_id = self._get_msg_ids(kwargs, chat_id)
params = self._get_msg_kwargs(kwargs)
_LOGGER.debug(
"Edit message %s in chat ID %s with params: %s",
message_id or inline_message_id,
chat_id,
params,
)
if type_edit == SERVICE_EDIT_MESSAGE:
message = kwargs.get(ATTR_MESSAGE)
title = kwargs.get(ATTR_TITLE)
text = f"{title}\n{message}" if title else message
_LOGGER.debug("Editing message with ID %s", message_id or inline_message_id)
return await self._send_msg(
self.bot.edit_message_text,
params[ATTR_MESSAGE_TAG],
text,
chat_id=chat_id,
message_id=message_id,
inline_message_id=inline_message_id,
parse_mode=params[ATTR_PARSER],
disable_web_page_preview=params[ATTR_DISABLE_WEB_PREV],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
context=context,
)
if type_edit == SERVICE_EDIT_CAPTION:
return await self._send_msg(
self.bot.edit_message_caption,
params[ATTR_MESSAGE_TAG],
chat_id=chat_id,
message_id=message_id,
inline_message_id=inline_message_id,
caption=kwargs.get(ATTR_CAPTION),
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
parse_mode=params[ATTR_PARSER],
context=context,
)
return await self._send_msg(
self.bot.edit_message_reply_markup,
params[ATTR_MESSAGE_TAG],
chat_id=chat_id,
message_id=message_id,
inline_message_id=inline_message_id,
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
context=context,
)
async def answer_callback_query(
self,
message: str | None,
callback_query_id: str,
show_alert: bool = False,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> None:
"""Answer a callback originated with a press in an inline keyboard."""
params = self._get_msg_kwargs(kwargs)
_LOGGER.debug(
"Answer callback query with callback ID %s: %s, alert: %s",
callback_query_id,
message,
show_alert,
)
await self._send_msg(
self.bot.answer_callback_query,
params[ATTR_MESSAGE_TAG],
callback_query_id,
text=message,
show_alert=show_alert,
read_timeout=params[ATTR_TIMEOUT],
context=context,
)
async def send_chat_action(
self,
chat_id: int,
chat_action: str = "",
context: Context | None = None,
**kwargs: Any,
) -> dict[str, JsonValueType]:
"""Send a chat action to pre-allowed chat IDs."""
result: dict[str, JsonValueType] = {}
_LOGGER.debug("Send action %s in chat ID %s", chat_action, chat_id)
is_successful = await self._send_msg(
self.bot.send_chat_action,
None,
chat_id=chat_id,
action=chat_action,
message_thread_id=kwargs.get(ATTR_MESSAGE_THREAD_ID),
context=context,
)
result[str(chat_id)] = is_successful
return result
async def send_file(
self,
file_type: str,
context: Context | None = None,
**kwargs: Any,
) -> dict[str, JsonValueType]:
"""Send a photo, sticker, video, or document."""
params = self._get_msg_kwargs(kwargs)
file_content = await load_data(
self.hass,
url=kwargs.get(ATTR_URL),
filepath=kwargs.get(ATTR_FILE),
username=kwargs.get(ATTR_USERNAME, ""),
password=kwargs.get(ATTR_PASSWORD, ""),
authentication=kwargs.get(ATTR_AUTHENTICATION),
verify_ssl=(
get_default_context()
if kwargs.get(ATTR_VERIFY_SSL, False)
else get_default_no_verify_context()
),
)
if file_type == SERVICE_SEND_PHOTO:
return await self._send_msg_formatted(
self.bot.send_photo,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
photo=file_content,
caption=kwargs.get(ATTR_CAPTION),
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
parse_mode=params[ATTR_PARSER],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
if file_type == SERVICE_SEND_STICKER:
return await self._send_msg_formatted(
self.bot.send_sticker,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
sticker=file_content,
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
if file_type == SERVICE_SEND_VIDEO:
return await self._send_msg_formatted(
self.bot.send_video,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
video=file_content,
caption=kwargs.get(ATTR_CAPTION),
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
parse_mode=params[ATTR_PARSER],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
if file_type == SERVICE_SEND_DOCUMENT:
return await self._send_msg_formatted(
self.bot.send_document,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
document=file_content,
caption=kwargs.get(ATTR_CAPTION),
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
parse_mode=params[ATTR_PARSER],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
if file_type == SERVICE_SEND_VOICE:
return await self._send_msg_formatted(
self.bot.send_voice,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
voice=file_content,
caption=kwargs.get(ATTR_CAPTION),
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
# SERVICE_SEND_ANIMATION
return await self._send_msg_formatted(
self.bot.send_animation,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
animation=file_content,
caption=kwargs.get(ATTR_CAPTION),
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
parse_mode=params[ATTR_PARSER],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
async def send_sticker(
self,
context: Context | None = None,
**kwargs: Any,
) -> dict[str, JsonValueType]:
"""Send a sticker from a telegram sticker pack."""
params = self._get_msg_kwargs(kwargs)
stickerid = kwargs.get(ATTR_STICKER_ID)
if stickerid:
return await self._send_msg_formatted(
self.bot.send_sticker,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
sticker=stickerid,
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
reply_markup=params[ATTR_REPLYMARKUP],
read_timeout=params[ATTR_TIMEOUT],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
return await self.send_file(SERVICE_SEND_STICKER, context, **kwargs)
async def send_location(
self,
latitude: Any,
longitude: Any,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> dict[str, JsonValueType]:
"""Send a location."""
latitude = float(latitude)
longitude = float(longitude)
params = self._get_msg_kwargs(kwargs)
return await self._send_msg_formatted(
self.bot.send_location,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
latitude=latitude,
longitude=longitude,
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
read_timeout=params[ATTR_TIMEOUT],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
async def send_poll(
self,
question: str,
options: Sequence[str | InputPollOption],
is_anonymous: bool | None,
allows_multiple_answers: bool | None,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> dict[str, JsonValueType]:
"""Send a poll."""
params = self._get_msg_kwargs(kwargs)
openperiod = kwargs.get(ATTR_OPEN_PERIOD)
return await self._send_msg_formatted(
self.bot.send_poll,
params[ATTR_MESSAGE_TAG],
chat_id=kwargs[ATTR_CHAT_ID],
question=question,
options=options,
is_anonymous=is_anonymous,
allows_multiple_answers=allows_multiple_answers,
open_period=openperiod,
disable_notification=params[ATTR_DISABLE_NOTIF],
reply_to_message_id=params[ATTR_REPLY_TO_MSGID],
read_timeout=params[ATTR_TIMEOUT],
message_thread_id=params[ATTR_MESSAGE_THREAD_ID],
context=context,
)
async def leave_chat(
self,
chat_id: int,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> Any:
"""Remove bot from chat."""
_LOGGER.debug("Leave from chat ID %s", chat_id)
return await self._send_msg(self.bot.leave_chat, None, chat_id, context=context)
async def set_message_reaction(
self,
reaction: str,
chat_id: int,
is_big: bool = False,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> None:
"""Set the bot's reaction for a given message."""
message_id, _ = self._get_msg_ids(kwargs, chat_id)
params = self._get_msg_kwargs(kwargs)
_LOGGER.debug(
"Set reaction to message %s in chat ID %s to %s with params: %s",
message_id,
chat_id,
reaction,
params,
)
await self._send_msg(
self.bot.set_message_reaction,
params[ATTR_MESSAGE_TAG],
chat_id,
message_id,
reaction=reaction,
is_big=is_big,
read_timeout=params[ATTR_TIMEOUT],
context=context,
)
async def download_file(
self,
file_id: str,
directory_path: str | None = None,
file_name: str | None = None,
context: Context | None = None,
**kwargs: dict[str, Any],
) -> dict[str, JsonValueType]:
"""Download a file from Telegram."""
if not directory_path:
directory_path = self.hass.config.path(DOMAIN)
file: File = await self._send_msg(
self.bot.get_file,
None,
file_id=file_id,
context=context,
)
if not file.file_path:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="action_failed",
translation_placeholders={
"error": "No file path returned from Telegram"
},
)
if not file_name:
file_name = os.path.basename(file.file_path)
custom_path = os.path.join(directory_path, file_name)
await self.hass.async_add_executor_job(
self._prepare_download_directory, directory_path
)
_LOGGER.debug("Download file %s to %s", file_id, custom_path)
try:
file_content = await file.download_as_bytearray()
await self.hass.async_add_executor_job(
Path(custom_path).write_bytes, file_content
)
except (RuntimeError, OSError, TelegramError) as exc:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="action_failed",
translation_placeholders={"error": str(exc)},
) from exc
return {ATTR_FILE_PATH: custom_path}
@staticmethod
def _prepare_download_directory(directory_path: str) -> None:
"""Create download directory if it does not exist."""
if not os.path.exists(directory_path):
_LOGGER.debug("directory %s does not exist, creating it", directory_path)
os.makedirs(directory_path, exist_ok=True)
def initialize_bot(hass: HomeAssistant, p_config: MappingProxyType[str, Any]) -> Bot:
"""Initialize telegram bot with proxy support."""
api_key: str = p_config[CONF_API_KEY]
# set up timeouts to handle large file downloads and uploads
# server-side file size limit is 2GB
read_timeout = DEFAULT_TIMEOUT_SECONDS
media_write_timeout = DEFAULT_TIMEOUT_SECONDS
proxy_url: str | None = p_config.get(CONF_PROXY_URL)
if proxy_url is not None:
proxy = httpx.Proxy(proxy_url)
request = HTTPXRequest(
connection_pool_size=8,
proxy=proxy,
read_timeout=read_timeout,
media_write_timeout=media_write_timeout,
)
else:
request = HTTPXRequest(
connection_pool_size=8,
read_timeout=read_timeout,
media_write_timeout=media_write_timeout,
)
base_url: str = p_config[CONF_API_ENDPOINT]
return Bot(
token=api_key,
base_url=f"{base_url}/bot",
base_file_url=f"{base_url}/file/bot",
request=request,
)
async def load_data(
hass: HomeAssistant,
url: str | None,
filepath: str | None,
username: str,
password: str,
authentication: str | None,
verify_ssl: SSLContext,
num_retries: int = 5,
) -> io.BytesIO:
"""Load data into ByteIO/File container from a source."""
if url is not None:
# Load data from URL
params: dict[str, Any] = {}
headers: dict[str, str] = {}
_validate_credentials_input(authentication, username, password)
if authentication == HTTP_BEARER_AUTHENTICATION:
headers = {"Authorization": f"Bearer {password}"}
elif authentication == HTTP_DIGEST_AUTHENTICATION:
params["auth"] = httpx.DigestAuth(username, password)
elif authentication == HTTP_BASIC_AUTHENTICATION:
params["auth"] = httpx.BasicAuth(username, password)
if verify_ssl is not None:
params["verify"] = verify_ssl
retry_num = 0
async with httpx.AsyncClient(
timeout=DEFAULT_TIMEOUT_SECONDS, headers=headers, **params
) as client:
while retry_num < num_retries:
try:
req = await client.get(url)
except (httpx.HTTPError, httpx.InvalidURL) as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="failed_to_load_url",
translation_placeholders={"error": str(err)},
) from err
if req.status_code != 200:
_LOGGER.warning(
"Status code %s (retry #%s) loading %s",
req.status_code,
retry_num + 1,
url,
)
else:
data = io.BytesIO(req.content)
if data.read():
data.seek(0)
data.name = url
_LOGGER.debug("file downloaded: %s", url)
return data
_LOGGER.warning("Empty data (retry #%s) in %s)", retry_num + 1, url)
retry_num += 1
if retry_num < num_retries:
await asyncio.sleep(
1
) # Add a sleep to allow other async operations to proceed
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="failed_to_load_url",
translation_placeholders={"error": str(req.status_code)},
)
elif filepath is not None:
if hass.config.is_allowed_path(filepath):
return await hass.async_add_executor_job(_read_file_as_bytesio, filepath)
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="allowlist_external_dirs_error",
)
else:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="missing_input",
translation_placeholders={"field": "URL or File"},
)
def _validate_credentials_input(
authentication: str | None, username: str | None, password: str | None
) -> None:
if (
authentication in (HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION)
and not username
):
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="missing_input",
translation_placeholders={"field": "Username"},
)
if (
authentication
in (
HTTP_BASIC_AUTHENTICATION,
HTTP_BEARER_AUTHENTICATION,
HTTP_BEARER_AUTHENTICATION,
)
and not password
):
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="missing_input",
translation_placeholders={"field": "Password"},
)
def _read_file_as_bytesio(file_path: str) -> io.BytesIO:
"""Read a file and return it as a BytesIO object."""
try:
with open(file_path, "rb") as file:
data = io.BytesIO(file.read())
data.name = file_path
return data
except OSError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="failed_to_load_file",
translation_placeholders={"error": str(err)},
) from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/telegram_bot/bot.py",
"license": "Apache License 2.0",
"lines": 1077,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/telegram_bot/config_flow.py | """Config flow for Telegram Bot."""
from collections.abc import Mapping
from ipaddress import AddressValueError, IPv4Network
import logging
from types import MappingProxyType
from typing import Any
from telegram import Bot, ChatFullInfo
from telegram.error import BadRequest, InvalidToken, TelegramError
import voluptuous as vol
from homeassistant.config_entries import (
SOURCE_RECONFIGURE,
ConfigEntryState,
ConfigFlow,
ConfigFlowResult,
ConfigSubentryFlow,
OptionsFlow,
SubentryFlowResult,
)
from homeassistant.const import CONF_API_KEY, CONF_PLATFORM, CONF_URL
from homeassistant.core import callback
from homeassistant.data_entry_flow import section
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.network import NoURLAvailableError, get_url
from homeassistant.helpers.selector import (
SelectSelector,
SelectSelectorConfig,
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from . import initialize_bot
from .bot import TelegramBotConfigEntry, TelegramNotificationService
from .const import (
ATTR_PARSER,
BOT_NAME,
CONF_API_ENDPOINT,
CONF_CHAT_ID,
CONF_PROXY_URL,
CONF_TRUSTED_NETWORKS,
DEFAULT_API_ENDPOINT,
DEFAULT_TRUSTED_NETWORKS,
DOMAIN,
ERROR_FIELD,
ERROR_MESSAGE,
PARSER_HTML,
PARSER_MD,
PARSER_MD2,
PARSER_PLAIN_TEXT,
PLATFORM_BROADCAST,
PLATFORM_POLLING,
PLATFORM_WEBHOOKS,
SECTION_ADVANCED_SETTINGS,
SUBENTRY_TYPE_ALLOWED_CHAT_IDS,
)
_LOGGER = logging.getLogger(__name__)
DESCRIPTION_PLACEHOLDERS: dict[str, str] = {
"botfather_username": "@BotFather",
"botfather_url": "https://t.me/botfather",
"getidsbot_username": "@GetIDs Bot",
"getidsbot_url": "https://t.me/getidsbot",
"socks_url": "socks5://username:password@proxy_ip:proxy_port",
# used in advanced settings section
"default_api_endpoint": DEFAULT_API_ENDPOINT,
}
STEP_USER_DATA_SCHEMA: vol.Schema = vol.Schema(
{
vol.Required(CONF_PLATFORM): SelectSelector(
SelectSelectorConfig(
options=[
PLATFORM_BROADCAST,
PLATFORM_POLLING,
PLATFORM_WEBHOOKS,
],
translation_key="platforms",
)
),
vol.Required(CONF_API_KEY): TextSelector(
TextSelectorConfig(
type=TextSelectorType.PASSWORD,
autocomplete="current-password",
)
),
vol.Required(SECTION_ADVANCED_SETTINGS): section(
vol.Schema(
{
vol.Required(
CONF_API_ENDPOINT,
default=DEFAULT_API_ENDPOINT,
): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.URL)
),
vol.Optional(CONF_PROXY_URL): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.URL)
),
},
),
{"collapsed": True},
),
}
)
STEP_RECONFIGURE_USER_DATA_SCHEMA: vol.Schema = vol.Schema(
{
vol.Required(CONF_PLATFORM): SelectSelector(
SelectSelectorConfig(
options=[
PLATFORM_BROADCAST,
PLATFORM_POLLING,
PLATFORM_WEBHOOKS,
],
translation_key="platforms",
)
),
vol.Required(SECTION_ADVANCED_SETTINGS): section(
vol.Schema(
{
vol.Required(
CONF_API_ENDPOINT,
default=DEFAULT_API_ENDPOINT,
): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.URL)
),
vol.Optional(CONF_PROXY_URL): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.URL)
),
},
),
{"collapsed": True},
),
}
)
STEP_REAUTH_DATA_SCHEMA: vol.Schema = vol.Schema(
{
vol.Required(CONF_API_KEY): TextSelector(
TextSelectorConfig(
type=TextSelectorType.PASSWORD,
autocomplete="current-password",
)
)
}
)
STEP_WEBHOOKS_DATA_SCHEMA: vol.Schema = vol.Schema(
{
vol.Optional(CONF_URL): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.URL)
),
vol.Required(CONF_TRUSTED_NETWORKS): vol.Coerce(str),
}
)
OPTIONS_SCHEMA: vol.Schema = vol.Schema(
{
vol.Required(
ATTR_PARSER,
): SelectSelector(
SelectSelectorConfig(
options=[PARSER_MD, PARSER_MD2, PARSER_HTML, PARSER_PLAIN_TEXT],
translation_key="parse_mode",
)
),
}
)
class OptionsFlowHandler(OptionsFlow):
"""Options flow."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Manage the options."""
if user_input is not None:
return self.async_create_entry(data=user_input)
return self.async_show_form(
step_id="init",
data_schema=self.add_suggested_values_to_schema(
OPTIONS_SCHEMA,
self.config_entry.options,
),
)
class TelgramBotConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Telegram."""
VERSION = 1
MINOR_VERSION = 2
@staticmethod
@callback
def async_get_options_flow(
config_entry: TelegramBotConfigEntry,
) -> OptionsFlowHandler:
"""Create the options flow."""
return OptionsFlowHandler()
@classmethod
@callback
def async_get_supported_subentry_types(
cls, config_entry: TelegramBotConfigEntry
) -> dict[str, type[ConfigSubentryFlow]]:
"""Return subentries supported by this integration."""
return {SUBENTRY_TYPE_ALLOWED_CHAT_IDS: AllowedChatIdsSubEntryFlowHandler}
def __init__(self) -> None:
"""Create instance of the config flow."""
super().__init__()
self._bot: Bot | None = None
self._bot_name = "Unknown bot"
# for passing data between steps
self._step_user_data: dict[str, Any] = {}
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a flow to create a new config entry for a Telegram bot."""
description_placeholders: dict[str, str] = DESCRIPTION_PLACEHOLDERS.copy()
if not user_input:
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
description_placeholders=description_placeholders,
)
# prevent duplicates
await self.async_set_unique_id(user_input[CONF_API_KEY])
self._abort_if_unique_id_configured()
# validate connection to Telegram API
errors: dict[str, str] = {}
user_input[CONF_API_ENDPOINT] = user_input[SECTION_ADVANCED_SETTINGS][
CONF_API_ENDPOINT
]
user_input[CONF_PROXY_URL] = user_input[SECTION_ADVANCED_SETTINGS].get(
CONF_PROXY_URL
)
bot_name = await self._validate_bot(
user_input, errors, description_placeholders
)
if errors:
return self.async_show_form(
step_id="user",
data_schema=self.add_suggested_values_to_schema(
STEP_USER_DATA_SCHEMA, user_input
),
errors=errors,
description_placeholders=description_placeholders,
)
if user_input[CONF_PLATFORM] != PLATFORM_WEBHOOKS:
await self._shutdown_bot()
return self.async_create_entry(
title=bot_name,
data={
CONF_PLATFORM: user_input[CONF_PLATFORM],
CONF_API_ENDPOINT: user_input[CONF_API_ENDPOINT],
CONF_API_KEY: user_input[CONF_API_KEY],
CONF_PROXY_URL: user_input[SECTION_ADVANCED_SETTINGS].get(
CONF_PROXY_URL
),
},
options={ATTR_PARSER: PARSER_MD},
description_placeholders=description_placeholders,
)
self._bot_name = bot_name
self._step_user_data.update(user_input)
return await self.async_step_webhooks()
async def _shutdown_bot(self) -> None:
"""Shutdown the bot if it exists."""
if self._bot:
await self._bot.shutdown()
async def _validate_bot(
self,
user_input: dict[str, Any],
errors: dict[str, str],
placeholders: dict[str, str],
) -> str:
try:
bot = await self.hass.async_add_executor_job(
initialize_bot, self.hass, MappingProxyType(user_input)
)
self._bot = bot
user = await bot.get_me()
except InvalidToken as err:
_LOGGER.warning("Invalid API token")
errors["base"] = "invalid_api_key"
placeholders[ERROR_FIELD] = "API key"
placeholders[ERROR_MESSAGE] = str(err)
return "Unknown bot"
except ValueError as err:
_LOGGER.warning("Invalid proxy")
errors["base"] = "invalid_proxy_url"
placeholders["proxy_url_error"] = str(err)
placeholders[ERROR_FIELD] = "proxy url"
placeholders[ERROR_MESSAGE] = str(err)
return "Unknown bot"
except TelegramError as err:
errors["base"] = "telegram_error"
placeholders[ERROR_MESSAGE] = str(err)
return "Unknown bot"
else:
return user.full_name
async def async_step_webhooks(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle config flow for webhook Telegram bot."""
if not user_input:
default_trusted_networks = ",".join(
[str(network) for network in DEFAULT_TRUSTED_NETWORKS]
)
if self.source == SOURCE_RECONFIGURE:
suggested_values = dict(self._get_reconfigure_entry().data)
if CONF_TRUSTED_NETWORKS not in self._get_reconfigure_entry().data:
suggested_values[CONF_TRUSTED_NETWORKS] = default_trusted_networks
return self.async_show_form(
step_id="webhooks",
data_schema=self.add_suggested_values_to_schema(
STEP_WEBHOOKS_DATA_SCHEMA,
suggested_values,
),
)
return self.async_show_form(
step_id="webhooks",
data_schema=self.add_suggested_values_to_schema(
STEP_WEBHOOKS_DATA_SCHEMA,
{
CONF_TRUSTED_NETWORKS: default_trusted_networks,
},
),
)
errors: dict[str, str] = {}
description_placeholders: dict[str, str] = {BOT_NAME: self._bot_name}
self._validate_webhooks(user_input, errors, description_placeholders)
if errors:
return self.async_show_form(
step_id="webhooks",
data_schema=self.add_suggested_values_to_schema(
STEP_WEBHOOKS_DATA_SCHEMA,
user_input,
),
errors=errors,
description_placeholders=description_placeholders,
)
await self._shutdown_bot()
if self.source == SOURCE_RECONFIGURE:
user_input.update(self._step_user_data)
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(),
title=self._bot_name,
data_updates=user_input,
)
return self.async_create_entry(
title=self._bot_name,
data={
CONF_PLATFORM: self._step_user_data[CONF_PLATFORM],
CONF_API_KEY: self._step_user_data[CONF_API_KEY],
CONF_API_ENDPOINT: self._step_user_data[SECTION_ADVANCED_SETTINGS][
CONF_API_ENDPOINT
],
CONF_PROXY_URL: self._step_user_data[SECTION_ADVANCED_SETTINGS].get(
CONF_PROXY_URL
),
CONF_URL: user_input.get(CONF_URL),
CONF_TRUSTED_NETWORKS: user_input[CONF_TRUSTED_NETWORKS],
},
options={ATTR_PARSER: self._step_user_data.get(ATTR_PARSER, PARSER_MD)},
description_placeholders=description_placeholders,
)
def _validate_webhooks(
self,
user_input: dict[str, Any],
errors: dict[str, str],
description_placeholders: dict[str, str],
) -> None:
# validate URL
url: str | None = user_input.get(CONF_URL)
if url is None:
try:
get_url(self.hass, require_ssl=True, allow_internal=False)
except NoURLAvailableError:
errors["base"] = "no_url_available"
description_placeholders[ERROR_FIELD] = "URL"
description_placeholders[ERROR_MESSAGE] = (
"URL is required since you have not configured an external URL in Home Assistant"
)
return
elif not url.startswith("https"):
errors["base"] = "invalid_url"
description_placeholders[ERROR_FIELD] = "URL"
description_placeholders[ERROR_MESSAGE] = "URL must start with https"
return
# validate trusted networks
csv_trusted_networks: list[str] = []
formatted_trusted_networks: str = (
user_input[CONF_TRUSTED_NETWORKS].lstrip("[").rstrip("]")
)
for trusted_network in cv.ensure_list_csv(formatted_trusted_networks):
formatted_trusted_network: str = trusted_network.strip("'")
try:
IPv4Network(formatted_trusted_network)
except (AddressValueError, ValueError) as err:
errors["base"] = "invalid_trusted_networks"
description_placeholders[ERROR_FIELD] = "trusted networks"
description_placeholders[ERROR_MESSAGE] = str(err)
return
else:
csv_trusted_networks.append(formatted_trusted_network)
user_input[CONF_TRUSTED_NETWORKS] = csv_trusted_networks
return
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Reconfigure Telegram bot."""
api_key: str = self._get_reconfigure_entry().data[CONF_API_KEY]
await self.async_set_unique_id(api_key)
self._abort_if_unique_id_mismatch()
if not user_input:
return self.async_show_form(
step_id="reconfigure",
data_schema=self.add_suggested_values_to_schema(
STEP_RECONFIGURE_USER_DATA_SCHEMA,
{
**self._get_reconfigure_entry().data,
SECTION_ADVANCED_SETTINGS: {
CONF_API_ENDPOINT: self._get_reconfigure_entry().data[
CONF_API_ENDPOINT
],
CONF_PROXY_URL: self._get_reconfigure_entry().data.get(
CONF_PROXY_URL
),
},
},
),
description_placeholders=DESCRIPTION_PLACEHOLDERS,
)
user_input[CONF_PROXY_URL] = user_input[SECTION_ADVANCED_SETTINGS].get(
CONF_PROXY_URL
)
user_input[CONF_API_ENDPOINT] = user_input[SECTION_ADVANCED_SETTINGS][
CONF_API_ENDPOINT
]
errors: dict[str, str] = {}
description_placeholders: dict[str, str] = DESCRIPTION_PLACEHOLDERS.copy()
user_input[CONF_API_KEY] = api_key
bot_name = await self._validate_bot(
user_input, errors, description_placeholders
)
self._bot_name = bot_name
existing_api_endpoint: str = self._get_reconfigure_entry().data[
CONF_API_ENDPOINT
]
if (
self._get_reconfigure_entry().state == ConfigEntryState.LOADED
and user_input[CONF_API_ENDPOINT] != DEFAULT_API_ENDPOINT
and existing_api_endpoint == DEFAULT_API_ENDPOINT
):
# logout existing bot from the official Telegram bot API
# logout is only used when changing the API endpoint from official to a custom one
# there is a 10-minute lockout period after logout so we only logout if necessary
service: TelegramNotificationService = (
self._get_reconfigure_entry().runtime_data
)
try:
is_logged_out = await service.bot.log_out()
except TelegramError as err:
errors["base"] = "telegram_error"
description_placeholders[ERROR_MESSAGE] = str(err)
else:
_LOGGER.info(
"[%s %s] Logged out: %s",
service.bot.username,
service.bot.id,
is_logged_out,
)
if not is_logged_out:
errors["base"] = "bot_logout_failed"
if errors:
return self.async_show_form(
step_id="reconfigure",
data_schema=self.add_suggested_values_to_schema(
STEP_RECONFIGURE_USER_DATA_SCHEMA,
{
**user_input,
SECTION_ADVANCED_SETTINGS: {
CONF_API_ENDPOINT: user_input[CONF_API_ENDPOINT],
CONF_PROXY_URL: user_input.get(CONF_PROXY_URL),
},
},
),
errors=errors,
description_placeholders=description_placeholders,
)
if user_input[CONF_PLATFORM] != PLATFORM_WEBHOOKS:
await self._shutdown_bot()
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(), title=bot_name, data_updates=user_input
)
self._step_user_data.update(user_input)
return await self.async_step_webhooks()
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Reauth step."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Reauth confirm step."""
if user_input is None:
return self.async_show_form(
step_id="reauth_confirm",
data_schema=self.add_suggested_values_to_schema(
STEP_REAUTH_DATA_SCHEMA, self._get_reauth_entry().data
),
)
errors: dict[str, str] = {}
description_placeholders: dict[str, str] = {}
updated_data = {**self._get_reauth_entry().data}
updated_data[CONF_API_KEY] = user_input[CONF_API_KEY]
bot_name = await self._validate_bot(
updated_data, errors, description_placeholders
)
await self._shutdown_bot()
if errors:
return self.async_show_form(
step_id="reauth_confirm",
data_schema=self.add_suggested_values_to_schema(
STEP_REAUTH_DATA_SCHEMA, self._get_reauth_entry().data
),
errors=errors,
description_placeholders=description_placeholders,
)
return self.async_update_reload_and_abort(
self._get_reauth_entry(), title=bot_name, data_updates=updated_data
)
class AllowedChatIdsSubEntryFlowHandler(ConfigSubentryFlow):
"""Handle a subentry flow for creating chat ID."""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""Create allowed chat ID."""
if self._get_entry().state != ConfigEntryState.LOADED:
return self.async_abort(
reason="entry_not_loaded",
description_placeholders={"telegram_bot": self._get_entry().title},
)
errors: dict[str, str] = {}
if user_input is not None:
config_entry: TelegramBotConfigEntry = self._get_entry()
bot = config_entry.runtime_data.bot
chat_id: int = user_input[CONF_CHAT_ID]
chat_name = await _async_get_chat_name(bot, chat_id)
if chat_name:
return self.async_create_entry(
title=f"{chat_name} ({chat_id})",
data={CONF_CHAT_ID: chat_id},
unique_id=str(chat_id),
)
errors["base"] = "chat_not_found"
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({vol.Required(CONF_CHAT_ID): vol.Coerce(int)}),
description_placeholders=DESCRIPTION_PLACEHOLDERS,
errors=errors,
)
async def _async_get_chat_name(bot: Bot, chat_id: int) -> str:
try:
chat_info: ChatFullInfo = await bot.get_chat(chat_id)
return chat_info.effective_name or str(chat_id)
except BadRequest:
return ""
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/telegram_bot/config_flow.py",
"license": "Apache License 2.0",
"lines": 556,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/telegram_bot/const.py | """Constants for the Telegram Bot integration."""
from ipaddress import ip_network
DOMAIN = "telegram_bot"
PLATFORM_BROADCAST = "broadcast"
PLATFORM_POLLING = "polling"
PLATFORM_WEBHOOKS = "webhooks"
SECTION_ADVANCED_SETTINGS = "advanced_settings"
SUBENTRY_TYPE_ALLOWED_CHAT_IDS = "allowed_chat_ids"
CONF_ALLOWED_CHAT_IDS = "allowed_chat_ids"
CONF_CONFIG_ENTRY_ID = "config_entry_id"
CONF_API_ENDPOINT = "api_endpoint"
CONF_PROXY_URL = "proxy_url"
CONF_TRUSTED_NETWORKS = "trusted_networks"
# subentry
CONF_CHAT_ID = "chat_id"
BOT_NAME = "telegram_bot"
ERROR_FIELD = "error_field"
ERROR_MESSAGE = "error_message"
DEFAULT_TIMEOUT_SECONDS = 1800 # 30 minutes
DEFAULT_API_ENDPOINT = "https://api.telegram.org"
DEFAULT_TRUSTED_NETWORKS = [ip_network("149.154.160.0/20"), ip_network("91.108.4.0/22")]
SERVICE_SEND_CHAT_ACTION = "send_chat_action"
SERVICE_SEND_MESSAGE = "send_message"
SERVICE_SEND_PHOTO = "send_photo"
SERVICE_SEND_STICKER = "send_sticker"
SERVICE_SEND_ANIMATION = "send_animation"
SERVICE_SEND_VIDEO = "send_video"
SERVICE_SEND_VOICE = "send_voice"
SERVICE_SEND_DOCUMENT = "send_document"
SERVICE_SEND_LOCATION = "send_location"
SERVICE_SEND_POLL = "send_poll"
SERVICE_SET_MESSAGE_REACTION = "set_message_reaction"
SERVICE_EDIT_MESSAGE = "edit_message"
SERVICE_EDIT_MESSAGE_MEDIA = "edit_message_media"
SERVICE_EDIT_CAPTION = "edit_caption"
SERVICE_EDIT_REPLYMARKUP = "edit_replymarkup"
SERVICE_ANSWER_CALLBACK_QUERY = "answer_callback_query"
SERVICE_DELETE_MESSAGE = "delete_message"
SERVICE_LEAVE_CHAT = "leave_chat"
SERVICE_DOWNLOAD_FILE = "download_file"
SIGNAL_UPDATE_EVENT = "telegram_bot_update_event"
EVENT_TELEGRAM_CALLBACK = "telegram_callback"
EVENT_TELEGRAM_COMMAND = "telegram_command"
EVENT_TELEGRAM_TEXT = "telegram_text"
EVENT_TELEGRAM_ATTACHMENT = "telegram_attachment"
EVENT_TELEGRAM_SENT = "telegram_sent"
PARSER_HTML = "html"
PARSER_MD = "markdown"
PARSER_MD2 = "markdownv2"
PARSER_PLAIN_TEXT = "plain_text"
ATTR_CHAT_ACTION = "chat_action"
ATTR_DATA = "data"
ATTR_MESSAGE = "message"
ATTR_TITLE = "title"
CHAT_ACTION_TYPING = "typing"
CHAT_ACTION_UPLOAD_PHOTO = "upload_photo"
CHAT_ACTION_RECORD_VIDEO = "record_video"
CHAT_ACTION_UPLOAD_VIDEO = "upload_video"
CHAT_ACTION_RECORD_VOICE = "record_voice"
CHAT_ACTION_UPLOAD_VOICE = "upload_voice"
CHAT_ACTION_UPLOAD_DOCUMENT = "upload_document"
CHAT_ACTION_CHOOSE_STICKER = "choose_sticker"
CHAT_ACTION_FIND_LOCATION = "find_location"
CHAT_ACTION_RECORD_VIDEO_NOTE = "record_video_note"
CHAT_ACTION_UPLOAD_VIDEO_NOTE = "upload_video_note"
ATTR_ARGS = "args"
ATTR_AUTHENTICATION = "authentication"
ATTR_CALLBACK_QUERY = "callback_query"
ATTR_CALLBACK_QUERY_ID = "callback_query_id"
ATTR_CAPTION = "caption"
ATTR_CHAT_ID = "chat_id"
ATTR_CHAT_INSTANCE = "chat_instance"
ATTR_DATE = "date"
ATTR_DISABLE_NOTIF = "disable_notification"
ATTR_DISABLE_WEB_PREV = "disable_web_page_preview"
ATTR_DIRECTORY_PATH = "directory_path"
ATTR_EDITED_MSG = "edited_message"
ATTR_FILE = "file"
ATTR_FILE_ID = "file_id"
ATTR_FILE_PATH = "file_path"
ATTR_FILE_MIME_TYPE = "file_mime_type"
ATTR_FILE_NAME = "file_name"
ATTR_FILE_SIZE = "file_size"
ATTR_FROM_FIRST = "from_first"
ATTR_FROM_LAST = "from_last"
ATTR_KEYBOARD = "keyboard"
ATTR_RESIZE_KEYBOARD = "resize_keyboard"
ATTR_ONE_TIME_KEYBOARD = "one_time_keyboard"
ATTR_KEYBOARD_INLINE = "inline_keyboard"
ATTR_MESSAGE_ID = "message_id"
ATTR_INLINE_MESSAGE_ID = "inline_message_id"
ATTR_MEDIA_TYPE = "media_type"
ATTR_MSG = "message"
ATTR_MSGID = "id"
ATTR_PARSER = "parse_mode"
ATTR_PASSWORD = "password"
ATTR_REACTION = "reaction"
ATTR_IS_BIG = "is_big"
ATTR_REPLY_TO_MSGID = "reply_to_message_id"
ATTR_REPLYMARKUP = "reply_markup"
ATTR_SHOW_ALERT = "show_alert"
ATTR_STICKER_ID = "sticker_id"
ATTR_TARGET = "target"
ATTR_TEXT = "text"
ATTR_URL = "url"
ATTR_USER_ID = "user_id"
ATTR_USERNAME = "username"
ATTR_VERIFY_SSL = "verify_ssl"
ATTR_TIMEOUT = "timeout"
ATTR_MESSAGE_TAG = "message_tag"
ATTR_CHANNEL_POST = "channel_post"
ATTR_QUESTION = "question"
ATTR_OPTIONS = "options"
ATTR_ANSWERS = "answers"
ATTR_OPEN_PERIOD = "open_period"
ATTR_IS_ANONYMOUS = "is_anonymous"
ATTR_ALLOWS_MULTIPLE_ANSWERS = "allows_multiple_answers"
ATTR_MESSAGE_THREAD_ID = "message_thread_id"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/telegram_bot/const.py",
"license": "Apache License 2.0",
"lines": 118,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/tilt_pi/config_flow.py | """Config flow for Tilt Pi integration."""
from typing import Any
import aiohttp
from tiltpi import TiltPiClient, TiltPiError
import voluptuous as vol
from yarl import URL
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_URL
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN
class TiltPiConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Tilt Pi."""
async def _check_connection(self, host: str, port: int) -> str | None:
"""Check if we can connect to the TiltPi instance."""
client = TiltPiClient(
host,
port,
session=async_get_clientsession(self.hass),
)
try:
await client.get_hydrometers()
except TiltPiError, TimeoutError, aiohttp.ClientError:
return "cannot_connect"
return None
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a configuration flow initialized by the user."""
errors = {}
if user_input is not None:
url = URL(user_input[CONF_URL])
if (host := url.host) is None:
errors[CONF_URL] = "invalid_host"
else:
self._async_abort_entries_match({CONF_HOST: host})
port = url.port
assert port
error = await self._check_connection(host=host, port=port)
if error:
errors["base"] = error
else:
return self.async_create_entry(
title="Tilt Pi",
data={
CONF_HOST: host,
CONF_PORT: port,
},
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({vol.Required(CONF_URL): str}),
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/tilt_pi/config_flow.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/tilt_pi/const.py | """Constants for the Tilt Pi integration."""
import logging
from typing import Final
LOGGER = logging.getLogger(__package__)
DOMAIN: Final = "tilt_pi"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/tilt_pi/const.py",
"license": "Apache License 2.0",
"lines": 5,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/tilt_pi/coordinator.py | """Data update coordinator for Tilt Pi."""
from datetime import timedelta
from typing import Final
from tiltpi import TiltHydrometerData, TiltPiClient, TiltPiError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import LOGGER
SCAN_INTERVAL: Final = timedelta(seconds=60)
type TiltPiConfigEntry = ConfigEntry[TiltPiDataUpdateCoordinator]
class TiltPiDataUpdateCoordinator(DataUpdateCoordinator[dict[str, TiltHydrometerData]]):
"""Class to manage fetching Tilt Pi data."""
config_entry: TiltPiConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: TiltPiConfigEntry,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
LOGGER,
config_entry=config_entry,
name="Tilt Pi",
update_interval=SCAN_INTERVAL,
)
self._api = TiltPiClient(
host=config_entry.data[CONF_HOST],
port=config_entry.data[CONF_PORT],
session=async_get_clientsession(hass),
)
self.identifier = config_entry.entry_id
async def _async_update_data(self) -> dict[str, TiltHydrometerData]:
"""Fetch data from Tilt Pi and return as a dict keyed by mac_id."""
try:
hydrometers = await self._api.get_hydrometers()
except TiltPiError as err:
raise UpdateFailed(f"Error communicating with Tilt Pi: {err}") from err
return {h.mac_id: h for h in hydrometers}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/tilt_pi/coordinator.py",
"license": "Apache License 2.0",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.