Add active-keg detection and a keg name sensor
Resolves the tapped keg's product id to a beer name via a bundled catalog (keg_catalog.json), exposing it as a new Keg sensor alongside the existing Keg Remaining/Freshness sensors.
This commit is contained in:
@@ -7,6 +7,7 @@ A Home Assistant custom integration for the [PerfectDraft Pro](https://www.perfe
|
||||
| Sensor | Description | Unit |
|
||||
|--------|-------------|------|
|
||||
| Temperature | Current beer temperature | °C |
|
||||
| Keg | Name of the tapped beer, resolved from a bundled catalog | — |
|
||||
| Keg Remaining | Beer left in the keg | % |
|
||||
| Keg Freshness | Days remaining until 30-day freshness expires | days |
|
||||
| Connection | Machine connectivity status | — |
|
||||
|
||||
@@ -187,3 +187,17 @@ class PerfectDraftApiClient:
|
||||
return await self._request(
|
||||
"GET", f"/api/perfectdraft_machines/{machine_id}"
|
||||
)
|
||||
|
||||
async def get_machine_active_keg(self, machine_id: str) -> dict[str, Any]:
|
||||
"""GET the machine serialized with the active-keg group.
|
||||
|
||||
Returns the machine with a ``kegActive`` object holding the currently
|
||||
tapped keg's product reference and its insertion date. This group is
|
||||
mutually exclusive with the default status fields, so it needs its own
|
||||
request alongside get_machine_details.
|
||||
"""
|
||||
return await self._request(
|
||||
"GET",
|
||||
f"/api/perfectdraft_machines/{machine_id}",
|
||||
params={"groups[]": "perfectdraft_keg_active_read"},
|
||||
)
|
||||
|
||||
@@ -82,4 +82,13 @@ class PerfectDraftDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
raise UpdateFailed(str(err)) from err
|
||||
|
||||
details["_machine_id"] = machine_id
|
||||
|
||||
# The active keg lives behind a separate serialization group. Treat it
|
||||
# as best-effort so a failure here doesn't take the whole device down.
|
||||
try:
|
||||
active = await self.client.get_machine_active_keg(machine_id)
|
||||
details["kegActive"] = active.get("kegActive")
|
||||
except (PerfectDraftApiError, PerfectDraftConnectionError) as err:
|
||||
_LOGGER.debug("Active keg lookup failed: %s", err)
|
||||
|
||||
return details
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"452": "Beck's Gold",
|
||||
"453": "Beck's",
|
||||
"454": "Löwenbräu",
|
||||
"455": "Franziskaner Weissbier",
|
||||
"456": "Diebels",
|
||||
"457": "Stella Artois",
|
||||
"458": "Jupiler",
|
||||
"500": "Hasseroder",
|
||||
"509": "Leffe Blonde",
|
||||
"679": "Hoegaarden",
|
||||
"759": "Diekirch Grand Cru",
|
||||
"1095": "Leffe Ruby",
|
||||
"2073": "Hertog Jan",
|
||||
"2167": "Leffe Spring",
|
||||
"2172": "Leffe Brune",
|
||||
"2452": "Leffe Royal Whitbread Golding",
|
||||
"2565": "Hoegaarden Rose",
|
||||
"9156": "Leffe Royal Cascade",
|
||||
"29745": "Lowenbrau Oktoberfestbier",
|
||||
"29775": "Goose Island Midway",
|
||||
"29896": "Kwak",
|
||||
"29974": "Spaten",
|
||||
"30955": "Franziskaner Royal",
|
||||
"31718": "Leffe Summer",
|
||||
"31747": "Budweiser",
|
||||
"31896": "Tripel Karmeliet",
|
||||
"32814": "Birra Del Borgo Lisa",
|
||||
"32816": "Goose Island IPA",
|
||||
"32864": "Leffe Amber",
|
||||
"33642": "Ginette Bio Refreshing Blonde",
|
||||
"33917": "Tiny Rebel Clwb Tropica",
|
||||
"33918": "Spaten Oktoberfestbier",
|
||||
"34327": "Thornbridge Jaipur",
|
||||
"34493": "Corona Extra",
|
||||
"34944": "Leffe La Légère",
|
||||
"35344": "Ginette Bio White",
|
||||
"36302": "Tennent's Lager",
|
||||
"41588": "Schneider's Bayrisch Hell",
|
||||
"41830": "BrewDog Punk IPA",
|
||||
"42223": "Victoria",
|
||||
"42352": "St Feuillien Blonde",
|
||||
"42377": "Bud Light",
|
||||
"42526": "Vocation Life & Death",
|
||||
"42640": "Kwak Blonde",
|
||||
"42756": "Innis & Gunn Lager Beer",
|
||||
"42778": "Mikkeller Game of Thrones",
|
||||
"42863": "1L Stein",
|
||||
"42876": "Orchard Pig Reveller Cider",
|
||||
"43006": "Camden Hells Lager",
|
||||
"43009": "Stella Artois Unfiltered",
|
||||
"43019": "Hawkstone Lager",
|
||||
"43033": "Hertog Jan Bockbier",
|
||||
"43235": "Corona Cero (0.0% abv) 6L Keg",
|
||||
"43805": "Camden Pale Ale",
|
||||
"43806": "Magic Rock Magic Orange",
|
||||
"44059": "San Miguel Especial",
|
||||
"44090": "Kopparberg Strawberry and Lime Cider",
|
||||
"44171": "Leffe Blanche",
|
||||
"44238": "BrewDog Hopped in Harmony",
|
||||
"44331": "Short Date Ninkasi Flower Lager 6L Keg BBE June 2024",
|
||||
"44387": "Mont Blanc La Rousse",
|
||||
"44452": "Franziskaner Kellerbier",
|
||||
"44474": "Camden Marzen",
|
||||
"44526": "Mahou",
|
||||
"44536": "Short Date Tiny Rebel Stay Puft 6L Keg BBE August 2024",
|
||||
"47144": "Haake Beck",
|
||||
"47285": "Theakston Old Peculier",
|
||||
"47384": "Peroni Nastro Azzurro",
|
||||
"47418": "Singha",
|
||||
"47440": "Ninkasi French IPA",
|
||||
"47486": "Meteor White IPA",
|
||||
"47629": "Camden Eazy IPA",
|
||||
"47943": "Fuller's London Pride",
|
||||
"47962": "Bass Pale Ale",
|
||||
"47972": "Stella Artois 0.0%",
|
||||
"47973": "Trooper Original",
|
||||
"47974": "Ch'ti Blonde",
|
||||
"47977": "Früh Kölsch",
|
||||
"47978": "Saison Dupont Dry Hop",
|
||||
"47979": "Modelo Especial",
|
||||
"47984": "Samson 11",
|
||||
"47986": "La Chouffe Blonde",
|
||||
"47999": "Thatchers Gold Cider",
|
||||
"48019": "Leffe Blonde 0.0%",
|
||||
"48024": "Siren Lumina IPA",
|
||||
"48061": "Northern Monk Faith"
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"domain": "perfectdraft",
|
||||
"name": "PerfectDraft",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"documentation": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro",
|
||||
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro/issues",
|
||||
"codeowners": ["@Falkvinge"],
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
"""Sensor entities for PerfectDraft."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
@@ -24,9 +27,23 @@ from .const import DOMAIN, keg_changed_signal
|
||||
from .coordinator import PerfectDraftDataUpdateCoordinator
|
||||
from .keg_detection import KEG_TOTAL_VOLUME, detect_keg_change
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
KEG_FRESHNESS_DAYS = 30
|
||||
|
||||
|
||||
def _load_keg_catalog() -> dict[int, str]:
|
||||
try:
|
||||
raw = json.loads((Path(__file__).parent / "keg_catalog.json").read_text())
|
||||
return {int(k): v for k, v in raw.items()}
|
||||
except (OSError, ValueError) as err:
|
||||
_LOGGER.debug("Could not load keg catalog: %s", err)
|
||||
return {}
|
||||
|
||||
|
||||
_KEG_CATALOG: dict[int, str] = _load_keg_catalog()
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class PerfectDraftSensorDescription(SensorEntityDescription):
|
||||
"""Extended description with a value extractor."""
|
||||
@@ -88,6 +105,33 @@ def _get_mode(data: dict) -> str | None:
|
||||
return setting.get("mode")
|
||||
|
||||
|
||||
def _get_keg_product_id(data: dict) -> int | None:
|
||||
ref = (data.get("kegActive") or {}).get("keg")
|
||||
if not ref:
|
||||
return None
|
||||
try:
|
||||
return int(str(ref).rstrip("/").rsplit("/", 1)[-1])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _get_keg_name(data: dict) -> str | None:
|
||||
product_id = _get_keg_product_id(data)
|
||||
if product_id is None:
|
||||
return None
|
||||
return _KEG_CATALOG.get(product_id)
|
||||
|
||||
|
||||
def _keg_inserted_at(data: dict) -> datetime | None:
|
||||
iso = (data.get("kegActive") or {}).get("insertedAt")
|
||||
if not iso:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(iso)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
SENSOR_DESCRIPTIONS: tuple[PerfectDraftSensorDescription, ...] = (
|
||||
PerfectDraftSensorDescription(
|
||||
key="temperature",
|
||||
@@ -107,6 +151,18 @@ SENSOR_DESCRIPTIONS: tuple[PerfectDraftSensorDescription, ...] = (
|
||||
suggested_display_precision=0,
|
||||
value_fn=_get_volume_remaining,
|
||||
),
|
||||
PerfectDraftSensorDescription(
|
||||
key="keg_product_id",
|
||||
translation_key="keg_product_id",
|
||||
icon="mdi:barcode",
|
||||
value_fn=_get_keg_product_id,
|
||||
),
|
||||
PerfectDraftSensorDescription(
|
||||
key="keg_name",
|
||||
translation_key="keg_name",
|
||||
icon="mdi:beer",
|
||||
value_fn=_get_keg_name,
|
||||
),
|
||||
PerfectDraftSensorDescription(
|
||||
key="connection",
|
||||
translation_key="connection",
|
||||
@@ -200,9 +256,10 @@ class PerfectDraftKegFreshnessSensor(
|
||||
):
|
||||
"""Tracks keg freshness as a 30-day countdown from insertion.
|
||||
|
||||
Detects new keg insertion when numberOfPoursSinceStartup resets to 0
|
||||
and kegVolume is near full. Persists the insertion timestamp across
|
||||
HA restarts via RestoreEntity.
|
||||
Prefers the insertion date reported by the API's active keg. When that is
|
||||
unavailable it falls back to detecting insertion locally (pour count reset
|
||||
with a near-full keg). The date is persisted across HA restarts via
|
||||
RestoreEntity.
|
||||
"""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
@@ -261,27 +318,30 @@ class PerfectDraftKegFreshnessSensor(
|
||||
|
||||
@callback
|
||||
def _handle_coordinator_update(self) -> None:
|
||||
"""Detect new keg insertion on each data update."""
|
||||
"""Update the insertion date on each poll."""
|
||||
data = self.coordinator.data
|
||||
if not data:
|
||||
super()._handle_coordinator_update()
|
||||
return
|
||||
|
||||
details = data.get("details") or {}
|
||||
pours = details.get("numberOfPoursSinceStartup")
|
||||
volume = details.get("kegVolume")
|
||||
reported = _keg_inserted_at(data)
|
||||
if reported is not None:
|
||||
self._keg_inserted_at = reported
|
||||
else:
|
||||
details = data.get("details") or {}
|
||||
pours = details.get("numberOfPoursSinceStartup")
|
||||
volume = details.get("kegVolume")
|
||||
if pours is not None and volume is not None:
|
||||
if detect_keg_change(
|
||||
last_pours=self._last_pours,
|
||||
last_volume=self._last_volume,
|
||||
pours=int(pours),
|
||||
volume=float(volume),
|
||||
):
|
||||
self._keg_inserted_at = datetime.now(timezone.utc)
|
||||
|
||||
if pours is not None and volume is not None:
|
||||
if detect_keg_change(
|
||||
last_pours=self._last_pours,
|
||||
last_volume=self._last_volume,
|
||||
pours=int(pours),
|
||||
volume=float(volume),
|
||||
):
|
||||
self._keg_inserted_at = datetime.now(timezone.utc)
|
||||
|
||||
self._last_pours = int(pours)
|
||||
self._last_volume = float(volume)
|
||||
self._last_pours = int(pours)
|
||||
self._last_volume = float(volume)
|
||||
|
||||
super()._handle_coordinator_update()
|
||||
|
||||
@@ -304,17 +364,25 @@ class PerfectDraftKegFreshnessSensor(
|
||||
|
||||
self.async_write_ha_state()
|
||||
|
||||
def _inserted_at(self) -> datetime | None:
|
||||
"""The current insertion date, preferring the live API value."""
|
||||
if self.coordinator.data:
|
||||
reported = _keg_inserted_at(self.coordinator.data)
|
||||
if reported is not None:
|
||||
return reported
|
||||
return self._keg_inserted_at
|
||||
|
||||
@property
|
||||
def native_value(self) -> int | None:
|
||||
if self._keg_inserted_at is None:
|
||||
inserted = self._inserted_at()
|
||||
if inserted is None:
|
||||
return None
|
||||
elapsed = (datetime.now(timezone.utc) - self._keg_inserted_at).days
|
||||
remaining = KEG_FRESHNESS_DAYS - elapsed
|
||||
return max(remaining, 0)
|
||||
elapsed = (datetime.now(timezone.utc) - inserted).days
|
||||
return max(KEG_FRESHNESS_DAYS - elapsed, 0)
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
return super().available and self._keg_inserted_at is not None
|
||||
return super().available and self._inserted_at() is not None
|
||||
|
||||
|
||||
def _device_info(
|
||||
|
||||
@@ -39,6 +39,8 @@
|
||||
"sensor": {
|
||||
"temperature": { "name": "Temperature" },
|
||||
"keg_remaining": { "name": "Keg Remaining" },
|
||||
"keg_product_id": { "name": "Keg Product" },
|
||||
"keg_name": { "name": "Keg" },
|
||||
"connection": { "name": "Connection" },
|
||||
"door": { "name": "Door" },
|
||||
"pours": { "name": "Pours" },
|
||||
|
||||
@@ -39,6 +39,8 @@
|
||||
"sensor": {
|
||||
"temperature": { "name": "Temperature" },
|
||||
"keg_remaining": { "name": "Keg Remaining" },
|
||||
"keg_product_id": { "name": "Keg Product" },
|
||||
"keg_name": { "name": "Keg" },
|
||||
"connection": { "name": "Connection" },
|
||||
"door": { "name": "Door" },
|
||||
"pours": { "name": "Pours" },
|
||||
|
||||
Reference in New Issue
Block a user