diff --git a/custom_components/perfectdraft/button.py b/custom_components/perfectdraft/button.py new file mode 100644 index 0000000..0e56ecb --- /dev/null +++ b/custom_components/perfectdraft/button.py @@ -0,0 +1,46 @@ +"""Button entities for PerfectDraft.""" +from __future__ import annotations + +from homeassistant.components.button import ButtonEntity +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.dispatcher import async_dispatcher_send +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from .const import DOMAIN, keg_changed_signal +from .coordinator import PerfectDraftDataUpdateCoordinator +from .sensor import _device_info + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Set up PerfectDraft button entities.""" + coordinator: PerfectDraftDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] + async_add_entities([PerfectDraftKegResetButton(coordinator)]) + + +class PerfectDraftKegResetButton( + CoordinatorEntity[PerfectDraftDataUpdateCoordinator], ButtonEntity +): + """Button that marks the current keg as freshly changed as of now.""" + + _attr_has_entity_name = True + _attr_translation_key = "mark_keg_changed" + _attr_icon = "mdi:keg" + + def __init__( + self, + coordinator: PerfectDraftDataUpdateCoordinator, + ) -> None: + super().__init__(coordinator) + self._machine_id = (coordinator.data or {}).get("_machine_id", "unknown") + self._attr_unique_id = f"{self._machine_id}_mark_keg_changed" + self._attr_device_info = _device_info(coordinator) + + async def async_press(self) -> None: + """Tell the freshness sensor to set the keg insertion date to now.""" + async_dispatcher_send(self.hass, keg_changed_signal(self._machine_id)) diff --git a/custom_components/perfectdraft/const.py b/custom_components/perfectdraft/const.py index 725647f..dbaf61e 100644 --- a/custom_components/perfectdraft/const.py +++ b/custom_components/perfectdraft/const.py @@ -19,4 +19,9 @@ CONF_USER_ID = "user_id" CONF_MACHINE_ID = "machine_id" CONF_SCAN_INTERVAL = "scan_interval" -PLATFORMS = ["sensor"] +PLATFORMS = ["sensor", "button"] + + +def keg_changed_signal(machine_id: str) -> str: + """Dispatcher signal fired when the keg is manually marked as changed.""" + return f"{DOMAIN}_keg_changed_{machine_id}" diff --git a/custom_components/perfectdraft/keg_detection.py b/custom_components/perfectdraft/keg_detection.py new file mode 100644 index 0000000..bb7e813 --- /dev/null +++ b/custom_components/perfectdraft/keg_detection.py @@ -0,0 +1,53 @@ +"""Pure keg-change detection logic — no Home Assistant dependencies. + +Kept import-free so the decision logic can be unit-tested standalone, +without a Home Assistant test harness. +""" +from __future__ import annotations + +KEG_TOTAL_VOLUME = 6.0 # litres — a full keg +KEG_NEW_VOLUME_THRESHOLD = 5.5 # litres — "near full" for the pour-reset signal + +# Volume-jump thresholds, expressed as percent of a full keg. +KEG_REFILL_LOW_PCT = 80 # previous level below this counts as "low" (4.8 L) +KEG_REFILL_FULL_PCT = 95 # current level at/above this counts as "near full" (5.7 L) +KEG_JUMP_PCT = 50 # an upward step at least this large implies a swap (3.0 L) + + +def detect_keg_change( + *, + last_pours: int | None, + last_volume: float | None, + pours: int, + volume: float, +) -> bool: + """Return True when the readings indicate a fresh keg was inserted. + + Any single trigger is sufficient: + (a) pour counter reads 0 while the keg is near full (the original signal); + (b) remaining volume jumped from below 80% to at least 95% of capacity; + (c) remaining volume jumped up by at least 50 percentage points. + + Triggers (b) and (c) compare against the previous reading, so they are + skipped on the first reading after install/restart (``last_volume is None``) + to avoid a false positive. + """ + # (a) Pour-reset signal — unchanged from the original behaviour. + if pours == 0 and volume > KEG_NEW_VOLUME_THRESHOLD and last_pours != 0: + return True + + if last_volume is None: + return False + + pct = volume / KEG_TOTAL_VOLUME * 100 + last_pct = last_volume / KEG_TOTAL_VOLUME * 100 + + # (b) Refilled to near-full from a low level. + if last_pct < KEG_REFILL_LOW_PCT and pct >= KEG_REFILL_FULL_PCT: + return True + + # (c) Large upward jump in remaining volume. + if pct - last_pct >= KEG_JUMP_PCT: + return True + + return False diff --git a/custom_components/perfectdraft/manifest.json b/custom_components/perfectdraft/manifest.json index 87fd5bf..0fc22b0 100644 --- a/custom_components/perfectdraft/manifest.json +++ b/custom_components/perfectdraft/manifest.json @@ -1,7 +1,7 @@ { "domain": "perfectdraft", "name": "PerfectDraft", - "version": "0.2.1", + "version": "0.3.0", "documentation": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro", "issue_tracker": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro/issues", "codeowners": ["@Falkvinge"], diff --git a/custom_components/perfectdraft/sensor.py b/custom_components/perfectdraft/sensor.py index f4fb877..a0802b5 100644 --- a/custom_components/perfectdraft/sensor.py +++ b/custom_components/perfectdraft/sensor.py @@ -15,16 +15,16 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.const import PERCENTAGE, UnitOfTemperature from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity -from .const import DOMAIN +from .const import DOMAIN, keg_changed_signal from .coordinator import PerfectDraftDataUpdateCoordinator +from .keg_detection import KEG_TOTAL_VOLUME, detect_keg_change -KEG_TOTAL_VOLUME = 6.0 # litres KEG_FRESHNESS_DAYS = 30 -KEG_NEW_VOLUME_THRESHOLD = 5.5 # litres — above this + pours==0 means new keg @dataclass(frozen=True, kw_only=True) @@ -220,9 +220,10 @@ class PerfectDraftKegFreshnessSensor( self._attr_device_info = _device_info(coordinator) self._keg_inserted_at: datetime | None = None self._last_pours: int | None = None + self._last_volume: float | None = None async def async_added_to_hass(self) -> None: - """Restore keg insertion date from previous session.""" + """Restore keg state from the previous session and subscribe to manual resets.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() @@ -236,6 +237,18 @@ class PerfectDraftKegFreshnessSensor( pours = last_state.attributes.get("last_pours") if pours is not None: self._last_pours = int(pours) + volume = last_state.attributes.get("last_volume") + if volume is not None: + self._last_volume = float(volume) + + machine_id = (self.coordinator.data or {}).get("_machine_id", "unknown") + self.async_on_remove( + async_dispatcher_connect( + self.hass, + keg_changed_signal(machine_id), + self._handle_manual_keg_change, + ) + ) @property def extra_state_attributes(self) -> dict[str, Any]: @@ -243,6 +256,7 @@ class PerfectDraftKegFreshnessSensor( return { "keg_inserted_at": self._keg_inserted_at.isoformat() if self._keg_inserted_at else None, "last_pours": self._last_pours, + "last_volume": self._last_volume, } @callback @@ -258,18 +272,38 @@ class PerfectDraftKegFreshnessSensor( volume = details.get("kegVolume") if pours is not None and volume is not None: - is_new_keg = ( - pours == 0 - and float(volume) > KEG_NEW_VOLUME_THRESHOLD - and self._last_pours != 0 - ) - if is_new_keg: + 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) super()._handle_coordinator_update() + @callback + def _handle_manual_keg_change(self) -> None: + """Record the keg insertion as now in response to the manual button. + + Rebaselines the tracked pour count and volume to the current readings + so automatic detection does not immediately re-fire. + """ + self._keg_inserted_at = datetime.now(timezone.utc) + + details = (self.coordinator.data or {}).get("details") or {} + pours = details.get("numberOfPoursSinceStartup") + volume = details.get("kegVolume") + if pours is not None: + self._last_pours = int(pours) + if volume is not None: + self._last_volume = float(volume) + + self.async_write_ha_state() + @property def native_value(self) -> int | None: if self._keg_inserted_at is None: diff --git a/custom_components/perfectdraft/strings.json b/custom_components/perfectdraft/strings.json index 18a957c..d6a4f71 100644 --- a/custom_components/perfectdraft/strings.json +++ b/custom_components/perfectdraft/strings.json @@ -46,6 +46,9 @@ "firmware": { "name": "Firmware" }, "mode": { "name": "Mode" }, "keg_freshness": { "name": "Keg Freshness" } + }, + "button": { + "mark_keg_changed": { "name": "Mark Keg Changed" } } }, "options": { diff --git a/custom_components/perfectdraft/translations/en.json b/custom_components/perfectdraft/translations/en.json index 18a957c..d6a4f71 100644 --- a/custom_components/perfectdraft/translations/en.json +++ b/custom_components/perfectdraft/translations/en.json @@ -46,6 +46,9 @@ "firmware": { "name": "Firmware" }, "mode": { "name": "Mode" }, "keg_freshness": { "name": "Keg Freshness" } + }, + "button": { + "mark_keg_changed": { "name": "Mark Keg Changed" } } }, "options": { diff --git a/tests/test_keg_detection.py b/tests/test_keg_detection.py new file mode 100644 index 0000000..75083a7 --- /dev/null +++ b/tests/test_keg_detection.py @@ -0,0 +1,104 @@ +"""Unit tests for the pure keg-change detection logic. + +Runs with the stdlib only (no Home Assistant): the logic under test lives +in ``keg_detection.py`` which has no Home Assistant imports. +""" +import os +import sys +import unittest + +sys.path.insert( + 0, + os.path.join(os.path.dirname(__file__), "..", "custom_components", "perfectdraft"), +) + +from keg_detection import KEG_TOTAL_VOLUME, detect_keg_change # noqa: E402 + + +def litres(pct: float) -> float: + """Convert a remaining percentage to litres against a full keg.""" + return pct / 100 * KEG_TOTAL_VOLUME + + +class TestKegDetection(unittest.TestCase): + # --- Trigger (a): pour reset + near full --- + def test_pour_reset_near_full(self): + self.assertTrue( + detect_keg_change(last_pours=12, last_volume=0.2, pours=0, volume=5.9) + ) + + def test_pour_reset_but_empty_is_not_a_change(self): + self.assertFalse( + detect_keg_change(last_pours=12, last_volume=5.9, pours=0, volume=0.3) + ) + + # --- Trigger (b): below 80% jumping to >= 95% --- + def test_refill_to_near_full(self): + self.assertTrue( + detect_keg_change( + last_pours=5, last_volume=litres(30), pours=6, volume=litres(96) + ) + ) + + def test_refill_from_just_below_80(self): + self.assertTrue( + detect_keg_change( + last_pours=5, last_volume=litres(79), pours=5, volume=litres(96) + ) + ) + + def test_moderate_rise_not_reaching_95_and_under_50_jump(self): + # 30% -> 70%: not (b) [<95] and jump is only 40 points -> no change + self.assertFalse( + detect_keg_change( + last_pours=5, last_volume=litres(30), pours=5, volume=litres(70) + ) + ) + + # --- Trigger (c): >= 50 percentage-point jump --- + def test_large_jump_below_95(self): + # 12% -> 70%: jump of 58 points fires (c) even though it lands below 95% + self.assertTrue( + detect_keg_change( + last_pours=5, last_volume=litres(12), pours=5, volume=litres(70) + ) + ) + + def test_swap_then_immediate_pour(self): + # The motivating case: pour count never reads 0 (it's 1), but volume + # jumps from ~5% to ~92% -> (c) catches it. + self.assertTrue( + detect_keg_change( + last_pours=20, last_volume=litres(5), pours=1, volume=litres(92) + ) + ) + + # --- No-baseline guard --- + def test_first_reading_no_volume_baseline(self): + self.assertFalse( + detect_keg_change(last_pours=3, last_volume=None, pours=4, volume=5.9) + ) + + def test_first_reading_full_keg_pours_zero_still_fires_a(self): + # Preserves original behaviour: a fresh full keg seen first, pours 0. + self.assertTrue( + detect_keg_change(last_pours=None, last_volume=None, pours=0, volume=5.9) + ) + + # --- Normal operation: no false positives --- + def test_normal_pour_decrease(self): + self.assertFalse( + detect_keg_change(last_pours=5, last_volume=5.0, pours=6, volume=4.7) + ) + + def test_small_upward_noise(self): + # +10 points, lands at 60%: neither (b) nor (c) + self.assertFalse( + detect_keg_change( + last_pours=5, last_volume=litres(50), pours=5, volume=litres(60) + ) + ) + + +if __name__ == "__main__": + unittest.main()