Initial commit

This commit is contained in:
2025-12-24 16:12:45 -05:00
committed by GitHub
commit 84b312fd46
31 changed files with 1043 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
"""
Custom integration to integrate integration_blueprint with Home Assistant.
For more details about this integration, please refer to
https://github.com/ludeeus/integration_blueprint
"""
from __future__ import annotations
from datetime import timedelta
from typing import TYPE_CHECKING
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.loader import async_get_loaded_integration
from .api import IntegrationBlueprintApiClient
from .const import DOMAIN, LOGGER
from .coordinator import BlueprintDataUpdateCoordinator
from .data import IntegrationBlueprintData
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant
from .data import IntegrationBlueprintConfigEntry
PLATFORMS: list[Platform] = [
Platform.SENSOR,
Platform.BINARY_SENSOR,
Platform.SWITCH,
]
# https://developers.home-assistant.io/docs/config_entries_index/#setting-up-an-entry
async def async_setup_entry(
hass: HomeAssistant,
entry: IntegrationBlueprintConfigEntry,
) -> bool:
"""Set up this integration using UI."""
coordinator = BlueprintDataUpdateCoordinator(
hass=hass,
logger=LOGGER,
name=DOMAIN,
update_interval=timedelta(hours=1),
)
entry.runtime_data = IntegrationBlueprintData(
client=IntegrationBlueprintApiClient(
username=entry.data[CONF_USERNAME],
password=entry.data[CONF_PASSWORD],
session=async_get_clientsession(hass),
),
integration=async_get_loaded_integration(hass, entry.domain),
coordinator=coordinator,
)
# https://developers.home-assistant.io/docs/integration_fetching_data#coordinated-single-api-poll-for-data-for-all-entities
await coordinator.async_config_entry_first_refresh()
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_unload_entry(
hass: HomeAssistant,
entry: IntegrationBlueprintConfigEntry,
) -> bool:
"""Handle removal of an entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
async def async_reload_entry(
hass: HomeAssistant,
entry: IntegrationBlueprintConfigEntry,
) -> None:
"""Reload config entry."""
await hass.config_entries.async_reload(entry.entry_id)

View File

@@ -0,0 +1,101 @@
"""Sample API Client."""
from __future__ import annotations
import socket
from typing import Any
import aiohttp
import async_timeout
class IntegrationBlueprintApiClientError(Exception):
"""Exception to indicate a general API error."""
class IntegrationBlueprintApiClientCommunicationError(
IntegrationBlueprintApiClientError,
):
"""Exception to indicate a communication error."""
class IntegrationBlueprintApiClientAuthenticationError(
IntegrationBlueprintApiClientError,
):
"""Exception to indicate an authentication error."""
def _verify_response_or_raise(response: aiohttp.ClientResponse) -> None:
"""Verify that the response is valid."""
if response.status in (401, 403):
msg = "Invalid credentials"
raise IntegrationBlueprintApiClientAuthenticationError(
msg,
)
response.raise_for_status()
class IntegrationBlueprintApiClient:
"""Sample API Client."""
def __init__(
self,
username: str,
password: str,
session: aiohttp.ClientSession,
) -> None:
"""Sample API Client."""
self._username = username
self._password = password
self._session = session
async def async_get_data(self) -> Any:
"""Get data from the API."""
return await self._api_wrapper(
method="get",
url="https://jsonplaceholder.typicode.com/posts/1",
)
async def async_set_title(self, value: str) -> Any:
"""Get data from the API."""
return await self._api_wrapper(
method="patch",
url="https://jsonplaceholder.typicode.com/posts/1",
data={"title": value},
headers={"Content-type": "application/json; charset=UTF-8"},
)
async def _api_wrapper(
self,
method: str,
url: str,
data: dict | None = None,
headers: dict | None = None,
) -> Any:
"""Get information from the API."""
try:
async with async_timeout.timeout(10):
response = await self._session.request(
method=method,
url=url,
headers=headers,
json=data,
)
_verify_response_or_raise(response)
return await response.json()
except TimeoutError as exception:
msg = f"Timeout error fetching information - {exception}"
raise IntegrationBlueprintApiClientCommunicationError(
msg,
) from exception
except (aiohttp.ClientError, socket.gaierror) as exception:
msg = f"Error fetching information - {exception}"
raise IntegrationBlueprintApiClientCommunicationError(
msg,
) from exception
except Exception as exception: # pylint: disable=broad-except
msg = f"Something really wrong happened! - {exception}"
raise IntegrationBlueprintApiClientError(
msg,
) from exception

View File

@@ -0,0 +1,61 @@
"""Binary sensor platform for integration_blueprint."""
from __future__ import annotations
from typing import TYPE_CHECKING
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from .entity import IntegrationBlueprintEntity
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .coordinator import BlueprintDataUpdateCoordinator
from .data import IntegrationBlueprintConfigEntry
ENTITY_DESCRIPTIONS = (
BinarySensorEntityDescription(
key="integration_blueprint",
name="Integration Blueprint Binary Sensor",
device_class=BinarySensorDeviceClass.CONNECTIVITY,
),
)
async def async_setup_entry(
hass: HomeAssistant, # noqa: ARG001 Unused function argument: `hass`
entry: IntegrationBlueprintConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the binary_sensor platform."""
async_add_entities(
IntegrationBlueprintBinarySensor(
coordinator=entry.runtime_data.coordinator,
entity_description=entity_description,
)
for entity_description in ENTITY_DESCRIPTIONS
)
class IntegrationBlueprintBinarySensor(IntegrationBlueprintEntity, BinarySensorEntity):
"""integration_blueprint binary_sensor class."""
def __init__(
self,
coordinator: BlueprintDataUpdateCoordinator,
entity_description: BinarySensorEntityDescription,
) -> None:
"""Initialize the binary_sensor class."""
super().__init__(coordinator)
self.entity_description = entity_description
@property
def is_on(self) -> bool:
"""Return true if the binary_sensor is on."""
return self.coordinator.data.get("title", "") == "foo"

