Add Nut device explicitly to the device registry (#59525)

* Add Nut device explicitly to the device registry

* Restore resources in data and remove unused string
This commit is contained in:
ollo69 2021-11-12 11:10:40 +01:00 committed by GitHub
parent 363de37400
commit 21f92f6286
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 9 deletions

View file

@ -19,6 +19,7 @@ from homeassistant.const import (
CONF_USERNAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
@ -37,11 +38,14 @@ _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Network UPS Tools (NUT) from a config entry."""
# strip out the stale setting CONF_RESOURCES from data & options
if CONF_RESOURCES in entry.data:
new_data = {k: v for k, v in entry.data.items() if k != CONF_RESOURCES}
new_opts = {k: v for k, v in entry.options.items() if k != CONF_RESOURCES}
hass.config_entries.async_update_entry(entry, data=new_data, options=new_opts)
# strip out the stale options CONF_RESOURCES,
# maintain the entry in data in case of version rollback
if CONF_RESOURCES in entry.options:
new_data = {**entry.data, CONF_RESOURCES: entry.options[CONF_RESOURCES]}
new_options = {k: v for k, v in entry.options.items() if k != CONF_RESOURCES}
hass.config_entries.async_update_entry(
entry, data=new_data, options=new_options
)
config = entry.data
host = config[CONF_HOST]
@ -88,6 +92,17 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
PYNUT_UNIQUE_ID: unique_id,
UNDO_UPDATE_LISTENER: undo_listener,
}
device_registry = dr.async_get(hass)
device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, unique_id)},
name=data.name.title(),
manufacturer=data.device_info.get(ATTR_MANUFACTURER),
model=data.device_info.get(ATTR_MODEL),
sw_version=data.device_info.get(ATTR_SW_VERSION),
)
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True

View file

@ -13,8 +13,7 @@
"ups": {
"title": "Choose the UPS to Monitor",
"data": {
"alias": "Alias",
"resources": "Resources"
"alias": "Alias"
}
}
},

View file

@ -270,7 +270,7 @@ async def test_stale_options(hass):
data={
CONF_HOST: "mock",
CONF_PORT: "mock",
CONF_RESOURCES: ["battery.charge"],
CONF_RESOURCES: ["ups.load"],
},
options={CONF_RESOURCES: ["battery.charge"]},
)
@ -291,7 +291,7 @@ async def test_stale_options(hass):
entry = registry.async_get("sensor.ups1_battery_charge")
assert entry
assert entry.unique_id == f"{config_entry.entry_id}_battery.charge"
assert CONF_RESOURCES not in config_entry.data
assert config_entry.data[CONF_RESOURCES] == ["battery.charge"]
assert config_entry.options == {}
state = hass.states.get("sensor.ups1_battery_charge")