Use current config entry standards for SimpliSafe (#57141)

* Use current config entry standards for SimpliSafe

* Include tests
This commit is contained in:
Aaron Bach 2021-10-08 13:22:29 -06:00 committed by GitHub
parent 4104a3dee6
commit fe3b5e8804
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 40 deletions

View File

@ -130,12 +130,12 @@ async def async_get_client_id(hass: HomeAssistant) -> str:
async def async_register_base_station( async def async_register_base_station(
hass: HomeAssistant, system: SystemV2 | SystemV3, config_entry_id: str hass: HomeAssistant, entry: ConfigEntry, system: SystemV2 | SystemV3
) -> None: ) -> None:
"""Register a new bridge.""" """Register a new bridge."""
device_registry = await dr.async_get_registry(hass) device_registry = await dr.async_get_registry(hass)
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=config_entry_id, config_entry_id=entry.entry_id,
identifiers={(DOMAIN, system.serial)}, identifiers={(DOMAIN, system.serial)},
manufacturer="SimpliSafe", manufacturer="SimpliSafe",
model=system.version, model=system.version,
@ -144,36 +144,34 @@ async def async_register_base_station(
@callback @callback
def _async_standardize_config_entry( def _async_standardize_config_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
"""Bring a config entry up to current standards.""" """Bring a config entry up to current standards."""
if CONF_PASSWORD not in config_entry.data: if CONF_PASSWORD not in entry.data:
raise ConfigEntryAuthFailed("Config schema change requires re-authentication") raise ConfigEntryAuthFailed("Config schema change requires re-authentication")
entry_updates = {} entry_updates = {}
if not config_entry.unique_id: if not entry.unique_id:
# If the config entry doesn't already have a unique ID, set one: # If the config entry doesn't already have a unique ID, set one:
entry_updates["unique_id"] = config_entry.data[CONF_USERNAME] entry_updates["unique_id"] = entry.data[CONF_USERNAME]
if CONF_CODE in config_entry.data: if CONF_CODE in entry.data:
# If an alarm code was provided as part of configuration.yaml, pop it out of # If an alarm code was provided as part of configuration.yaml, pop it out of
# the config entry's data and move it to options: # the config entry's data and move it to options:
data = {**config_entry.data} data = {**entry.data}
entry_updates["data"] = data entry_updates["data"] = data
entry_updates["options"] = { entry_updates["options"] = {
**config_entry.options, **entry.options,
CONF_CODE: data.pop(CONF_CODE), CONF_CODE: data.pop(CONF_CODE),
} }
if entry_updates: if entry_updates:
hass.config_entries.async_update_entry(config_entry, **entry_updates) hass.config_entries.async_update_entry(entry, **entry_updates)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up SimpliSafe as config entry.""" """Set up SimpliSafe as config entry."""
hass.data.setdefault(DOMAIN, {DATA_CLIENT: {}}) hass.data.setdefault(DOMAIN, {DATA_CLIENT: {}})
hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = [] hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] = []
_async_standardize_config_entry(hass, config_entry) _async_standardize_config_entry(hass, entry)
_verify_domain_control = verify_domain_control(hass, DOMAIN) _verify_domain_control = verify_domain_control(hass, DOMAIN)
@ -182,8 +180,8 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
try: try:
api = await get_api( api = await get_api(
config_entry.data[CONF_USERNAME], entry.data[CONF_USERNAME],
config_entry.data[CONF_PASSWORD], entry.data[CONF_PASSWORD],
client_id=client_id, client_id=client_id,
session=websession, session=websession,
) )
@ -193,15 +191,15 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
LOGGER.error("Config entry failed: %s", err) LOGGER.error("Config entry failed: %s", err)
raise ConfigEntryNotReady from err raise ConfigEntryNotReady from err
simplisafe = SimpliSafe(hass, config_entry, api) simplisafe = SimpliSafe(hass, entry, api)
try: try:
await simplisafe.async_init() await simplisafe.async_init()
except SimplipyError as err: except SimplipyError as err:
raise ConfigEntryNotReady from err raise ConfigEntryNotReady from err
hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = simplisafe hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] = simplisafe
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
@callback @callback
def verify_system_exists( def verify_system_exists(
@ -292,7 +290,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
): ):
async_register_admin_service(hass, DOMAIN, service, method, schema=schema) async_register_admin_service(hass, DOMAIN, service, method, schema=schema)
config_entry.async_on_unload(config_entry.add_update_listener(async_reload_entry)) entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True return True
@ -306,25 +304,25 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return unload_ok return unload_ok
async def async_reload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> None: async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update.""" """Handle an options update."""
await hass.config_entries.async_reload(config_entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)
class SimpliSafe: class SimpliSafe:
"""Define a SimpliSafe data object.""" """Define a SimpliSafe data object."""
def __init__( def __init__(self, hass: HomeAssistant, entry: ConfigEntry, api: API) -> None:
self, hass: HomeAssistant, config_entry: ConfigEntry, api: API
) -> None:
"""Initialize.""" """Initialize."""
self._api = api self._api = api
self._hass = hass self._hass = hass
self._system_notifications: dict[int, set[SystemNotification]] = {} self._system_notifications: dict[int, set[SystemNotification]] = {}
self.config_entry = config_entry self.entry = entry
self.coordinator: DataUpdateCoordinator | None = None
self.systems: dict[int, SystemV2 | SystemV3] = {} self.systems: dict[int, SystemV2 | SystemV3] = {}
# This will get filled in by async_init:
self.coordinator: DataUpdateCoordinator | None = None
@callback @callback
def _async_process_new_notifications(self, system: SystemV2 | SystemV3) -> None: def _async_process_new_notifications(self, system: SystemV2 | SystemV3) -> None:
"""Act on any new system notifications.""" """Act on any new system notifications."""
@ -369,15 +367,13 @@ class SimpliSafe:
self._system_notifications[system.system_id] = set() self._system_notifications[system.system_id] = set()
self._hass.async_create_task( self._hass.async_create_task(
async_register_base_station( async_register_base_station(self._hass, self.entry, system)
self._hass, system, self.config_entry.entry_id
)
) )
self.coordinator = DataUpdateCoordinator( self.coordinator = DataUpdateCoordinator(
self._hass, self._hass,
LOGGER, LOGGER,
name=self.config_entry.data[CONF_USERNAME], name=self.entry.data[CONF_USERNAME],
update_interval=DEFAULT_SCAN_INTERVAL, update_interval=DEFAULT_SCAN_INTERVAL,
update_method=self.async_update, update_method=self.async_update,
) )

View File

@ -70,7 +70,7 @@ class SimpliSafeAlarm(SimpliSafeEntity, AlarmControlPanelEntity):
"""Initialize the SimpliSafe alarm.""" """Initialize the SimpliSafe alarm."""
super().__init__(simplisafe, system, "Alarm Control Panel") super().__init__(simplisafe, system, "Alarm Control Panel")
if code := self._simplisafe.config_entry.options.get(CONF_CODE): if code := self._simplisafe.entry.options.get(CONF_CODE):
if code.isdigit(): if code.isdigit():
self._attr_code_format = FORMAT_NUMBER self._attr_code_format = FORMAT_NUMBER
else: else:
@ -98,10 +98,10 @@ class SimpliSafeAlarm(SimpliSafeEntity, AlarmControlPanelEntity):
@callback @callback
def _is_code_valid(self, code: str | None, state: str) -> bool: def _is_code_valid(self, code: str | None, state: str) -> bool:
"""Validate that a code matches the required one.""" """Validate that a code matches the required one."""
if not self._simplisafe.config_entry.options.get(CONF_CODE): if not self._simplisafe.entry.options.get(CONF_CODE):
return True return True
if not code or code != self._simplisafe.config_entry.options[CONF_CODE]: if not code or code != self._simplisafe.entry.options[CONF_CODE]:
LOGGER.warning( LOGGER.warning(
"Incorrect alarm code entered (target state: %s): %s", state, code "Incorrect alarm code entered (target state: %s): %s", state, code
) )

View File

@ -59,19 +59,19 @@ async def test_options_flow(hass):
"""Test config flow options.""" """Test config flow options."""
conf = {CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"} conf = {CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"}
config_entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
unique_id="abcde12345", unique_id="abcde12345",
data=conf, data=conf,
options={CONF_CODE: "1234"}, options={CONF_CODE: "1234"},
) )
config_entry.add_to_hass(hass) entry.add_to_hass(hass)
with patch( with patch(
"homeassistant.components.simplisafe.async_setup_entry", return_value=True "homeassistant.components.simplisafe.async_setup_entry", return_value=True
): ):
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(entry.entry_id)
result = await hass.config_entries.options.async_init(config_entry.entry_id) result = await hass.config_entries.options.async_init(entry.entry_id)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "init" assert result["step_id"] == "init"
@ -81,7 +81,7 @@ async def test_options_flow(hass):
) )
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert config_entry.options == {CONF_CODE: "4321"} assert entry.options == {CONF_CODE: "4321"}
async def test_show_form(hass): async def test_show_form(hass):