diff --git a/.coveragerc b/.coveragerc index 1cf45057dc9..ccb0135b4a3 100644 --- a/.coveragerc +++ b/.coveragerc @@ -511,6 +511,9 @@ omit = homeassistant/components/insteon/schemas.py homeassistant/components/insteon/switch.py homeassistant/components/insteon/utils.py + homeassistant/components/intellifire/__init__.py + homeassistant/components/intellifire/coordinator.py + homeassistant/components/intellifire/binary_sensor.py homeassistant/components/incomfort/* homeassistant/components/intesishome/* homeassistant/components/ios/* diff --git a/CODEOWNERS b/CODEOWNERS index 75c9465f6d6..52ee23898ed 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -444,6 +444,8 @@ homeassistant/components/insteon/* @teharris1 tests/components/insteon/* @teharris1 homeassistant/components/integration/* @dgomes tests/components/integration/* @dgomes +homeassistant/components/intellifire/* @jeeftor +tests/components/intellifire/* @jeeftor homeassistant/components/intent/* @home-assistant/core tests/components/intent/* @home-assistant/core homeassistant/components/intesishome/* @jnimmo diff --git a/homeassistant/components/intellifire/__init__.py b/homeassistant/components/intellifire/__init__.py new file mode 100644 index 00000000000..26fcb92bffc --- /dev/null +++ b/homeassistant/components/intellifire/__init__.py @@ -0,0 +1,41 @@ +"""The IntelliFire integration.""" +from __future__ import annotations + +from intellifire4py import IntellifireAsync + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_HOST, Platform +from homeassistant.core import HomeAssistant + +from .const import DOMAIN, LOGGER +from .coordinator import IntellifireDataUpdateCoordinator + +PLATFORMS = [Platform.BINARY_SENSOR] + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Set up IntelliFire from a config entry.""" + LOGGER.debug("Setting up config entry: %s", entry.unique_id) + + # Define the API Object + api_object = IntellifireAsync(entry.data[CONF_HOST]) + + # Define the update coordinator + coordinator = IntellifireDataUpdateCoordinator( + hass=hass, + api=api_object, + ) + await coordinator.async_config_entry_first_refresh() + hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator + + hass.config_entries.async_setup_platforms(entry, PLATFORMS) + + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Unload a config entry.""" + if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): + hass.data[DOMAIN].pop(entry.entry_id) + + return unload_ok diff --git a/homeassistant/components/intellifire/binary_sensor.py b/homeassistant/components/intellifire/binary_sensor.py new file mode 100644 index 00000000000..139087a6ec7 --- /dev/null +++ b/homeassistant/components/intellifire/binary_sensor.py @@ -0,0 +1,106 @@ +"""Support for IntelliFire Binary Sensors.""" +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass + +from intellifire4py import IntellifirePollData + +from homeassistant.components.binary_sensor import ( + BinarySensorEntity, + BinarySensorEntityDescription, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from . import IntellifireDataUpdateCoordinator +from .const import DOMAIN + + +@dataclass +class IntellifireSensorEntityDescriptionMixin: + """Mixin for required keys.""" + + value_fn: Callable[[IntellifirePollData], bool] + + +@dataclass +class IntellifireBinarySensorEntityDescription( + BinarySensorEntityDescription, IntellifireSensorEntityDescriptionMixin +): + """Describes a binary sensor entity.""" + + +INTELLIFIRE_BINARY_SENSORS: tuple[IntellifireBinarySensorEntityDescription, ...] = ( + IntellifireBinarySensorEntityDescription( + key="on_off", # This is the sensor name + name="Flame", # This is the human readable name + icon="mdi:fire", + value_fn=lambda data: data.is_on, + ), + IntellifireBinarySensorEntityDescription( + key="timer_on", + name="Timer On", + icon="mdi:camera-timer", + value_fn=lambda data: data.timer_on, + ), + IntellifireBinarySensorEntityDescription( + key="pilot_light_on", + name="Pilot Light On", + icon="mdi:fire-alert", + value_fn=lambda data: data.pilot_on, + ), + IntellifireBinarySensorEntityDescription( + key="thermostat_on", + name="Thermostat On", + icon="mdi:home-thermometer-outline", + value_fn=lambda data: data.thermostat_on, + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Set up a IntelliFire On/Off Sensor.""" + coordinator: IntellifireDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] + + async_add_entities( + IntellifireBinarySensor( + coordinator=coordinator, entry_id=entry.entry_id, description=description + ) + for description in INTELLIFIRE_BINARY_SENSORS + ) + + +class IntellifireBinarySensor(CoordinatorEntity, BinarySensorEntity): + """A semi-generic wrapper around Binary Sensor entities for IntelliFire.""" + + # Define types + coordinator: IntellifireDataUpdateCoordinator + entity_description: IntellifireBinarySensorEntityDescription + + def __init__( + self, + coordinator: IntellifireDataUpdateCoordinator, + entry_id: str, + description: IntellifireBinarySensorEntityDescription, + ) -> None: + """Class initializer.""" + super().__init__(coordinator=coordinator) + self.entity_description = description + + # Set the Display name the User will see + self._attr_name = f"Fireplace {description.name}" + self._attr_unique_id = f"{description.key}_{coordinator.api.data.serial}" + # Configure the Device Info + self._attr_device_info = self.coordinator.device_info + + @property + def is_on(self) -> bool: + """Use this to get the correct value.""" + return self.entity_description.value_fn(self.coordinator.api.data) diff --git a/homeassistant/components/intellifire/config_flow.py b/homeassistant/components/intellifire/config_flow.py new file mode 100644 index 00000000000..f47b434ae94 --- /dev/null +++ b/homeassistant/components/intellifire/config_flow.py @@ -0,0 +1,68 @@ +"""Config flow for IntelliFire integration.""" +from __future__ import annotations + +from typing import Any + +from aiohttp import ClientConnectionError +from intellifire4py import IntellifireAsync +import voluptuous as vol + +from homeassistant import config_entries +from homeassistant.const import CONF_HOST +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResult +from homeassistant.exceptions import HomeAssistantError + +from .const import DOMAIN + +STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str}) + + +async def validate_input(hass: HomeAssistant, host: str) -> str: + """Validate the user input allows us to connect. + + Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user. + """ + api = IntellifireAsync(host) + await api.poll() + + # Return the serial number which will be used to calculate a unique ID for the device/sensors + return api.data.serial + + +class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): + """Handle a config flow for IntelliFire.""" + + VERSION = 1 + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + """Handle the initial step.""" + if user_input is None: + return self.async_show_form( + step_id="user", data_schema=STEP_USER_DATA_SCHEMA + ) + errors = {} + + try: + serial = await validate_input(self.hass, user_input[CONF_HOST]) + except (ConnectionError, ClientConnectionError): + errors["base"] = "cannot_connect" + else: + await self.async_set_unique_id(serial) + self._abort_if_unique_id_configured( + updates={CONF_HOST: user_input[CONF_HOST]} + ) + + return self.async_create_entry( + title="Fireplace", + data={CONF_HOST: user_input[CONF_HOST]}, + ) + return self.async_show_form( + step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors + ) + + +class CannotConnect(HomeAssistantError): + """Error to indicate we cannot connect.""" diff --git a/homeassistant/components/intellifire/const.py b/homeassistant/components/intellifire/const.py new file mode 100644 index 00000000000..d4aba5d2f8a --- /dev/null +++ b/homeassistant/components/intellifire/const.py @@ -0,0 +1,8 @@ +"""Constants for the IntelliFire integration.""" +from __future__ import annotations + +import logging + +DOMAIN = "intellifire" + +LOGGER = logging.getLogger(__package__) diff --git a/homeassistant/components/intellifire/coordinator.py b/homeassistant/components/intellifire/coordinator.py new file mode 100644 index 00000000000..be5e3110cac --- /dev/null +++ b/homeassistant/components/intellifire/coordinator.py @@ -0,0 +1,54 @@ +"""The IntelliFire integration.""" +from __future__ import annotations + +from datetime import timedelta + +from aiohttp import ClientConnectionError +from async_timeout import timeout +from intellifire4py import IntellifireAsync, IntellifirePollData + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity import DeviceInfo +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed + +from .const import DOMAIN, LOGGER + + +class IntellifireDataUpdateCoordinator(DataUpdateCoordinator[IntellifirePollData]): + """Class to manage the polling of the fireplace API.""" + + def __init__(self, hass: HomeAssistant, api: IntellifireAsync) -> None: + """Initialize the Coordinator.""" + super().__init__( + hass, + LOGGER, + name=DOMAIN, + update_interval=timedelta(seconds=15), + update_method=self._async_update_data, + ) + self._api = api + + async def _async_update_data(self): + LOGGER.debug("Calling update loop on IntelliFire") + async with timeout(100): + try: + await self._api.poll() + except (ConnectionError, ClientConnectionError) as exception: + raise UpdateFailed from exception + return self._api.data + + @property + def api(self): + """Return the API pointer.""" + return self._api + + @property + def device_info(self): + """Return the device info.""" + return DeviceInfo( + manufacturer="Hearth and Home", + model="IFT-WFM", + name="IntelliFire Fireplace", + identifiers={("IntelliFire", f"{self.api.data.serial}]")}, + sw_version=self.api.data.fw_ver_str, + ) diff --git a/homeassistant/components/intellifire/manifest.json b/homeassistant/components/intellifire/manifest.json new file mode 100644 index 00000000000..ab7a814693f --- /dev/null +++ b/homeassistant/components/intellifire/manifest.json @@ -0,0 +1,14 @@ +{ + "domain": "intellifire", + "name": "IntelliFire", + "config_flow": true, + "documentation": "https://www.home-assistant.io/integrations/intellifire", + "requirements": [ + "intellifire4py==0.4.3" + ], + "dependencies": [], + "codeowners": [ + "@jeeftor" + ], + "iot_class": "local_polling" +} \ No newline at end of file diff --git a/homeassistant/components/intellifire/strings.json b/homeassistant/components/intellifire/strings.json new file mode 100644 index 00000000000..06315a7fc50 --- /dev/null +++ b/homeassistant/components/intellifire/strings.json @@ -0,0 +1,18 @@ +{ + "config": { + "step": { + "user": { + "data": { + "host": "[%key:common::config_flow::data::host%]" + } + } + }, + "error": { + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "unknown": "[%key:common::config_flow::error::unknown%]" + }, + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" + } + } +} diff --git a/homeassistant/components/intellifire/translations/en.json b/homeassistant/components/intellifire/translations/en.json new file mode 100644 index 00000000000..0a4ba36e285 --- /dev/null +++ b/homeassistant/components/intellifire/translations/en.json @@ -0,0 +1,18 @@ +{ + "config": { + "abort": { + "already_configured": "Device is already configured" + }, + "error": { + "cannot_connect": "Failed to connect", + "unknown": "Unexpected error" + }, + "step": { + "user": { + "data": { + "host": "Host" + } + } + } + } +} \ No newline at end of file diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index fbc4035d230..e995dd6ad87 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -150,6 +150,7 @@ FLOWS = [ "icloud", "ifttt", "insteon", + "intellifire", "ios", "iotawatt", "ipma", diff --git a/requirements_all.txt b/requirements_all.txt index 3602d131a17..8f9b7e1eafa 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -913,6 +913,9 @@ influxdb-client==1.24.0 # homeassistant.components.influxdb influxdb==5.3.1 +# homeassistant.components.intellifire +intellifire4py==0.4.3 + # homeassistant.components.iotawatt iotawattpy==0.1.0 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index ab185bb285a..f47cbac7ede 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -585,6 +585,9 @@ influxdb-client==1.24.0 # homeassistant.components.influxdb influxdb==5.3.1 +# homeassistant.components.intellifire +intellifire4py==0.4.3 + # homeassistant.components.iotawatt iotawattpy==0.1.0 diff --git a/tests/components/intellifire/__init__.py b/tests/components/intellifire/__init__.py new file mode 100644 index 00000000000..f655ccc2fa4 --- /dev/null +++ b/tests/components/intellifire/__init__.py @@ -0,0 +1 @@ +"""Tests for the IntelliFire integration.""" diff --git a/tests/components/intellifire/test_config_flow.py b/tests/components/intellifire/test_config_flow.py new file mode 100644 index 00000000000..44f31ab32c5 --- /dev/null +++ b/tests/components/intellifire/test_config_flow.py @@ -0,0 +1,113 @@ +"""Test the IntelliFire config flow.""" +from unittest.mock import Mock, patch + +from homeassistant import config_entries +from homeassistant.components.intellifire.config_flow import validate_input +from homeassistant.components.intellifire.const import DOMAIN +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_FORM + + +async def test_form(hass: HomeAssistant) -> None: + """Test we get the form.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] == RESULT_TYPE_FORM + assert result["errors"] is None + + with patch( + "homeassistant.components.intellifire.config_flow.validate_input", + return_value={ + "title": "Living Room Fireplace", + "type": "Fireplace", + "serial": "abcd1234", + "host": "1.1.1.1", + }, + ), patch( + "homeassistant.components.intellifire.async_setup_entry", return_value=True + ) as mock_setup_entry: + print("mock_setup_entry", mock_setup_entry) + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "host": "1.1.1.1", + }, + ) + await hass.async_block_till_done() + + assert result2["type"] == RESULT_TYPE_CREATE_ENTRY + assert result2["title"] == "Fireplace" + assert result2["data"] == {"host": "1.1.1.1"} + + +async def test_form_cannot_connect(hass: HomeAssistant) -> None: + """Test we handle cannot connect error.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + with patch( + "intellifire4py.IntellifireAsync.poll", + side_effect=ConnectionError, + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "host": "1.1.1.1", + }, + ) + + assert result2["type"] == RESULT_TYPE_FORM + assert result2["errors"] == {"base": "cannot_connect"} + + +async def test_form_good(hass: HomeAssistant) -> None: + """Test we handle cannot connect error.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + with patch( + "intellifire4py.IntellifireAsync.poll", + side_effect=ConnectionError, + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "host": "1.1.1.1", + }, + ) + + assert result2["type"] == RESULT_TYPE_FORM + assert result2["errors"] == {"base": "cannot_connect"} + + +async def test_validate_input(hass: HomeAssistant) -> None: + """Test for the ideal case.""" + # Define a mock object + data_mock = Mock() + data_mock.serial = "12345" + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + with patch( + "homeassistant.components.intellifire.config_flow.validate_input", + return_value="abcd1234", + ), patch("intellifire4py.IntellifireAsync.poll", return_value=3), patch( + "intellifire4py.IntellifireAsync.data", return_value="something" + ), patch( + "intellifire4py.IntellifireAsync.data.serial", return_value="1234" + ), patch( + "intellifire4py.intellifire_async.IntellifireAsync", return_value="1111" + ), patch( + "intellifire4py.IntellifireAsync", return_value=True + ), patch( + "intellifire4py.model.IntellifirePollData", new=data_mock + ) as mobj: + assert mobj.serial == "12345" + + result = await validate_input(hass, {"host": "127.0.0.1"}) + + assert result() == "1234"