From 269b8b07c46e29153aaef66dc70b2578f1cb550a Mon Sep 17 00:00:00 2001 From: Yuxin Wang Date: Mon, 1 Jul 2024 01:30:08 -0400 Subject: [PATCH] Add handling for different STATFLAG formats in APCUPSD (#120870) * Add handling for different STATFLAG formats * Just use removesuffix --- .../components/apcupsd/binary_sensor.py | 6 +++++- .../components/apcupsd/test_binary_sensor.py | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/apcupsd/binary_sensor.py b/homeassistant/components/apcupsd/binary_sensor.py index 77b2b8591e5..5f86ceb6eec 100644 --- a/homeassistant/components/apcupsd/binary_sensor.py +++ b/homeassistant/components/apcupsd/binary_sensor.py @@ -68,4 +68,8 @@ class OnlineStatus(CoordinatorEntity[APCUPSdCoordinator], BinarySensorEntity): """Returns true if the UPS is online.""" # Check if ONLINE bit is set in STATFLAG. key = self.entity_description.key.upper() - return int(self.coordinator.data[key], 16) & _VALUE_ONLINE_MASK != 0 + # The daemon could either report just a hex ("0x05000008"), or a hex with a "Status Flag" + # suffix ("0x05000008 Status Flag") in older versions. + # Here we trim the suffix if it exists to support both. + flag = self.coordinator.data[key].removesuffix(" Status Flag") + return int(flag, 16) & _VALUE_ONLINE_MASK != 0 diff --git a/tests/components/apcupsd/test_binary_sensor.py b/tests/components/apcupsd/test_binary_sensor.py index 7616a960b21..02351109603 100644 --- a/tests/components/apcupsd/test_binary_sensor.py +++ b/tests/components/apcupsd/test_binary_sensor.py @@ -1,5 +1,7 @@ """Test binary sensors of APCUPSd integration.""" +import pytest + from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from homeassistant.util import slugify @@ -31,3 +33,22 @@ async def test_no_binary_sensor(hass: HomeAssistant) -> None: device_slug = slugify(MOCK_STATUS["UPSNAME"]) state = hass.states.get(f"binary_sensor.{device_slug}_online_status") assert state is None + + +@pytest.mark.parametrize( + ("override", "expected"), + [ + ("0x008", "on"), + ("0x02040010 Status Flag", "off"), + ], +) +async def test_statflag(hass: HomeAssistant, override: str, expected: str) -> None: + """Test binary sensor for different STATFLAG values.""" + status = MOCK_STATUS.copy() + status["STATFLAG"] = override + await async_init_integration(hass, status=status) + + device_slug = slugify(MOCK_STATUS["UPSNAME"]) + assert ( + hass.states.get(f"binary_sensor.{device_slug}_online_status").state == expected + )