View File

@@ -0,0 +1,89 @@
"""Adds config flow for Blueprint."""
from __future__ import annotations
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import selector
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from slugify import slugify
from .api import (
IntegrationBlueprintApiClient,
IntegrationBlueprintApiClientAuthenticationError,
IntegrationBlueprintApiClientCommunicationError,
IntegrationBlueprintApiClientError,
)
from .const import DOMAIN, LOGGER
class BlueprintFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Config flow for Blueprint."""
VERSION = 1
async def async_step_user(
self,
user_input: dict | None = None,
) -> config_entries.ConfigFlowResult:
"""Handle a flow initialized by the user."""
_errors = {}
if user_input is not None:
try:
await self._test_credentials(
username=user_input[CONF_USERNAME],
password=user_input[CONF_PASSWORD],
)
except IntegrationBlueprintApiClientAuthenticationError as exception:
LOGGER.warning(exception)
_errors["base"] = "auth"
except IntegrationBlueprintApiClientCommunicationError as exception:
LOGGER.error(exception)
_errors["base"] = "connection"
except IntegrationBlueprintApiClientError as exception:
LOGGER.exception(exception)
_errors["base"] = "unknown"
else:
await self.async_set_unique_id(
## Do NOT use this in production code
## The unique_id should never be something that can change
## https://developers.home-assistant.io/docs/config_entries_config_flow_handler#unique-ids
unique_id=slugify(user_input[CONF_USERNAME])
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=user_input[CONF_USERNAME],
data=user_input,
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(
CONF_USERNAME,
default=(user_input or {}).get(CONF_USERNAME, vol.UNDEFINED),
): selector.TextSelector(
selector.TextSelectorConfig(
type=selector.TextSelectorType.TEXT,
),
),
vol.Required(CONF_PASSWORD): selector.TextSelector(
selector.TextSelectorConfig(
type=selector.TextSelectorType.PASSWORD,
),
),
},
),
errors=_errors,
)
async def _test_credentials(self, username: str, password: str) -> None:
"""Validate credentials."""
client = IntegrationBlueprintApiClient(
username=username,
password=password,
session=async_create_clientsession(self.hass),
)
await client.async_get_data()

View File

@@ -0,0 +1,8 @@
"""Constants for integration_blueprint."""
from logging import Logger, getLogger
LOGGER: Logger = getLogger(__package__)
DOMAIN = "integration_blueprint"
ATTRIBUTION = "Data provided by http://jsonplaceholder.typicode.com/"

View File

@@ -0,0 +1,32 @@
"""DataUpdateCoordinator for integration_blueprint."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .api import (
IntegrationBlueprintApiClientAuthenticationError,
IntegrationBlueprintApiClientError,
)
if TYPE_CHECKING:
from .data import IntegrationBlueprintConfigEntry
# https://developers.home-assistant.io/docs/integration_fetching_data#coordinated-single-api-poll-for-data-for-all-entities
class BlueprintDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""
config_entry: IntegrationBlueprintConfigEntry
async def _async_update_data(self) -> Any:
"""Update data via library."""
try:
return await self.config_entry.runtime_data.client.async_get_data()
except IntegrationBlueprintApiClientAuthenticationError as exception:
raise ConfigEntryAuthFailed(exception) from exception
except IntegrationBlueprintApiClientError as exception:
raise UpdateFailed(exception) from exception

View File

@@ -0,0 +1,25 @@
"""Custom types for integration_blueprint."""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from homeassistant.config_entries import ConfigEntry
from homeassistant.loader import Integration
from .api import IntegrationBlueprintApiClient
from .coordinator import BlueprintDataUpdateCoordinator
type IntegrationBlueprintConfigEntry = ConfigEntry[IntegrationBlueprintData]
@dataclass
class IntegrationBlueprintData:
"""Data for the Blueprint integration."""
client: IntegrationBlueprintApiClient
coordinator: BlueprintDataUpdateCoordinator
integration: Integration

