Add zeroconf discovery to HP Printer (#191064)

This commit is contained in:
Simone Chemelli
2026-11-11 18:51:59 +00:00
committed by GitHub
parent cd2c9e4b41
commit a0d43caec1
6 changed files with 201 additions and 15 deletions
@@ -2,7 +2,7 @@
from typing import Any, override
from aiohpprinter import HpPrinter, HpPrinterError
from aiohpprinter import HpPrinter, HpPrinterDevice, HpPrinterError
import probatio
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
@@ -16,6 +16,7 @@ from homeassistant.helpers.selector import (
NumberSelectorMode,
TextSelector,
)
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from .const import DOMAIN, SECTION_ADVANCED_SETTINGS
@@ -44,6 +45,9 @@ class HpPrinterConfigFlow(ConfigFlow, domain=DOMAIN):
MINOR_VERSION = 2
_host: str
_title: str
@override
async def async_step_user(
self, user_input: dict[str, Any] | None = None
@@ -57,17 +61,10 @@ class HpPrinterConfigFlow(ConfigFlow, domain=DOMAIN):
}
if CONF_PORT in data:
data[CONF_PORT] = int(data[CONF_PORT])
client = HpPrinter(
data[CONF_HOST],
async_get_clientsession(self.hass),
port=data.get(CONF_PORT),
ssl=data[CONF_SSL],
device = await self._async_get_device(
data[CONF_HOST], data.get(CONF_PORT), data[CONF_SSL]
)
try:
device = await client.device()
# Updates fail without the status endpoint, so check it too.
await client.status()
except HpPrinterError:
if device is None:
errors["base"] = "cannot_connect"
else:
if not device.serial_number:
@@ -86,3 +83,51 @@ class HpPrinterConfigFlow(ConfigFlow, domain=DOMAIN):
),
errors=errors,
)
@override
async def async_step_zeroconf(
self, discovery_info: ZeroconfServiceInfo
) -> ConfigFlowResult:
"""Handle a printer discovered via zeroconf."""
self._host = discovery_info.host
self._async_abort_entries_match({CONF_HOST: self._host})
device = await self._async_get_device(self._host, None, False)
if device is None:
return self.async_abort(reason="cannot_connect")
if not device.serial_number:
return self.async_abort(reason="missing_serial_number")
await self.async_set_unique_id(device.serial_number)
self._abort_if_unique_id_configured(updates={CONF_HOST: self._host})
self._title = device.make_and_model or self._host
self.context["title_placeholders"] = {"name": self._title}
return await self.async_step_zeroconf_confirm()
async def async_step_zeroconf_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm adding a discovered printer."""
if user_input is not None:
return self.async_create_entry(
title=self._title, data={CONF_HOST: self._host, CONF_SSL: False}
)
return self.async_show_form(
step_id="zeroconf_confirm",
description_placeholders={"name": self._title, "host": self._host},
)
async def _async_get_device(
self, host: str, port: int | None, ssl: bool
) -> HpPrinterDevice | None:
"""Return the printer's identity, or None if it cannot be reached."""
client = HpPrinter(host, async_get_clientsession(self.hass), port=port, ssl=ssl)
try:
device = await client.device()
# Updates fail without the status endpoint, so check it too.
await client.status()
except HpPrinterError:
return None
return device
@@ -10,5 +10,15 @@
"iot_class": "local_polling",
"loggers": ["aiohpprinter"],
"quality_scale": "bronze",
"requirements": ["aiohpprinter==3.7.0"]
"requirements": ["aiohpprinter==3.7.0"],
"zeroconf": [
{
"name": "hp*",
"type": "_ipp._tcp.local."
},
{
"name": "hp*",
"type": "_ipps._tcp.local."
}
]
}
@@ -52,8 +52,8 @@ rules:
# Gold
devices: done
diagnostics: done
discovery-update-info: todo
discovery: todo
discovery-update-info: done
discovery: done
docs-data-update: done
docs-examples: done
docs-known-limitations: done
@@ -2,11 +2,13 @@
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"missing_serial_number": "The printer did not report a serial number."
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]"
},
"flow_title": "{name}",
"step": {
"user": {
"data": {
@@ -28,6 +30,9 @@
"name": "Advanced settings"
}
}
},
"zeroconf_confirm": {
"description": "Do you want to add the HP printer {name} at {host}?"
}
}
},
+8
View File
@@ -752,11 +752,19 @@ ZEROCONF = {
},
],
"_ipp._tcp.local.": [
{
"domain": "hp_printer",
"name": "hp*",
},
{
"domain": "ipp",
},
],
"_ipps._tcp.local.": [
{
"domain": "hp_printer",
"name": "hp*",
},
{
"domain": "ipp",
},
+119 -1
View File
@@ -1,6 +1,7 @@
"""Test the HP Printer config flow."""
from dataclasses import replace
from ipaddress import ip_address
from unittest.mock import AsyncMock
from aiohpprinter import (
@@ -15,15 +16,28 @@ import pytest
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.components.hp_printer.const import DOMAIN, SECTION_ADVANCED_SETTINGS
from homeassistant.config_entries import SOURCE_USER
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SSL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from .conftest import HOST, SERIAL_NUMBER, TITLE
USER_INPUT = {CONF_HOST: HOST, SECTION_ADVANCED_SETTINGS: {CONF_SSL: False}}
NEW_HOST = "192.168.1.13"
ZEROCONF_DISCOVERY = ZeroconfServiceInfo(
ip_address=ip_address(NEW_HOST),
ip_addresses=[ip_address(NEW_HOST)],
hostname="HPA1B2C3.local.",
name="HP OfficeJet Pro 9020 series [A1B2C3]._ipp._tcp.local.",
port=631,
type="_ipp._tcp.local.",
properties={},
)
@pytest.mark.usefixtures("mock_hp_printer")
async def test_user_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
@@ -163,3 +177,107 @@ async def test_user_flow_ssl_and_port(
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {CONF_HOST: HOST, CONF_SSL: True, CONF_PORT: 8443}
assert result["result"].unique_id == SERIAL_NUMBER
@pytest.mark.usefixtures("mock_hp_printer")
async def test_zeroconf_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test a printer discovered via zeroconf is added after confirmation."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DISCOVERY
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_confirm"
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == TITLE
assert result["data"] == {CONF_HOST: NEW_HOST, CONF_SSL: False}
assert result["result"].unique_id == SERIAL_NUMBER
assert mock_setup_entry.call_count == 1
@pytest.mark.usefixtures("mock_setup_entry")
async def test_zeroconf_flow_title_falls_back_to_host(
hass: HomeAssistant,
mock_hp_printer: AsyncMock,
mock_device: HpPrinterDevice,
) -> None:
"""Test a discovered printer is named after its host when it has no model."""
mock_hp_printer.device.return_value = replace(mock_device, make_and_model=None)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DISCOVERY
)
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == NEW_HOST
assert result["result"].unique_id == SERIAL_NUMBER
@pytest.mark.parametrize(
("device_changes", "side_effect", "reason"),
[
pytest.param(
{}, HpPrinterConnectionError, "cannot_connect", id="cannot_connect"
),
pytest.param(
{"serial_number": None}, None, "missing_serial_number", id="no_serial"
),
],
)
async def test_zeroconf_flow_abort(
hass: HomeAssistant,
mock_hp_printer: AsyncMock,
mock_device: HpPrinterDevice,
device_changes: dict[str, str | None],
side_effect: type[HpPrinterError] | None,
reason: str,
) -> None:
"""Test the zeroconf flow aborts when the printer cannot be identified."""
mock_hp_printer.device.return_value = replace(mock_device, **device_changes)
mock_hp_printer.device.side_effect = side_effect
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DISCOVERY
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
async def test_zeroconf_flow_updates_host(
hass: HomeAssistant,
mock_hp_printer: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test rediscovering a configured printer at a new host updates the entry."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DISCOVERY
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config_entry.data == {CONF_HOST: NEW_HOST, CONF_SSL: False}
async def test_zeroconf_flow_known_host(
hass: HomeAssistant,
mock_hp_printer: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test a printer at an already configured host is not probed again."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=replace(ZEROCONF_DISCOVERY, ip_address=ip_address(HOST)),
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
mock_hp_printer.device.assert_not_called()