35 Commits
Author SHA1 Message Date
rickandCursor 9a81654579 Version 0.4.6: French translation
Ships the French translation contributed by aurel in PR #14 (704f55e).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-07 18:35:46 +01:00
aurel 704f55e595 feat(i18n): add complete French translation (fr.json) 2026-11-07 13:23:59 +01:00
rickandCursor 1598e7b031 Spell keg 29745 as Löwenbräu Oktoberfestbier; version 0.4.5
The catalog had the umlauts stripped, unlike its own 454 entry (Löwenbräu) and the companion card. Product ID and position are unchanged. Issue #8; ships with card 0.4.5, which adds keg artwork for both Oktoberfestbier kegs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-07 12:34:20 +01:00
rick 48434a7af3 Merge agent/add-keg-48180: Camden Stout (48180) in the keg catalog 2026-11-07 12:23:49 +01:00
rickandCursor a21273c000 Version 0.4.4, in step with the companion card
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-07 12:12:41 +01:00
8b2c4418b3 Add keg 48180 (Camden Stout) to the catalog
Observed by MThomas564 on a machine with the keg fitted (#9, PR #10).
Appended after 48134 to keep numeric key order; catalog floor ratchets
to 117.

Co-authored-by: MThomas564 <mattraethomas97@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-07 12:07:47 +01:00
rickandCursor 20ed62b963 Sign in via Cognito directly so PerfectDraft gets the domain
PerfectDraft's Cognito PreAuthentication Lambda now requires a "domain"
field in ClientMetadata. The api.perfectdraft.com /authentication/sign-in
gateway does not forward it, so every setup and reauth failed with
"PreAuthentication failed with error 'domain'" (#11, #12, #13).
authenticate() now calls Cognito InitiateAuth (USER_PASSWORD_AUTH)
itself, the endpoint token refresh already uses.

A failed sign-in now says what was rejected and why. A wrong email or
password returns to the credentials form; a rejected token stays on the
token step; both show Cognito's reason instead of the old blanket "token
may have expired", which hid this outage.

The README snippet copies the token to the clipboard. It captures copy()
up front because Chromium removes it once the console command returns.

Root cause and fix by @cesa030 in #11; confirmed in @brettjenkins' fork.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-07 11:20:47 +01:00
rickandCursor 3b82df6e83 Add Camden Eazy (47792) to the keg name catalog.
The Keg sensor stayed blank for this product ID. 47629 remains Camden Eazy IPA.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 07:14:57 +02:00
rickandCursor fc8a25c41a Add Anheuser-Busch Bud (48050) to the keg name catalog
The DE/AT wrap is a distinct SKU from the UK Budweiser keg at 31747.
Observed from a fitted machine in issue #3. Bump to 0.3.3.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 12:41:54 +02:00
rick 2a21c70241 Merge master into agent/backport-keg-catalog 2026-09-06 16:16:03 +02:00
rick 44fd73f661 Credit the catalog backport and guard its format
Companion to the previous commit, which is Brett Jenkins' catalog work
cherry-picked with authorship intact rather than copied in as data. This
commit adds what the backport needs around it.

README: credit Brett and his fork for the keg name sensor, the Keg and
Keg Product sensors, and the whole 114-entry catalog, and explain why the
catalog is hand-maintained — the API will not return the ID-to-name
mapping in bulk, so every entry is observed from a machine with that keg
fitted and none of it can be inferred. Also tells a user with a blank Keg
sensor to report their Keg Product ID, which is the only way the catalog
grows.

tests/test_keg_catalog.py: format and content guards for the spec
scenarios, stdlib-only so it runs under python3 -m unittest alongside
test_keg_detection.py without the opt-in HA harness.

Two of those guards cover failure modes that are silent rather than loud:

  - Duplicate keys. json.loads() keeps the last one, so a repeated ID
    would quietly discard an observed name. Only a pair-count comparison
    sees it.

  - Non-numeric keys. _load_keg_catalog builds {int(k): v ...} and
    catches ValueError by returning an empty dict, so one "_meta" or
    "_source" key would disable the entire catalog and leave every keg
    with no name. This matters because embedding attribution or
    provenance in the JSON is the obvious next idea, and it cannot be
    done without changing the loader first. The test documents that.

Version 0.3.2, continuing from 0.3.1. Not the fork's 0.4.1: 0f3b4c2
renumbered to 0.3.1 deliberately because no v0.4.0 tag was ever cut.
hacs.json is left alone, including the 2024.11.0 floor the fork predates.
2026-09-06 16:16:03 +02:00
Brett Jenkinsandrick 3c4b9ca625 Complete the keg name catalog: 86 -> 114 kegs
This is the full mapping — every keg the PerfectDraft app can select, including ones no
longer sold but which can still be sat in a machine. The same mapping drives the
seemy.beer tap sign, where it has been running well.

The ids can't be looked up in bulk, so each one was observed directly from the machine.
Every entry here is measured rather than inferred.

28 kegs previously showed no name at all in Home Assistant. Now named, among them
Kopparberg Crisp Apple, Leffe Prestige, Kwak Rouge, Hertog Jan Grand Pilsener and all
three Diekirchs.

Four existing names were wrong rather than merely styled differently:

  32814  Birra Del Borgo Lisa -> Romola          the beer was renamed, so this was
                                                 showing one that no longer exists
  44331  Short Date Ninkasi Flower Lager 6L Keg BBE June 2024   -> Ninkasi Flower Lager
  44536  Short Date Tiny Rebel Stay Puft 6L Keg BBE August 2024 -> Tiny Rebel Stay Puft
                                                 shop listings still carrying a
                                                 best-before date from 2024
  43235  Corona Cero (0.0% abv) 6L Keg -> Corona Cero (0.0% abv)   6L is the pack

Eleven other names differ only in styling (Trooper vs TROOPER, St vs Saint Feuillien).
Left alone deliberately: this is a display name, the existing spellings are the ones the
shop uses, and rewriting them would only make the diff harder to read.

File formatting is untouched (no indent, numeric key order), so the diff is just the
real additions.

(cherry picked from commit 0982d20737d22c241c736fe657b3e0d02625b50c)

Backported-from: https://github.com/brettjenkins/hassio-integration-perfectdraft-pro
Backported-via: brettjenkins/hassio-integration-perfectdraft-pro#1
2026-09-06 16:12:17 +02:00
rickandCursor 133f7082cf fix(sensor): reject implausible temperature readings
An uninitialised probe reports -128 (0x80 read as a signed 8-bit
integer) while the refrigeration starts up. The cloud API relays it
verbatim and the sensor reported it as a real measurement, polluting
history graphs and long-term statistics.

Readings outside -20..50 C are now treated as firmware sentinels and
the sensor reports no value, so the state is 'unknown' and the recorder
excludes it. A range check is used rather than matching -128 exactly so
sibling sentinels are caught too. Both temperature fields are validated;
previously the details.temperature fallback was used unconditionally.

The sensor deliberately reports 'unknown' rather than going unavailable:
the coordinator poll succeeded and only the reading is missing, which
matches how every other sensor here signals absent data.

Logic lives in a new HA-free temperature.py so it can be unit-tested
without the Home Assistant harness, following the keg_detection.py
precedent.

Refs: Falkvinge/hassio-integration-perfectdraft-pro#4
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 16:11:07 +02:00
rickandCursor 5d049c5529 fix: translate the already_in_progress abort, derive the reason set
Verification caught this change violating its own requirement that every
abort reason the flow can emit has a translation. async_set_unique_id()
defaults to raise_on_progress=True and raises already_in_progress when
another flow holds the same unique ID. That is reachable, and reachable
by exactly the users this change is for: park a reauth flow, give up,
try Add Integration for the same account, and the raw key surfaces.

The coverage test was hardcoded to three reasons, so it checked a "for
every" requirement against a list written by hand and passed anyway.
Replace it with an AST scan of config_flow.py that resolves each
aborting helper call to the reason it raises, honouring explicit reason=
and the raise_on_progress=False opt-out, plus a sanity test so a scanner
that goes blind fails instead of silently passing. Confirmed the new
check fails against the pre-fix translation files.

Also adds a regression test for the concurrent-flow path, which is the
evidence that this abort is real rather than theoretical.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 15:39:13 +02:00
rickandCursor 0f3b4c20af fix: make reauth update the existing entry instead of aborting
async_step_token is shared by the user and reauth sources but was written
only for the former. It called _abort_if_unique_id_configured() on every
path, and during reauth the unique ID belongs to the entry being repaired,
so the duplicate guard fired by design: authentication succeeded, the flow
aborted with already_configured, the new tokens were discarded, and the
coordinator's next poll re-raised the reauth repair. The integration was
unrecoverable through the UI short of delete-and-re-add, which costs entity
history and the restored keg-freshness baseline.

Branch on self.source at the terminal step, per HA's documented pattern for
flows shared between setup and reauth: reauth now guards with
_abort_if_unique_id_mismatch() and persists through
async_update_reload_and_abort(), which merges the new tokens into the
existing entry, keeps email and machine ID, reloads, and aborts with
reauth_successful. The user path keeps _abort_if_unique_id_configured()
unchanged.

Reauth also stops re-fetching /api/me when the entry already records a
machine ID, removing a round trip from a flow the user waits on and a
failure mode where a transient /api/me error turned a successful sign-in
into cannot_connect.

The helpers require core 2024.11, so declare that floor in hacs.json —
otherwise older cores would AttributeError mid-flow, which is worse than
the bug being fixed.

Adds the repo's first HA test harness (requirements-test.txt, opt-in) with
regression tests covering token persistence, entry reload, account
mismatch, case-insensitive email, and the explicit assertion that reauth
never aborts as already_configured. tests/test_keg_detection.py still runs
standalone under python3 -m unittest.

Version set to 0.3.1 rather than the 0.4.0 that PR #2 introduced; no
v0.4.0 tag was ever cut, so nothing was released under that number.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 15:26:48 +02:00
Brett Jenkins 9b3852b9fd 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.
2026-07-05 00:49:29 +01:00
rickandCursor f5c9019802 feat: detect keg change by volume jump + manual reset button
Keg-change detection previously fired only when the pour counter reset
to 0 while the keg read near full. That misses the common case where the
user swaps the keg and pours immediately, so pours never reads 0.

Detection now also fires on two volume-based signals (independent of the
pour counter): (b) remaining volume jumping from below 80% to at least
95%, and (c) any upward jump of at least 50 percentage points. The
decision logic is extracted to a dependency-free keg_detection module
with unit tests covering each trigger and the swap-then-pour case.

Adds a "Mark Keg Changed" button as a deterministic manual override,
wired to the freshness sensor via a dispatcher signal; the sensor now
tracks and restores last_volume alongside last_pours.

Bumps version to 0.3.0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-31 21:04:44 +02:00
rick 73559b7bd2 Write comprehensive main specs from scratch
5 capability specs covering the integration as-built:
- api-client: sign-in, Cognito refresh, auto-retry, endpoints
- config-flow: credentials, token paste, reauth, options flow
- data-coordinator: single poller, dynamic interval, error handling
- entities: 9 sensors (temp, keg %, freshness, connection, door,
  pours, last pour, firmware, mode), device model, translations
- hacs-packaging: repo structure, manifest, brand icon, README,
  GitHub mirror, translation constraints

331 lines of testable requirements with scenarios.

Made-with: Cursor
2026-04-18 15:41:29 +02:00
rick afa5b5a60a manifest: add @Falkvinge as codeowner
Made-with: Cursor
2026-04-13 14:41:41 +02:00
rick 8ad4ce2d8c Add clickable link to setup instructions in token step description
Made-with: Cursor
2026-04-13 13:00:17 +02:00
rick 7cb12a8fad Point manifest URLs at GitHub mirror for HACS compatibility
Made-with: Cursor
2026-04-13 12:47:14 +02:00
rick 5e4ef94cff Fix RestoreEntity: use state attributes instead of ExtraStoredData API
Made-with: Cursor
2026-04-13 12:17:15 +02:00
rick 70882b939e v0.2.0: Fix token refresh, HACS compliance, brand icon, keg freshness
Critical fix:
- Cognito refresh now parses response with content_type=None
  (was crashing after 1hr when access token expired)

HACS compliance:
- Added README.md with full setup instructions including the
  token generation command
- Fixed manifest.json URLs to point at actual repo
- Version bumped to 0.2.0

Brand:
- Added brand/icon.png (PerfectDraft glass icon from official app)

New sensor:
- Keg Freshness: 30-day countdown from keg insertion, detected
  via numberOfPoursSinceStartup reset + kegVolume near full,
  persisted across restarts via RestoreEntity

Polish:
- Fixed MALFORMED_ARGUMENT in token step description
- Cleaner description referencing README for instructions

Made-with: Cursor
2026-04-13 12:12:43 +02:00
rick 869058e8eb Fix MALFORMED_ARGUMENT: curly braces in description parsed as translation placeholders
Made-with: Cursor
2026-04-12 17:52:26 +02:00
rick 3d8f4b93e6 Add entity name translations so sensors show individual names
Made-with: Cursor
2026-04-12 17:39:34 +02:00
rick b3fdf2fc97 Fix translation error: remove newlines from description strings
Made-with: Cursor
2026-04-12 17:36:49 +02:00
rick 56ea7711f0 Simplify config flow: paste-token instead of external step
The reCAPTCHA external step has domain validation issues (HA's
hostname isn't in the allowed list for any reCAPTCHA key). Instead,
the config flow now asks the user to:

1. Open perfectdraft.com/en-gb/customer/account/login
2. Run one console command to generate a token
3. Paste the token into the HA config flow

Clear instructions are shown in the flow description. The token
expires in 2 minutes, and the error message tells the user to
try again with a fresh token if it fails.

Removed the external step, HTML page, and HTTP views entirely.
Much simpler code, no moving parts.

Made-with: Cursor
2026-04-12 17:27:29 +02:00
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
rick fcba32fecd Replace reCAPTCHA auth with token-bootstrap flow
The Android reCAPTCHA Enterprise key cannot be used from any
non-Android context (browser, server, headless). Certificate
pinning prevents MITM token capture. Every approach to bypass
reCAPTCHA has been exhausted.

New approach: user provides UserId + RefreshToken (one-time
extraction from the PerfectDraft app via HTTP Toolkit or similar).
The integration validates by calling /auth/renewaccesstokens,
which does NOT require reCAPTCHA, then refreshes forever.

Changes:
- config_flow.py: two-step flow (email, then tokens), validates
  via refresh endpoint, reauth asks for fresh tokens
- api.py: refresh_access_token() calls /auth/renewaccesstokens
  with {UserId, RefreshToken}, removed authenticate() method,
  added x-api-key header to all authenticated requests
- const.py: added CONF_USER_ID, removed reCAPTCHA constants
- __init__.py: passes user_id to client.set_tokens()
- strings.json + translations: updated for new flow steps
- Deleted recaptcha.py and static/recaptcha.html
- test_harness.py: updated for refresh-based flow

Made-with: Cursor
2026-04-12 12:26:12 +02:00
rick b383fdc20a gitignore: add swap files and zip artifacts
Made-with: Cursor
2026-04-12 05:14:35 +02:00
rick e6f5af9771 APK analysis: map full API surface and discover refresh endpoint
Decompiled PerfectDraft APK (Expo/React Native + Hermes bytecode).
Key discoveries:

API has TWO auth systems:
- /authentication/sign-in (Cognito + Lambda trigger) — old
- /auth/signin (.NET backend) — new, same reCAPTCHA gate

Critical find: /auth/renewaccesstokens accepts POST with
{UserId, RefreshToken} and does NOT require reCAPTCHA.

Full API surface discovered:
- /auth/signin, /auth/renewaccesstokens, /auth/signout
- /auth/changepassword, /auth/confirmsignup
- /api/perfectdraft_machines/, /api/perfectdraft_machines/{id}
- /api/perfectdraft_machine_kegs
- /api/pda_machines/add
- /api/countries, /api/customer_product_ratings

reCAPTCHA is Android Enterprise key — cannot generate valid
high-score tokens from any non-Android context. Both /auth/signin
and /authentication/sign-in require it. But refresh does not.

Strategy: one-time token capture, then refresh forever.
Made-with: Cursor
2026-04-12 05:14:26 +02:00
rick 17c0551711 Switch to PerfectDraft web reCAPTCHA key
The Android key (6LdrqmAp...) only works with the Android SDK —
it rejects all web-based token generation with "Invalid domain."

Discovered that perfectdraft.com's web login uses a separate
Enterprise web key (6LcZQiUo...) with action "Magento/login".
Testing confirmed the API at api.perfectdraft.com accepts tokens
from this web key. The only remaining requirement is a high
reCAPTCHA score, which a real user's browser will provide.

The external step flow now uses:
- Enterprise JS (recaptcha/enterprise.js)
- Web site key: 6LcZQiUoAAAAAAO3JUjLiT470c-pNXbWyepuvMtV
- Action: Magento/login

Removed server-side token generation attempt from config flow
since it cannot produce high-score tokens.

Made-with: Cursor
2026-04-11 21:04:56 +02:00
rick 74163b1ff1 Add server-side reCAPTCHA token generation
The browser-based reCAPTCHA approach fails with "Invalid domain"
because PerfectDraft's site key is registered for their domains,
not for the HA instance hostname.

New approach: generate the token server-side via the reCAPTCHA
anchor/reload HTTP endpoints, bypassing domain validation entirely.
Falls back to browser-based external step if server-side fails.

Also adds better error logging in the auth step.

Made-with: Cursor
2026-04-11 20:47:29 +02:00
rick 1706a10ccb Fix config flow external step for reCAPTCHA
The external step mechanism requires a specific flow:
1. async_external_step() pauses the flow
2. Callback stashes token in hass.data and calls async_configure()
   with no user_input to signal completion
3. HA calls async_step_recaptcha_done() which picks up the token
4. async_external_step_done() transitions to async_step_finish()
5. async_step_finish() does the actual API authentication

Previously tried to resume the flow by passing user_input directly
to async_configure(), which doesn't work with external steps.

Made-with: Cursor
2026-04-11 20:32:46 +02:00
rick c24e3678a7 Implement PerfectDraft Pro HA integration (tasks 1–7)
Complete custom_components/perfectdraft/ with:
- Async API client (auth, refresh, machine polling)
- Config flow with reCAPTCHA v3 external step
- DataUpdateCoordinator for shared polling
- Sensor entities (temperature, % remaining, days to expiry, keg name)
- Image entity for keg artwork
- HACS-compliant packaging (manifest.json, hacs.json, translations)
- Configurable polling interval via OptionsFlow
- Reauth flow for expired refresh tokens

Group 8 (manual testing) deferred — requires live HA instance.

Made-with: Cursor
2026-04-11 19:09:44 +02:00