View File

@@ -0,0 +1,28 @@
"""BlueprintEntity class."""
from __future__ import annotations
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import ATTRIBUTION
from .coordinator import BlueprintDataUpdateCoordinator
class IntegrationBlueprintEntity(CoordinatorEntity[BlueprintDataUpdateCoordinator]):
"""BlueprintEntity class."""
_attr_attribution = ATTRIBUTION
def __init__(self, coordinator: BlueprintDataUpdateCoordinator) -> None:
"""Initialize."""
super().__init__(coordinator)
self._attr_unique_id = coordinator.config_entry.entry_id
self._attr_device_info = DeviceInfo(
identifiers={
(
coordinator.config_entry.domain,
coordinator.config_entry.entry_id,
),
},
)

View File

@@ -0,0 +1,12 @@
{
"domain": "integration_blueprint",
"name": "Integration blueprint",
"codeowners": [
"@ludeeus"
],
"config_flow": true,
"documentation": "https://github.com/ludeeus/integration_blueprint",
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/ludeeus/integration_blueprint/issues",
"version": "0.1.0"
}

View File

@@ -0,0 +1,57 @@
"""Sensor platform for integration_blueprint."""
from __future__ import annotations
from typing import TYPE_CHECKING
from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
from .entity import IntegrationBlueprintEntity
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .coordinator import BlueprintDataUpdateCoordinator
from .data import IntegrationBlueprintConfigEntry
ENTITY_DESCRIPTIONS = (
SensorEntityDescription(
key="integration_blueprint",
name="Integration Sensor",
icon="mdi:format-quote-close",
),
)
async def async_setup_entry(
hass: HomeAssistant, # noqa: ARG001 Unused function argument: `hass`
entry: IntegrationBlueprintConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the sensor platform."""
async_add_entities(
IntegrationBlueprintSensor(
coordinator=entry.runtime_data.coordinator,
entity_description=entity_description,
)
for entity_description in ENTITY_DESCRIPTIONS
)
class IntegrationBlueprintSensor(IntegrationBlueprintEntity, SensorEntity):
"""integration_blueprint Sensor class."""
def __init__(
self,
coordinator: BlueprintDataUpdateCoordinator,
entity_description: SensorEntityDescription,
) -> None:
"""Initialize the sensor class."""
super().__init__(coordinator)
self.entity_description = entity_description
@property
def native_value(self) -> str | None:
"""Return the native value of the sensor."""
return self.coordinator.data.get("body")

View File

@@ -0,0 +1,67 @@
"""Switch platform for integration_blueprint."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from .entity import IntegrationBlueprintEntity
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .coordinator import BlueprintDataUpdateCoordinator
from .data import IntegrationBlueprintConfigEntry
ENTITY_DESCRIPTIONS = (
SwitchEntityDescription(
key="integration_blueprint",
name="Integration Switch",
icon="mdi:format-quote-close",
),
)
async def async_setup_entry(
hass: HomeAssistant, # noqa: ARG001 Unused function argument: `hass`
entry: IntegrationBlueprintConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the switch platform."""
async_add_entities(
IntegrationBlueprintSwitch(
coordinator=entry.runtime_data.coordinator,
entity_description=entity_description,
)
for entity_description in ENTITY_DESCRIPTIONS
)
class IntegrationBlueprintSwitch(IntegrationBlueprintEntity, SwitchEntity):
"""integration_blueprint switch class."""
def __init__(
self,
coordinator: BlueprintDataUpdateCoordinator,
entity_description: SwitchEntityDescription,
) -> None:
"""Initialize the switch class."""
super().__init__(coordinator)
self.entity_description = entity_description
@property
def is_on(self) -> bool:
"""Return true if the switch is on."""
return self.coordinator.data.get("title", "") == "foo"
async def async_turn_on(self, **_: Any) -> None:
"""Turn on the switch."""
await self.coordinator.config_entry.runtime_data.client.async_set_title("bar")
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **_: Any) -> None:
"""Turn off the switch."""
await self.coordinator.config_entry.runtime_data.client.async_set_title("foo")
await self.coordinator.async_request_refresh()

View File

@@ -0,0 +1,21 @@
{
"config": {
"step": {
"user": {
"description": "If you need help with the configuration have a look here: https://github.com/ludeeus/integration_blueprint",
"data": {
"username": "Username",
"password": "Password"
}
}
},
"error": {
"auth": "Username/Password is wrong.",
"connection": "Unable to connect to the server.",
"unknown": "Unknown error occurred."
},
"abort": {
"already_configured": "This entry is already configured."
}
}
}