Add zeroconf discovery support to Brother Printer integration (#30959)

* Add zeroconf discovery support

* Fix data for config_entry

* Add sting for zeroconf confirm dialog

* Add and fix tests

* Fix pylint errors

* Suggested changes

* Tests

* Remove unnecessary object

* Add error handling

* Remove unnecessary objects

* Suggested change

* Suggested change

* Use core interfaces for tests
This commit is contained in:
Maciej Bieniek 2020-01-22 20:34:11 +01:00 committed by Paulus Schoutsen
parent 4015a046d2
commit 4c27d6b9aa
5 changed files with 192 additions and 43 deletions

View file

@ -34,6 +34,11 @@ class BrotherConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
def __init__(self):
"""Initialize."""
self.brother = None
self.host = None
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
@ -64,6 +69,58 @@ class BrotherConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)
async def async_step_zeroconf(self, user_input=None):
"""Handle zeroconf discovery."""
if user_input is None:
return self.async_abort(reason="connection_error")
if not user_input.get("name") or not user_input["name"].startswith("Brother"):
return self.async_abort(reason="not_brother_printer")
# Hostname is format: brother.local.
self.host = user_input["hostname"].rstrip(".")
self.brother = Brother(self.host)
try:
await self.brother.async_update()
except (ConnectionError, SnmpError, UnsupportedModel):
return self.async_abort(reason="connection_error")
# Check if already configured
await self.async_set_unique_id(self.brother.serial.lower())
self._abort_if_unique_id_configured()
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
self.context.update(
{
"title_placeholders": {
"serial_number": self.brother.serial,
"model": self.brother.model,
}
}
)
return await self.async_step_zeroconf_confirm()
async def async_step_zeroconf_confirm(self, user_input=None):
"""Handle a flow initiated by zeroconf."""
if user_input is not None:
title = f"{self.brother.model} {self.brother.serial}"
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
return self.async_create_entry(
title=title,
data={CONF_HOST: self.host, CONF_TYPE: user_input[CONF_TYPE]},
)
return self.async_show_form(
step_id="zeroconf_confirm",
data_schema=vol.Schema(
{vol.Optional(CONF_TYPE, default="laser"): vol.In(PRINTER_TYPES)}
),
description_placeholders={
"serial_number": self.brother.serial,
"model": self.brother.model,
},
)
class InvalidHost(exceptions.HomeAssistantError):
"""Error to indicate that hostname/IP address is invalid."""