Add handling for different STATFLAG formats in APCUPSD (#120870)

* Add handling for different STATFLAG formats

* Just use removesuffix
This commit is contained in:
Yuxin Wang 2024-07-01 01:30:08 -04:00 committed by GitHub
parent 6af9527310
commit 269b8b07c4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 26 additions and 1 deletions

View File

@ -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

View File

@ -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
)