diff --git a/homeassistant/components/powerwall/__init__.py b/homeassistant/components/powerwall/__init__.py index 57ae6f0e260..c6c508136b2 100644 --- a/homeassistant/components/powerwall/__init__.py +++ b/homeassistant/components/powerwall/__init__.py @@ -9,8 +9,9 @@ import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import CONF_IP_ADDRESS -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.helpers import entity_registry import homeassistant.helpers.config_validation as cv from homeassistant.helpers.update_coordinator import DataUpdateCoordinator @@ -20,6 +21,7 @@ from .const import ( POWERWALL_API_DEVICE_TYPE, POWERWALL_API_GRID_STATUS, POWERWALL_API_METERS, + POWERWALL_API_SERIAL_NUMBERS, POWERWALL_API_SITE_INFO, POWERWALL_API_SITEMASTER, POWERWALL_API_STATUS, @@ -55,6 +57,36 @@ async def async_setup(hass: HomeAssistant, config: dict): return True +async def _migrate_old_unique_ids(hass, entry_id, powerwall_data): + serial_numbers = powerwall_data[POWERWALL_API_SERIAL_NUMBERS] + site_info = powerwall_data[POWERWALL_API_SITE_INFO] + + @callback + def _async_migrator(entity_entry: entity_registry.RegistryEntry): + parts = entity_entry.unique_id.split("_") + # Check if the unique_id starts with the serial_numbers of the powerwakks + if parts[0 : len(serial_numbers)] != serial_numbers: + # The old unique_id ended with the nomianal_system_engery_kWh so we can use that + # to find the old base unique_id and extract the device_suffix. + normalized_energy_index = ( + len(parts) + - 1 + - parts[::-1].index(str(site_info.nominal_system_energy_kWh)) + ) + device_suffix = parts[normalized_energy_index + 1 :] + + new_unique_id = "_".join([*serial_numbers, *device_suffix]) + _LOGGER.info( + "Migrating unique_id from [%s] to [%s]", + entity_entry.unique_id, + new_unique_id, + ) + return {"new_unique_id": new_unique_id} + return None + + await entity_registry.async_migrate_entries(hass, entry_id, _async_migrator) + + async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Tesla Powerwall from a config entry.""" @@ -69,6 +101,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): http_session.close() raise ConfigEntryNotReady + await _migrate_old_unique_ids(hass, entry_id, powerwall_data) + async def async_update_data(): """Fetch data from API endpoint.""" return await hass.async_add_executor_job(_fetch_powerwall_data, power_wall) @@ -102,10 +136,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): def call_base_info(power_wall): """Wrap powerwall properties to be a callable.""" + serial_numbers = power_wall.get_serial_numbers() + # Make sure the serial numbers always have the same order + serial_numbers.sort() return { POWERWALL_API_SITE_INFO: power_wall.get_site_info(), POWERWALL_API_STATUS: power_wall.get_status(), POWERWALL_API_DEVICE_TYPE: power_wall.get_device_type(), + POWERWALL_API_SERIAL_NUMBERS: serial_numbers, } diff --git a/homeassistant/components/powerwall/binary_sensor.py b/homeassistant/components/powerwall/binary_sensor.py index f088a257574..4e1c639aa65 100644 --- a/homeassistant/components/powerwall/binary_sensor.py +++ b/homeassistant/components/powerwall/binary_sensor.py @@ -16,6 +16,7 @@ from .const import ( DOMAIN, POWERWALL_API_DEVICE_TYPE, POWERWALL_API_GRID_STATUS, + POWERWALL_API_SERIAL_NUMBERS, POWERWALL_API_SITE_INFO, POWERWALL_API_SITEMASTER, POWERWALL_API_STATUS, @@ -34,6 +35,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities): site_info = powerwall_data[POWERWALL_API_SITE_INFO] device_type = powerwall_data[POWERWALL_API_DEVICE_TYPE] status = powerwall_data[POWERWALL_API_STATUS] + powerwalls_serial_numbers = powerwall_data[POWERWALL_API_SERIAL_NUMBERS] entities = [] for sensor_class in ( @@ -41,7 +43,11 @@ async def async_setup_entry(hass, config_entry, async_add_entities): PowerWallGridStatusSensor, PowerWallConnectedSensor, ): - entities.append(sensor_class(coordinator, site_info, status, device_type)) + entities.append( + sensor_class( + coordinator, site_info, status, device_type, powerwalls_serial_numbers + ) + ) async_add_entities(entities, True) diff --git a/homeassistant/components/powerwall/const.py b/homeassistant/components/powerwall/const.py index d05e42f6bf7..9f652bea5f5 100644 --- a/homeassistant/components/powerwall/const.py +++ b/homeassistant/components/powerwall/const.py @@ -34,6 +34,7 @@ POWERWALL_API_SITEMASTER = "sitemaster" POWERWALL_API_STATUS = "status" POWERWALL_API_DEVICE_TYPE = "device_type" POWERWALL_API_SITE_INFO = "site_info" +POWERWALL_API_SERIAL_NUMBERS = "serial_numbers" POWERWALL_HTTP_SESSION = "http_session" diff --git a/homeassistant/components/powerwall/entity.py b/homeassistant/components/powerwall/entity.py index 9e09ed06c4b..27c12ed23ce 100644 --- a/homeassistant/components/powerwall/entity.py +++ b/homeassistant/components/powerwall/entity.py @@ -8,20 +8,17 @@ from .const import DOMAIN, MANUFACTURER, MODEL class PowerWallEntity(Entity): """Base class for powerwall entities.""" - def __init__(self, coordinator, site_info, status, device_type): + def __init__( + self, coordinator, site_info, status, device_type, powerwalls_serial_numbers + ): """Initialize the sensor.""" super().__init__() self._coordinator = coordinator self._site_info = site_info self._device_type = device_type self._version = status.version - # This group of properties will be unique to to the site - unique_group = ( - site_info.utility, - site_info.grid_code, - str(site_info.nominal_system_energy_kWh), - ) - self.base_unique_id = "_".join(unique_group) + # The serial numbers of the powerwalls are unique to every site + self.base_unique_id = "_".join(powerwalls_serial_numbers) @property def device_info(self): diff --git a/homeassistant/components/powerwall/sensor.py b/homeassistant/components/powerwall/sensor.py index 3b3d3b9cd32..253fae8bd36 100644 --- a/homeassistant/components/powerwall/sensor.py +++ b/homeassistant/components/powerwall/sensor.py @@ -19,6 +19,7 @@ from .const import ( POWERWALL_API_CHARGE, POWERWALL_API_DEVICE_TYPE, POWERWALL_API_METERS, + POWERWALL_API_SERIAL_NUMBERS, POWERWALL_API_SITE_INFO, POWERWALL_API_STATUS, POWERWALL_COORDINATOR, @@ -37,14 +38,26 @@ async def async_setup_entry(hass, config_entry, async_add_entities): site_info = powerwall_data[POWERWALL_API_SITE_INFO] device_type = powerwall_data[POWERWALL_API_DEVICE_TYPE] status = powerwall_data[POWERWALL_API_STATUS] + powerwalls_serial_numbers = powerwall_data[POWERWALL_API_SERIAL_NUMBERS] entities = [] for meter in MeterType: entities.append( - PowerWallEnergySensor(meter, coordinator, site_info, status, device_type) + PowerWallEnergySensor( + meter, + coordinator, + site_info, + status, + device_type, + powerwalls_serial_numbers, + ) ) - entities.append(PowerWallChargeSensor(coordinator, site_info, status, device_type)) + entities.append( + PowerWallChargeSensor( + coordinator, site_info, status, device_type, powerwalls_serial_numbers + ) + ) async_add_entities(entities, True) @@ -81,9 +94,19 @@ class PowerWallChargeSensor(PowerWallEntity): class PowerWallEnergySensor(PowerWallEntity): """Representation of an Powerwall Energy sensor.""" - def __init__(self, meter: MeterType, coordinator, site_info, status, device_type): + def __init__( + self, + meter: MeterType, + coordinator, + site_info, + status, + device_type, + powerwalls_serial_numbers, + ): """Initialize the sensor.""" - super().__init__(coordinator, site_info, status, device_type) + super().__init__( + coordinator, site_info, status, device_type, powerwalls_serial_numbers + ) self._meter = meter @property diff --git a/tests/components/powerwall/mocks.py b/tests/components/powerwall/mocks.py index afe9e130379..8a559d1dd49 100644 --- a/tests/components/powerwall/mocks.py +++ b/tests/components/powerwall/mocks.py @@ -36,6 +36,7 @@ async def _mock_powerwall_with_fixtures(hass): grid_status=GridStatus.CONNECTED, status=PowerwallStatusResponse(status), device_type=DeviceType(device_type["device_type"]), + serial_numbers=["TG0123456789AB", "TG9876543210BA"], ) @@ -47,6 +48,7 @@ def _mock_powerwall_return_value( grid_status=None, status=None, device_type=None, + serial_numbers=None, ): powerwall_mock = MagicMock(Powerwall("1.2.3.4")) powerwall_mock.get_site_info = Mock(return_value=site_info) @@ -56,6 +58,7 @@ def _mock_powerwall_return_value( powerwall_mock.get_grid_status = Mock(return_value=grid_status) powerwall_mock.get_status = Mock(return_value=status) powerwall_mock.get_device_type = Mock(return_value=device_type) + powerwall_mock.get_serial_numbers = Mock(return_value=serial_numbers) return powerwall_mock diff --git a/tests/components/powerwall/test_sensor.py b/tests/components/powerwall/test_sensor.py index ce0c929ab92..b6c224080a1 100644 --- a/tests/components/powerwall/test_sensor.py +++ b/tests/components/powerwall/test_sensor.py @@ -25,8 +25,7 @@ async def test_sensors(hass): device_registry = await hass.helpers.device_registry.async_get_registry() reg_device = device_registry.async_get_device( - identifiers={("powerwall", "Wom Energy_60Hz_240V_s_IEEE1547a_2014_13.5")}, - connections=set(), + identifiers={("powerwall", "TG0123456789AB_TG9876543210BA")}, connections=set(), ) assert reg_device.model == "PowerWall 2 (GW1)" assert reg_device.sw_version == "1.45.1"