Skip to content

Commit

Permalink
Fix display of period-of-time sensors w/ HA 2024.2 (#110)
Browse files Browse the repository at this point in the history
Add state_class to period-of-time sensors.
  • Loading branch information
pnbruckner authored Feb 15, 2024
1 parent 3776437 commit 58d6bcc
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions custom_components/sun2/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
UnitOfTime,
)
from homeassistant.core import CALLBACK_TYPE, CoreState, Event, HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import config_validation as cv, entity_registry as er
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import (
Expand Down Expand Up @@ -443,7 +443,7 @@ def __init__(
device_class=SensorDeviceClass.DURATION,
icon=icon,
native_unit_of_measurement=UnitOfTime.HOURS,
suggested_display_precision=3,
state_class=SensorStateClass.MEASUREMENT,
)
super().__init__(loc_params, extra, entity_description, SUN_APPARENT_RADIUS)

Expand All @@ -460,6 +460,30 @@ def extra_state_attributes(self) -> Mapping[str, Any] | None:
)
return data

async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass."""
await super().async_added_to_hass()

# In 3.1.0 and earlier, entity_description.suggested_display_precision was set
# to 3. Starting with HA 2024.2, that causes the state to be displayed as a
# float instead of HH:MM:SS. To fix that
# entity_description.suggested_display_precision is no longer being set.
# However, due to a bug in the sensor component, that value is not getting
# properly removed from the entity registry, causing the state to still be
# displayed as a float. To work around that bug, we'll forcibly remove it from
# the registry here if necessary.
ent_reg = er.async_get(self.hass)
sensor_options: Mapping[str, Any] = ent_reg.entities[
self.entity_id
].options.get(SENSOR_DOMAIN, {})
if sensor_options.get("suggested_display_precision") is None:
return
sensor_options = dict(sensor_options)
del sensor_options["suggested_display_precision"]
ent_reg.async_update_entity_options(
self.entity_id, SENSOR_DOMAIN, sensor_options or None
)

def _astral_event(
self,
date_or_dttm: date | datetime,
Expand Down

0 comments on commit 58d6bcc

Please sign in to comment.