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>
This commit is contained in:
2026-09-06 16:11:07 +02:00
co-authored by Cursor
parent 323e1daff0
commit 133f7082cf
3 changed files with 171 additions and 5 deletions
+2 -5
View File
@@ -26,6 +26,7 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, keg_changed_signal
from .coordinator import PerfectDraftDataUpdateCoordinator
from .keg_detection import KEG_TOTAL_VOLUME, detect_keg_change
from .temperature import beer_temperature
_LOGGER = logging.getLogger(__name__)
@@ -56,11 +57,7 @@ def _get_details(data: dict) -> dict:
def _get_temperature(data: dict) -> float | None:
val = _get_details(data).get("displayedBeerTemperatureInCelsius")
if val is not None and val != 0:
return float(val)
val = _get_details(data).get("temperature")
return float(val) if val is not None else None
return beer_temperature(_get_details(data))
def _get_volume_remaining(data: dict) -> float | None:
@@ -0,0 +1,42 @@
"""Pure temperature extraction logic — no Home Assistant dependencies.
Kept import-free so the validation can be unit-tested standalone,
without a Home Assistant test harness.
"""
from __future__ import annotations
from typing import Any
# Readings outside this closed range are firmware sentinels, not measurements.
# An uninitialised probe reports -128 (0x80 read as a signed 8-bit integer)
# while the refrigeration starts up, and the cloud API relays it verbatim.
TEMP_MIN_PLAUSIBLE = -20.0
TEMP_MAX_PLAUSIBLE = 50.0
def plausible_temperature(value: Any) -> float | None:
"""Return ``value`` as a float when it could be a real reading, else None."""
if value is None:
return None
try:
temp = float(value)
except (TypeError, ValueError):
return None
if not TEMP_MIN_PLAUSIBLE <= temp <= TEMP_MAX_PLAUSIBLE:
return None
return temp
def beer_temperature(details: dict) -> float | None:
"""Pick the beer temperature out of a machine's ``details`` payload.
Prefers ``displayedBeerTemperatureInCelsius`` and falls back to
``temperature``. An implausible or zero displayed value falls through to
the fallback rather than short-circuiting, so a sane fallback still wins
over a sentinel. Zero is rejected on the displayed field only, matching a
firmware that reports 0 before the probe initialises.
"""
displayed = plausible_temperature(details.get("displayedBeerTemperatureInCelsius"))
if displayed is not None and displayed != 0:
return displayed
return plausible_temperature(details.get("temperature"))
+127
View File
@@ -0,0 +1,127 @@
"""Unit tests for the pure temperature extraction logic.
Runs with the stdlib only (no Home Assistant): the logic under test lives
in ``temperature.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 temperature import ( # noqa: E402
TEMP_MAX_PLAUSIBLE,
TEMP_MIN_PLAUSIBLE,
beer_temperature,
)
# The sentinel an uninitialised probe reports: 0x80 as a signed 8-bit integer.
SENTINEL = -128
class TestBeerTemperature(unittest.TestCase):
def test_normal_reading_from_displayed_field(self):
self.assertEqual(
beer_temperature(
{"displayedBeerTemperatureInCelsius": 3, "temperature": 3}
),
3.0,
)
# --- The reported bug: -128 before the probe initialises ---
def test_sentinel_with_no_usable_fallback(self):
self.assertIsNone(
beer_temperature({"displayedBeerTemperatureInCelsius": SENTINEL})
)
def test_sentinel_falls_through_to_plausible_fallback(self):
self.assertEqual(
beer_temperature(
{"displayedBeerTemperatureInCelsius": SENTINEL, "temperature": 4}
),
4.0,
)
def test_sentinel_in_both_fields(self):
self.assertIsNone(
beer_temperature(
{
"displayedBeerTemperatureInCelsius": SENTINEL,
"temperature": SENTINEL,
}
)
)
def test_sentinel_in_fallback_field_only(self):
self.assertIsNone(beer_temperature({"temperature": SENTINEL}))
# --- Pre-existing behaviour that must not regress ---
def test_zero_on_displayed_field_falls_through(self):
self.assertEqual(
beer_temperature(
{"displayedBeerTemperatureInCelsius": 0, "temperature": 5}
),
5.0,
)
def test_fallback_used_when_displayed_absent(self):
self.assertEqual(beer_temperature({"temperature": 6}), 6.0)
def test_no_fields_present(self):
self.assertIsNone(beer_temperature({}))
def test_both_fields_null(self):
self.assertIsNone(
beer_temperature(
{"displayedBeerTemperatureInCelsius": None, "temperature": None}
)
)
# --- Defensive coercion ---
def test_non_numeric_value_does_not_raise(self):
self.assertIsNone(
beer_temperature({"displayedBeerTemperatureInCelsius": "n/a"})
)
def test_numeric_string_is_accepted(self):
self.assertEqual(
beer_temperature({"displayedBeerTemperatureInCelsius": "3.5"}), 3.5
)
# --- Range boundaries are inclusive ---
def test_lower_bound_accepted(self):
self.assertEqual(
beer_temperature(
{"displayedBeerTemperatureInCelsius": TEMP_MIN_PLAUSIBLE}
),
TEMP_MIN_PLAUSIBLE,
)
def test_upper_bound_accepted(self):
self.assertEqual(
beer_temperature(
{"displayedBeerTemperatureInCelsius": TEMP_MAX_PLAUSIBLE}
),
TEMP_MAX_PLAUSIBLE,
)
def test_just_below_lower_bound_rejected(self):
self.assertIsNone(
beer_temperature(
{"displayedBeerTemperatureInCelsius": TEMP_MIN_PLAUSIBLE - 0.1}
)
)
def test_just_above_upper_bound_rejected(self):
self.assertIsNone(
beer_temperature(
{"displayedBeerTemperatureInCelsius": TEMP_MAX_PLAUSIBLE + 0.1}
)
)
if __name__ == "__main__":
unittest.main()