mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 11:33:11 -04:00
Add uid to the unique_id of Shelly IR code button (#195894)
This commit is contained in:
@@ -77,6 +77,7 @@ from .repairs import (
|
||||
)
|
||||
from .services import async_setup_services
|
||||
from .utils import (
|
||||
async_migrate_rpc_ircode_unique_ids,
|
||||
async_migrate_rpc_sensor_description_unique_ids,
|
||||
async_migrate_rpc_virtual_components_unique_ids,
|
||||
get_coap_context,
|
||||
@@ -389,6 +390,11 @@ async def _async_setup_rpc_entry(hass: HomeAssistant, entry: ShellyConfigEntry)
|
||||
entry.entry_id,
|
||||
partial(async_migrate_rpc_virtual_components_unique_ids, device.config),
|
||||
)
|
||||
await er.async_migrate_entries(
|
||||
hass,
|
||||
entry.entry_id,
|
||||
partial(async_migrate_rpc_ircode_unique_ids, device.status),
|
||||
)
|
||||
|
||||
runtime_data.rpc = ShellyRpcCoordinator(hass, entry, device)
|
||||
runtime_data.rpc.async_setup()
|
||||
|
||||
@@ -39,6 +39,7 @@ from .entity import (
|
||||
rpc_call,
|
||||
)
|
||||
from .utils import (
|
||||
async_get_stale_rpc_ircode_entries,
|
||||
async_remove_orphaned_entities,
|
||||
async_remove_shelly_entity,
|
||||
format_ble_addr,
|
||||
@@ -169,6 +170,14 @@ async def async_setup_entry(
|
||||
RpcSleepingSmokeMuteButton,
|
||||
)
|
||||
else:
|
||||
# A deleted IR code's id can be given to a new code. If that happens
|
||||
# while Home Assistant is not connected, there is no reload to remove
|
||||
# the old entity, so remove entities whose uid is no longer on the device.
|
||||
for entry in async_get_stale_rpc_ircode_entries(
|
||||
hass, config_entry.entry_id, coordinator.mac, coordinator.device.status
|
||||
):
|
||||
async_remove_shelly_entity(hass, BUTTON_DOMAIN, entry.unique_id)
|
||||
|
||||
async_setup_entry_rpc(
|
||||
hass, config_entry, async_add_entities, RPC_BUTTONS, RpcVirtualButton
|
||||
)
|
||||
@@ -328,6 +337,11 @@ class RpcIrCodeButton(ShellyRpcAttributeEntity, ButtonEntity):
|
||||
"""Initialize IRCode button."""
|
||||
super().__init__(coordinator, key, attribute, description)
|
||||
|
||||
# uid is null for IR codes stored by firmware older than 2.2.2
|
||||
self._uid: str | None = self.status["uid"]
|
||||
if self._uid is not None:
|
||||
self._attr_unique_id = f"{super().unique_id}-{self._uid}"
|
||||
|
||||
if (custom_name := get_rpc_custom_name(coordinator.device, key)) is not None:
|
||||
self._attr_name = custom_name
|
||||
else:
|
||||
@@ -341,6 +355,13 @@ class RpcIrCodeButton(ShellyRpcAttributeEntity, ButtonEntity):
|
||||
key,
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def available(self) -> bool:
|
||||
"""Return False while the device holds a different code under this id."""
|
||||
status = self.coordinator.device.status.get(self.key)
|
||||
return super().available and (status is None or status["uid"] == self._uid)
|
||||
|
||||
@rpc_call
|
||||
@override
|
||||
async def async_press(self) -> None:
|
||||
|
||||
@@ -77,6 +77,7 @@ from .const import (
|
||||
)
|
||||
from .repairs import async_create_issue_unsupported_firmware
|
||||
from .utils import (
|
||||
async_get_stale_rpc_ircode_entries,
|
||||
async_manage_coiot_issues_task,
|
||||
get_block_device_sleep_period,
|
||||
get_device_entry_gen,
|
||||
@@ -850,6 +851,15 @@ class ShellyRpcCoordinator(ShellyCoordinatorBase[RpcDevice]):
|
||||
"Error running connected events for device %s: %s", self.name, err
|
||||
)
|
||||
self.last_update_success = False
|
||||
if (
|
||||
not self.sleep_period
|
||||
and self.device.firmware_supported
|
||||
and self.config_entry.state is ConfigEntryState.LOADED
|
||||
and async_get_stale_rpc_ircode_entries(
|
||||
self.hass, self.config_entry.entry_id, self.mac, self.device.status
|
||||
)
|
||||
):
|
||||
self._async_schedule_reload()
|
||||
|
||||
async def _async_run_connected_events(self) -> None:
|
||||
"""Run connected events.
|
||||
|
||||
@@ -33,6 +33,7 @@ from awesomeversion import AwesomeVersion
|
||||
from yarl import URL
|
||||
|
||||
from homeassistant.components import network
|
||||
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
from homeassistant.components.network import async_get_source_ip
|
||||
from homeassistant.const import (
|
||||
@@ -1102,6 +1103,53 @@ def async_migrate_rpc_virtual_components_unique_ids(
|
||||
return None
|
||||
|
||||
|
||||
@callback
|
||||
def async_migrate_rpc_ircode_unique_ids(
|
||||
status: dict[str, Any], entity_entry: er.RegistryEntry
|
||||
) -> dict[str, Any] | None:
|
||||
"""Migrate RPC IR code button unique_ids to include the uid.
|
||||
|
||||
The old unique_id format is: {mac}-{key}-ircode
|
||||
The new unique_id format is: {mac}-{key}-ircode-{uid}
|
||||
"""
|
||||
if (
|
||||
entity_entry.domain == BUTTON_DOMAIN
|
||||
and entity_entry.unique_id.endswith("-ircode")
|
||||
and (key := entity_entry.unique_id.split("-")[-2]) in status
|
||||
and (uid := status[key]["uid"]) is not None
|
||||
):
|
||||
new_unique_id = f"{entity_entry.unique_id}-{uid}"
|
||||
LOGGER.debug(
|
||||
"Migrating unique_id for %s entity from [%s] to [%s]",
|
||||
entity_entry.entity_id,
|
||||
entity_entry.unique_id,
|
||||
new_unique_id,
|
||||
)
|
||||
return {"new_unique_id": new_unique_id}
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@callback
|
||||
def async_get_stale_rpc_ircode_entries(
|
||||
hass: HomeAssistant, entry_id: str, mac: str, status: dict[str, Any]
|
||||
) -> list[er.RegistryEntry]:
|
||||
"""Return IR code button entries whose unique_id is not on the device."""
|
||||
current_unique_ids = {
|
||||
f"{mac}-{key}-ircode-{status[key]['uid']}"
|
||||
if status[key]["uid"] is not None
|
||||
else f"{mac}-{key}-ircode"
|
||||
for key in get_rpc_key_instances(status, "ircode")
|
||||
}
|
||||
return [
|
||||
entry
|
||||
for entry in er.async_entries_for_config_entry(er.async_get(hass), entry_id)
|
||||
if entry.domain == BUTTON_DOMAIN
|
||||
and entry.unique_id.startswith(f"{mac}-ircode:")
|
||||
and entry.unique_id not in current_unique_ids
|
||||
]
|
||||
|
||||
|
||||
def is_rpc_ble_scanner_supported(entry: ShellyConfigEntry) -> bool:
|
||||
"""Return true if BLE scanner is supported."""
|
||||
return bool(
|
||||
|
||||
@@ -233,7 +233,7 @@
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': None,
|
||||
'unique_id': '123456789ABC-ircode:200-ircode',
|
||||
'unique_id': '123456789ABC-ircode:200-ircode-9985fb6e-d805-4ebe-a4fa-12af2541aee5',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
@@ -283,7 +283,7 @@
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': None,
|
||||
'unique_id': '123456789ABC-ircode:203-ircode',
|
||||
'unique_id': '123456789ABC-ircode:203-ircode-c21a9f48-e6b7-4d03-8f15-9a4e7b6d5c03',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
@@ -333,7 +333,7 @@
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': None,
|
||||
'unique_id': '123456789ABC-ircode:202-ircode',
|
||||
'unique_id': '123456789ABC-ircode:202-ircode-b7d04e12-8a3f-4f65-a1c9-6e5d2c8b3a02',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
@@ -383,7 +383,7 @@
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': None,
|
||||
'unique_id': '123456789ABC-ircode:201-ircode',
|
||||
'unique_id': '123456789ABC-ircode:201-ircode-3f1c2a7e-5b4d-4c8a-9e60-1d2b7a9c4f01',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Tests for Shelly button platform."""
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import timedelta
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
from aioshelly.const import (
|
||||
@@ -10,11 +11,13 @@ from aioshelly.const import (
|
||||
MODEL_WALL_DISPLAY,
|
||||
)
|
||||
from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError, RpcCallError
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from pytest_homeassistant.common import async_fire_time_changed
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, ButtonService
|
||||
from homeassistant.components.shelly.const import DOMAIN
|
||||
from homeassistant.components.shelly.const import DOMAIN, ENTRY_RELOAD_COOLDOWN
|
||||
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
|
||||
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform, TargetKey
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -38,11 +41,12 @@ IRCODE_CONFIG = {
|
||||
"irdevice:200": {"id": 200, "name": "Fan"},
|
||||
"irdevice:201": {"id": 201, "name": "Light"},
|
||||
}
|
||||
IRCODE_200_UID = "9985fb6e-d805-4ebe-a4fa-12af2541aee5"
|
||||
IRCODE_STATUS = {
|
||||
"ircode:200": {"id": 200},
|
||||
"ircode:201": {"id": 201},
|
||||
"ircode:202": {"id": 202},
|
||||
"ircode:203": {"id": 203},
|
||||
"ircode:200": {"id": 200, "uid": IRCODE_200_UID},
|
||||
"ircode:201": {"id": 201, "uid": "3f1c2a7e-5b4d-4c8a-9e60-1d2b7a9c4f01"},
|
||||
"ircode:202": {"id": 202, "uid": "b7d04e12-8a3f-4f65-a1c9-6e5d2c8b3a02"},
|
||||
"ircode:203": {"id": 203, "uid": "c21a9f48-e6b7-4d03-8f15-9a4e7b6d5c03"},
|
||||
"irdevice:200": {"id": 200},
|
||||
"irdevice:201": {"id": 201},
|
||||
}
|
||||
@@ -349,6 +353,175 @@ async def test_rpc_remove_virtual_button_when_orphaned(
|
||||
assert not entry
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("uid", "expected_unique_id"),
|
||||
[
|
||||
(IRCODE_200_UID, f"123456789ABC-ircode:200-ircode-{IRCODE_200_UID}"),
|
||||
(None, "123456789ABC-ircode:200-ircode"),
|
||||
],
|
||||
)
|
||||
async def test_rpc_ircode_button_unique_id_migration(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: EntityRegistry,
|
||||
device_registry: DeviceRegistry,
|
||||
mock_rpc_device: Mock,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
uid: str | None,
|
||||
expected_unique_id: str,
|
||||
) -> None:
|
||||
"""Test IR code button unique_id migration to include the uid."""
|
||||
monkeypatch.setattr(mock_rpc_device, "config", IRCODE_CONFIG)
|
||||
monkeypatch.setattr(
|
||||
mock_rpc_device,
|
||||
"status",
|
||||
{**IRCODE_STATUS, "ircode:200": {"id": 200, "uid": uid}},
|
||||
)
|
||||
|
||||
config_entry = await init_integration(hass, 4, skip_setup=True)
|
||||
device_entry = register_device(device_registry, config_entry)
|
||||
entity_id = register_entity(
|
||||
hass,
|
||||
BUTTON_DOMAIN,
|
||||
"test_name_fan_speed_1",
|
||||
"ircode:200-ircode",
|
||||
config_entry,
|
||||
device_id=device_entry.id,
|
||||
)
|
||||
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (entry := entity_registry.async_get(entity_id))
|
||||
assert entry.unique_id == expected_unique_id
|
||||
ircode_entries = [
|
||||
e for e in entity_registry.entities.values() if "-ircode:" in e.unique_id
|
||||
]
|
||||
assert len(ircode_entries) == 4
|
||||
|
||||
|
||||
async def test_rpc_ircode_button_stale_uid_removed(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: EntityRegistry,
|
||||
device_registry: DeviceRegistry,
|
||||
mock_rpc_device: Mock,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Test IR code button with an outdated uid is removed."""
|
||||
monkeypatch.setattr(mock_rpc_device, "config", IRCODE_CONFIG)
|
||||
monkeypatch.setattr(mock_rpc_device, "status", IRCODE_STATUS)
|
||||
|
||||
config_entry = await init_integration(hass, 4, skip_setup=True)
|
||||
device_entry = register_device(device_registry, config_entry)
|
||||
stale_entity_id = register_entity(
|
||||
hass,
|
||||
BUTTON_DOMAIN,
|
||||
"test_name_fan_speed_1",
|
||||
"ircode:200-ircode-5a8e3c91-2f7b-4d16-b0a4-7c9e1d3f8b04",
|
||||
config_entry,
|
||||
device_id=device_entry.id,
|
||||
)
|
||||
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
entity_registry.async_get_entity_id(
|
||||
BUTTON_DOMAIN,
|
||||
DOMAIN,
|
||||
"123456789ABC-ircode:200-ircode-5a8e3c91-2f7b-4d16-b0a4-7c9e1d3f8b04",
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert (
|
||||
entity_registry.async_get_entity_id(
|
||||
BUTTON_DOMAIN, DOMAIN, f"123456789ABC-ircode:200-ircode-{IRCODE_200_UID}"
|
||||
)
|
||||
== stale_entity_id
|
||||
)
|
||||
ircode_entries = [
|
||||
e for e in entity_registry.entities.values() if "-ircode:" in e.unique_id
|
||||
]
|
||||
assert len(ircode_entries) == 4
|
||||
|
||||
|
||||
async def test_rpc_ircode_button_replaced_while_disconnected(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
entity_registry: EntityRegistry,
|
||||
mock_rpc_device: Mock,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Test IR code replaced with the same id while disconnected is reconciled."""
|
||||
new_uid = "5a8e3c91-2f7b-4d16-b0a4-7c9e1d3f8b04"
|
||||
entity_id = "button.test_name_fan_speed_1"
|
||||
monkeypatch.setattr(mock_rpc_device, "config", IRCODE_CONFIG)
|
||||
monkeypatch.setattr(
|
||||
mock_rpc_device, "status", {**mock_rpc_device.status, **IRCODE_STATUS}
|
||||
)
|
||||
await init_integration(hass, 4)
|
||||
|
||||
mock_rpc_device.mock_disconnected()
|
||||
await hass.async_block_till_done()
|
||||
mutate_rpc_device_status(monkeypatch, mock_rpc_device, "ircode:200", "uid", new_uid)
|
||||
mock_rpc_device.mock_initialized()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
mock_rpc_device.ircode_emit.reset_mock()
|
||||
await hass.services.async_call(
|
||||
BUTTON_DOMAIN,
|
||||
ButtonService.PRESS,
|
||||
{TargetKey.ENTITY_ID: entity_id},
|
||||
blocking=True,
|
||||
)
|
||||
mock_rpc_device.ircode_emit.assert_not_called()
|
||||
|
||||
freezer.tick(timedelta(seconds=ENTRY_RELOAD_COOLDOWN))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
entity_registry.async_get_entity_id(
|
||||
BUTTON_DOMAIN, DOMAIN, f"123456789ABC-ircode:200-ircode-{IRCODE_200_UID}"
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert (
|
||||
entity_registry.async_get_entity_id(
|
||||
BUTTON_DOMAIN, DOMAIN, f"123456789ABC-ircode:200-ircode-{new_uid}"
|
||||
)
|
||||
is not None
|
||||
)
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state != STATE_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_rpc_ircode_reconnect_unsupported_firmware(
|
||||
hass: HomeAssistant,
|
||||
mock_rpc_device: Mock,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test reconnect with unsupported firmware that does not report the uid."""
|
||||
monkeypatch.setattr(mock_rpc_device, "firmware_supported", False)
|
||||
monkeypatch.setattr(mock_rpc_device, "config", IRCODE_CONFIG)
|
||||
monkeypatch.setattr(
|
||||
mock_rpc_device,
|
||||
"status",
|
||||
{**mock_rpc_device.status, "ircode:200": {"id": 200}},
|
||||
)
|
||||
config_entry = await init_integration(hass, 4)
|
||||
|
||||
mock_rpc_device.mock_disconnected()
|
||||
await hass.async_block_till_done()
|
||||
mock_rpc_device.mock_initialized()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
assert "KeyError" not in caplog.text
|
||||
|
||||
|
||||
async def test_wall_display_virtual_button(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: EntityRegistry,
|
||||
@@ -549,7 +722,7 @@ async def test_rpc_ircode_button_no_custom_name(
|
||||
mock_rpc_device,
|
||||
"status",
|
||||
{
|
||||
"ircode:20": {"id": 20},
|
||||
"ircode:20": {"id": 20, "uid": "e4f6a0b2-7c1d-4e93-a5b8-3d2f9c6e1a05"},
|
||||
"irdevice:30": {"id": 30},
|
||||
},
|
||||
)
|
||||
@@ -565,7 +738,10 @@ async def test_rpc_ircode_button_no_custom_name(
|
||||
assert state.state == STATE_UNKNOWN
|
||||
|
||||
assert (entry := entity_registry.async_get(entity_id))
|
||||
assert entry.unique_id == "123456789ABC-ircode:20-ircode"
|
||||
assert (
|
||||
entry.unique_id
|
||||
== "123456789ABC-ircode:20-ircode-e4f6a0b2-7c1d-4e93-a5b8-3d2f9c6e1a05"
|
||||
)
|
||||
|
||||
# Verify IR device with fallback name
|
||||
ir_device = device_registry.async_get_child_device_by_identifier(
|
||||
|
||||
Reference in New Issue
Block a user