Use serial numbers for unique_id of powerwall devices (#34351)

* Update tesla-powerwall to version 0.2.5

* Create unique_id from serial numbers of powerwalls
	modified:   homeassistant/components/powerwall/__init__.py
	modified:   homeassistant/components/powerwall/binary_sensor.py
	modified:   homeassistant/components/powerwall/const.py
	modified:   homeassistant/components/powerwall/entity.py
	modified:   homeassistant/components/powerwall/sensor.py
	modified:   tests/components/powerwall/mocks.py
	modified:   tests/components/powerwall/test_sensor.py

* Fix pylint error
	modified:   homeassistant/components/powerwall/__init__.py
This commit is contained in:
jrester 2020-04-17 23:21:14 +02:00 committed by GitHub
parent 618538aeff
commit 3776a06281
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 83 additions and 16 deletions

View file

@ -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,
}

View file

@ -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)

View file

@ -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"

View file

@ -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):

View file

@ -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

View file

@ -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

View file

@ -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"