Files
hassio-integration-perfectd…/custom_components/perfectdraft/coordinator.py
T
rick 34a23a2814 Working integration with real API data
Breakthrough: discovered the web reCAPTCHA Enterprise key
(6LcZQiUo...) from perfectdraft.com with action "Magento/login"
is accepted by the /authentication/sign-in API endpoint when
generated from a real browser. Token refresh works via direct
AWS Cognito InitiateAuth (bypasses API gateway, no reCAPTCHA).

Cognito details extracted from JWT:
  Pool: eu-west-1_UXWVyvlHR
  Client: 57ddq2ppqg2jcpup06r2g1deur

Real API response fields mapped:
  /api/me → perfectdraftMachines[].id
  /api/perfectdraft_machines/{id} → details.temperature,
    details.kegVolume, details.connectedState, details.doorClosed,
    details.numberOfPoursSinceStartup, details.volumeOfLastPour,
    details.firmwareVersion, details.serialNumber, setting.mode

Changes:
- api.py: Cognito direct refresh, correct sign-in endpoint
- config_flow.py: external step with web reCAPTCHA on HA page
- const.py: Cognito config, web reCAPTCHA key
- coordinator.py: real field name extraction
- sensor.py: 8 sensors with real field mappings (temperature,
  keg remaining %, connection, door, pours, last pour, firmware, mode)
- Removed image.py (API doesn't expose keg images)
- Restored static/recaptcha.html with Enterprise JS

Made-with: Cursor
2026-04-12 17:18:03 +02:00

86 lines
2.7 KiB
Python

"""DataUpdateCoordinator for PerfectDraft."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
UpdateFailed,
)
from .api import PerfectDraftApiClient
from .const import (
CONF_MACHINE_ID,
CONF_SCAN_INTERVAL,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
)
from .exceptions import (
AuthenticationError,
PerfectDraftApiError,
PerfectDraftConnectionError,
)
_LOGGER = logging.getLogger(__name__)
class PerfectDraftDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Single coordinator that polls the PerfectDraft API for all entities."""
config_entry: ConfigEntry
def __init__(
self,
hass: HomeAssistant,
client: PerfectDraftApiClient,
config_entry: ConfigEntry,
) -> None:
self.client = client
interval = config_entry.options.get(
CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
)
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
update_interval=timedelta(seconds=interval),
config_entry=config_entry,
)
def update_interval_from_options(self) -> None:
"""Re-read the polling interval from config entry options."""
interval = self.config_entry.options.get(
CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
)
self.update_interval = timedelta(seconds=interval)
_LOGGER.debug("Polling interval updated to %s seconds", interval)
async def _async_update_data(self) -> dict[str, Any]:
machine_id = self.config_entry.data.get(CONF_MACHINE_ID)
try:
if not machine_id:
profile = await self.client.get_user_profile()
machines = profile.get("perfectdraftMachines", [])
if not machines:
raise UpdateFailed(
"No PerfectDraft machine found on this account"
)
machine_id = str(machines[0].get("id", ""))
details = await self.client.get_machine_details(machine_id)
except AuthenticationError as err:
raise ConfigEntryAuthFailed(
"Authentication failed — please re-authenticate"
) from err
except (PerfectDraftApiError, PerfectDraftConnectionError) as err:
raise UpdateFailed(str(err)) from err
details["_machine_id"] = machine_id
return details