Skip to content

Home Information - Your home, your data, organized.

Python

Issue #310: Consolidate polling-update paths (#314)

Tony C5ba768a51795
diff --git a/src/hi/apps/api/tests/test_views.py b/src/hi/apps/api/tests/test_views.py
index 60a27f2a..ca7823a2 100644
--- a/src/hi/apps/api/tests/test_views.py
+++ b/src/hi/apps/api/tests/test_views.py
@@ -29,7 +29,7 @@ class TestStatusView(AsyncViewTestCase):
self.assertIn('timestamp', data)
self.assertIn('startTimestamp', data)
self.assertIn('alertData', data)
- self.assertIn('cssClassUpdateMap', data)
+ self.assertIn('entityStateStatusMap', data)
self.assertIn('idReplaceUpdateMap', data)
self.assertIn('idReplaceHashMap', data)
self.assertIn('consoleLocked', data)
diff --git a/src/hi/apps/api/views.py b/src/hi/apps/api/views.py
index 359296c1..d37f4174 100644
--- a/src/hi/apps/api/views.py
+++ b/src/hi/apps/api/views.py
@@ -33,8 +33,7 @@ class StatusView( View,
ServerTimestampAttr = 'timestamp'
LastServerTimestampAttr = 'lastTimestamp'
AlertStatusDataAttr = 'alertData'
- CssClassUpdateMapAttr = 'cssClassUpdateMap'
- CssControllerValueMapAttr = 'cssControllerValueMap'
+ EntityStateStatusMapAttr = 'entityStateStatusMap'
IdReplaceUpdateMapAttr = 'idReplaceUpdateMap'
IdReplaceHashMapAttr = 'idReplaceHashMap'
ConsoleLockedAttr = 'consoleLocked'
@@ -70,10 +69,7 @@ class StatusView( View,
id_replace_map.update( self.security_manager().get_status_id_replace_map( request = request ) )
id_replace_map.update( self.weather_manager().get_status_id_replace_map( request = request ) )
- css_class_update_map = dict()
- css_class_update_map.update( StatusDisplayManager().get_status_css_class_update_map() )
-
- css_controller_value_map = StatusDisplayManager().get_status_controller_value_map()
+ entity_state_status_map = StatusDisplayManager().get_entity_state_status_map()
# Hash provided for client to prevent unneeded DOM updates since
# they can interfer with user interactions.
@@ -93,8 +89,7 @@ class StatusView( View,
self.ServerStartTimestampAttr: server_start_datetime.isoformat(),
self.ServerTimestampAttr: server_datetime.isoformat(),
self.AlertStatusDataAttr: alert_status_data.to_dict( request = request ),
- self.CssClassUpdateMapAttr: css_class_update_map,
- self.CssControllerValueMapAttr: css_controller_value_map,
+ self.EntityStateStatusMapAttr: entity_state_status_map,
self.IdReplaceUpdateMapAttr: id_replace_map,
self.IdReplaceHashMapAttr: id_replace_hash_map,
self.ConsoleLockedAttr: request.session.get(
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 20766d70..f3af72e9 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -1,6 +1,7 @@
from typing import List, Set, Tuple
from hi.apps.common.enums import LabeledEnum
+from hi.apps.common.utils import get_humanized_name
class EntityType(LabeledEnum):
@@ -188,6 +189,15 @@ class EntityType(LabeledEnum):
class EntityStateValue(LabeledEnum):
+ # Alarm-style values (e.g., ACTIVE, OPEN, SMOKE_DETECTED) are
+ # rendered as the ``status`` attribute on both the SVG icon
+ # ``g`` element and the sensor card ``div``. Each new pair
+ # needs matching ``g[status="..."]`` and ``div[status="..."]``
+ # rules in main.css for the resting and alarmed states (the
+ # resting state may legitimately omit the ``g`` rule when no
+ # glow is wanted). Missing rules surface as a first-paint
+ # color flash that disappears on the first poll once the
+ # bucketed StatusStyle value gets applied.
ACTIVE = ( 'Active', '' )
IDLE = ( 'Idle', '' )
@@ -222,6 +232,23 @@ class EntityStateValue(LabeledEnum):
COLOR_MODE_XY = ( 'XY Color', '' )
COLOR_MODE_WHITE = ( 'White', '' )
+ @classmethod
+ def to_display_label( cls, wire_value : str ) -> str:
+ """Resolve a stored wire value to a display label. Known
+ enum members return their authoritative ``.label``;
+ free-form wire values (e.g., HA's ``'heating'``,
+ ``'fan_only'``) are humanized into title case. Numeric
+ values pass through unchanged so the humanizer doesn't
+ mangle them."""
+ if not wire_value:
+ return wire_value
+ try:
+ return cls.from_name( wire_value ).label
+ except ValueError:
+ if wire_value[ 0 ].isdigit():
+ return wire_value
+ return get_humanized_name( wire_value )
+
class EntityStateType(LabeledEnum):
@@ -247,20 +274,15 @@ class EntityStateType(LabeledEnum):
[] )
# COLOR_MODE reports which lighting mode a smart bulb is
# currently in (e.g., HS color, white temperature, basic
- # on/off). Read-only sensor; HA derives the value from
- # whichever attribute was most recently written. The value
- # set is the ``COLOR_MODE_*`` family of EntityStateValues.
+ # on/off). The per-device supported subset is declared by HA
+ # in ``supported_color_modes`` and captured in
+ # ``value_range_str`` at import time, so ``choices()`` reads
+ # from there rather than enumerating every COLOR_MODE_*
+ # member here. The COLOR_MODE_* EntityStateValue members
+ # still provide authoritative labels for display via
+ # ``to_display_label``.
COLOR_MODE = ( 'Color Mode' , 'Active lighting color mode',
- [ EntityStateValue.COLOR_MODE_UNKNOWN,
- EntityStateValue.COLOR_MODE_ONOFF,
- EntityStateValue.COLOR_MODE_BRIGHTNESS,
- EntityStateValue.COLOR_MODE_COLOR_TEMP,
- EntityStateValue.COLOR_MODE_HS,
- EntityStateValue.COLOR_MODE_RGB,
- EntityStateValue.COLOR_MODE_RGBW,
- EntityStateValue.COLOR_MODE_RGBWW,
- EntityStateValue.COLOR_MODE_XY,
- EntityStateValue.COLOR_MODE_WHITE ] )
+ [] )
# COLOR_TEMPERATURE is the white-light Kelvin scale
# (warm 2000K to cool 6500K); distinct from a chromatic
# color (HUE+SATURATION) since the underlying physics and
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 6762902b..869341f8 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -11,6 +11,7 @@ from hi.apps.location.models import (
LocationView,
)
from hi.apps.attribute.models import AttributeModel, SoftDeleteAttributeModel, AttributeValueHistoryModel
+from hi.apps.common.utils import get_humanized_name
from hi.integrations.models import IntegrationDetailsModel
from hi.enums import ItemType
@@ -216,20 +217,34 @@ class EntityState( models.Model ):
return
def choices(self) -> List[ Tuple[str,str] ]:
- if self.value_range_str:
- try:
- value_range = json.loads( self.value_range_str )
- if (( len(value_range) == 2 )
- and ( 'min' in value_range )
- and ( 'max' in value_range )):
- return list()
- if isinstance( value_range, dict ):
- return [ ( str(k), str(v) ) for k, v in value_range.items() ]
- if isinstance( value_range, list ):
- return [ ( str(x), str(x) ) for x in value_range ]
- except json.JSONDecodeError:
- pass
- return self.entity_state_type.choices()
+ # State types whose ``entity_state_value_list`` is populated
+ # (OPEN_CLOSE, SMOKE, ON_OFF, ...) carry authoritative
+ # labels on their EntityStateValue members. Free-form
+ # discrete sets (DISCRETE state type, e.g., HA hvac_mode /
+ # fan preset) store only wire values in
+ # ``value_range_str`` and rely on the humanizer for
+ # readable labels.
+ type_choices = self.entity_state_type.choices()
+ if type_choices:
+ return type_choices
+ if not self.value_range_str:
+ return list()
+ try:
+ value_range = json.loads( self.value_range_str )
+ except json.JSONDecodeError:
+ return list()
+ if ( isinstance( value_range, dict )
+ and len( value_range ) == 2
+ and 'min' in value_range
+ and 'max' in value_range ):
+ return list()
+ if isinstance( value_range, dict ):
+ wire_values = list( value_range.keys() )
+ elif isinstance( value_range, list ):
+ wire_values = value_range
+ else:
+ return list()
+ return [ ( str(v), get_humanized_name( str(v) ) ) for v in wire_values ]
def toggle_values(self) -> List[str]:
if self.value_range_str:
diff --git a/src/hi/apps/entity/templatetags/entity_tags.py b/src/hi/apps/entity/templatetags/entity_tags.py
index 1da9c0b2..d5a8adb4 100644
--- a/src/hi/apps/entity/templatetags/entity_tags.py
+++ b/src/hi/apps/entity/templatetags/entity_tags.py
@@ -7,14 +7,8 @@ register = template.Library()
@register.filter
def value_label( value ):
- """Resolve a stored ``EntityStateValue`` wire string (the
- lowercased enum name, e.g., ``'smoke_detected'``) to its
- human-readable label (e.g., ``'Smoke Detected'``). Returns
- the input unchanged when it doesn't match an enum member —
- keeps numeric / free-form values rendering as-is."""
- if not value:
- return value
- try:
- return EntityStateValue.from_name( value ).label
- except ValueError:
- return value
+ """Resolve a stored wire value to its display label via
+ ``EntityStateValue.to_display_label`` — enum members return
+ their authoritative label, free-form names get humanized,
+ numeric values pass through."""
+ return EntityStateValue.to_display_label( value )
diff --git a/src/hi/apps/entity/tests/test_entity_tags.py b/src/hi/apps/entity/tests/test_entity_tags.py
index 2f2ad53e..6c91bd51 100644
--- a/src/hi/apps/entity/tests/test_entity_tags.py
+++ b/src/hi/apps/entity/tests/test_entity_tags.py
@@ -23,11 +23,17 @@ class TestValueLabel(BaseTestCase):
self.assertEqual( value_label( 'active' ), 'Active' )
self.assertEqual( value_label( 'closed' ), 'Closed' )
- def test_unknown_value_passes_through(self):
- # Numeric / free-form values (e.g., temperatures, raw
- # device strings) aren't enum members and must not raise.
+ def test_numeric_value_passes_through(self):
+ # Temperatures and other numeric values must not get
+ # mangled by humanization.
self.assertEqual( value_label( '72.5' ), '72.5' )
- self.assertEqual( value_label( 'arbitrary' ), 'arbitrary' )
+
+ def test_non_enum_name_value_humanized(self):
+ # Free-form wire values that aren't enum members (e.g., HA
+ # hvac_action values like 'heating') get humanized into a
+ # readable label.
+ self.assertEqual( value_label( 'heating' ), 'Heating' )
+ self.assertEqual( value_label( 'fan_only' ), 'Fan Only' )
def test_empty_and_none_pass_through(self):
self.assertEqual( value_label( '' ), '' )
diff --git a/src/hi/apps/entity/tests/test_models.py b/src/hi/apps/entity/tests/test_models.py
index 2d9ca8a0..111e4b9d 100644
--- a/src/hi/apps/entity/tests/test_models.py
+++ b/src/hi/apps/entity/tests/test_models.py
@@ -447,5 +447,55 @@ class TestEntityState(BaseTestCase):
self.assertFalse(EntityAttribute.objects.filter(id=specs_attr_id).exists())
self.assertFalse(EntityState.objects.filter(id=power_state_id).exists())
self.assertFalse(EntityState.objects.filter(id=temp_state_id).exists())
-
+
return
+
+
+class TestEntityStateChoices(BaseTestCase):
+ """``EntityState.choices()`` derives labels for the discrete
+ controller dropdown. Two paths: enum-bound state types use
+ EntityStateValue labels directly; free-form discrete state
+ types humanize wire values."""
+
+ def setUp(self):
+ super().setUp()
+ self.entity = Entity.objects.create(
+ name='Test', entity_type_str=str(EntityType.OTHER),
+ )
+
+ def test_enum_bound_state_type_uses_entity_state_value_labels(self):
+ # OPEN_CLOSE has an authoritative EntityStateValue list;
+ # labels come from those members, not from value_range_str.
+ state = EntityState.objects.create(
+ entity=self.entity,
+ entity_state_type_str=str(EntityStateType.OPEN_CLOSE),
+ name='Door',
+ )
+ self.assertEqual(
+ state.choices(),
+ [('open', 'Open'), ('closed', 'Closed')],
+ )
+
+ def test_discrete_state_humanizes_wire_values(self):
+ # DISCRETE has no enum-bound value list. Wire values
+ # captured in value_range_str (e.g., HA hvac_mode names)
+ # get humanized into readable labels — the dropdown shows
+ # "Heat Cool" / "Fan Only" instead of the snake_case wire.
+ state = EntityState.objects.create(
+ entity=self.entity,
+ entity_state_type_str=str(EntityStateType.DISCRETE),
+ name='HVAC Mode',
+ value_range_str=json.dumps({
+ 'heat_cool': 'heat_cool',
+ 'fan_only': 'fan_only',
+ 'off': 'off',
+ }),
+ )
+ self.assertEqual(
+ state.choices(),
+ [
+ ('heat_cool', 'Heat Cool'),
+ ('fan_only', 'Fan Only'),
+ ('off', 'Off'),
+ ],
+ )
diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.py
index 4ef572d9..8f081882 100644
--- a/src/hi/apps/monitor/status_display_data.py
+++ b/src/hi/apps/monitor/status_display_data.py
@@ -30,6 +30,15 @@ class StatusDisplayData:
self._sensor_response_list = entity_state_status_data.sensor_response_list
self._controller_data_list = entity_state_status_data.controller_data_list
+ # Compute once at init — every downstream consumer
+ # (svg_status_style fallback, controller_data_value,
+ # latest_display_label, to_polling_update_dict) reads
+ # this through the property, so the ConsoleConverterHelper
+ # lookup runs only once per instance.
+ self._latest_display_value = ConsoleConverterHelper.from_entity_state_value(
+ entity_state_value = self.latest_sensor_value,
+ entity_state = self._entity_state,
+ )
self._svg_status_style = self._get_svg_status_style()
self._controller_data_value = self._get_controller_data_value()
return
@@ -96,10 +105,36 @@ class StatusDisplayData:
magnitude and unit_symbol so consumers can format per
their need (slider's numeric ``value=`` uses ``.magnitude``;
status text uses ``str(...)`` which combines both)."""
- return ConsoleConverterHelper.from_entity_state_value(
- entity_state_value = self.latest_sensor_value,
- entity_state = self._entity_state,
- )
+ return self._latest_display_value
+
+ @property
+ def latest_display_label(self) -> str:
+ """Human-readable display string for the current sensor
+ value — universal source of truth for the polling-refresh
+ display text. Unit-bearing states get the combined
+ magnitude+unit form (``"72.0°F"``); other values resolve
+ through ``EntityStateValue.to_display_label`` (enum label,
+ humanized free-form, or numeric pass-through)."""
+ combined = str( self.latest_display_value )
+ return EntityStateValue.to_display_label( combined )
+
+ def to_polling_update_dict(self) -> dict:
+ """Build the per-EntityState row of ``entityStateStatusMap``.
+ Carries the three UI update pieces: DOM attributes,
+ controller widget state, and the human-readable display
+ text."""
+ display_value = self.latest_display_value
+ display_dict = { 'text': self.latest_display_label }
+ if display_value.unit_symbol:
+ display_dict[ 'magnitude' ] = display_value.magnitude
+ display_dict[ 'unit_symbol' ] = display_value.unit_symbol
+ row = {
+ 'attributes': self.attribute_dict,
+ 'display_value': display_dict,
+ }
+ if self.controller_data_value is not None:
+ row[ 'controller' ] = { 'value': self.controller_data_value }
+ return row
@property
def penultimate_sensor_value(self):
diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.py
index 443c6689..64816454 100644
--- a/src/hi/apps/monitor/status_display_manager.py
+++ b/src/hi/apps/monitor/status_display_manager.py
@@ -30,60 +30,34 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
)
return
- def get_status_css_class_update_map( self ) -> Dict[ str, str ]:
+ def get_entity_state_status_map( self ) -> Dict[ str, dict ]:
+ """Build the per-EntityState polling-update map consumed by
+ the client. One pass through ``StatusDisplayData`` per
+ EntityState produces all three UI update pieces
+ (attributes, controller, display_value) in one structure."""
entity_state_status_data_list = self.get_all_entity_state_status_data_list()
- status_display_data_list = [ StatusDisplayData(x) for x in entity_state_status_data_list ]
- css_class_update_map = dict()
- for status_display_data in status_display_data_list:
- if status_display_data.should_skip:
- continue
- css_class_update_map[status_display_data.css_class] = status_display_data.attribute_dict
+ status_map : Dict[ str, dict ] = {}
+ for entity_state_status_data in entity_state_status_data_list:
+ status_display_data = StatusDisplayData( entity_state_status_data )
+ status_map[ status_display_data.css_class ] = (
+ status_display_data.to_polling_update_dict()
+ )
if settings.DEBUG and settings.DEBUG_TRACE_STATE:
latest = status_display_data.sensor_response_list[ 0 ]
DevOverrideManager.trace_state(
- 'hi.ui_poll.sensor.out',
+ 'hi.ui_poll.entity_state.out',
ha_entity_id = latest.integration_key.integration_name,
hi_entity_state_id = status_display_data.entity_state.id,
hi_value = latest.value,
- attribute_dict = status_display_data.attribute_dict,
+ row = status_map[ status_display_data.css_class ],
)
continue
- return css_class_update_map
+ return status_map
- def get_status_controller_value_map( self ) -> Dict[ str, object ]:
- """Build the class-to-controller-value map consumed by the
- polling response's ``cssControllerValueMap`` key. Parallel
- to ``get_status_css_class_update_map`` but for value-bearing
- controller widgets (slider, checkbox, select, future color
- picker) rather than CSS-driven visual styling. States with
- no controller (read-only sensors) are skipped — see
- ``StatusDisplayData.controller_data_value``."""
-
- entity_state_status_data_list = self.get_all_entity_state_status_data_list()
- status_display_data_list = [ StatusDisplayData(x) for x in entity_state_status_data_list ]
-
- controller_value_map = dict()
- for status_display_data in status_display_data_list:
- controller_value = status_display_data.controller_data_value
- if controller_value is None:
- continue
- controller_value_map[ status_display_data.css_class ] = controller_value
- if settings.DEBUG and settings.DEBUG_TRACE_STATE:
- latest = status_display_data.sensor_response_list[ 0 ]
- DevOverrideManager.trace_state(
- 'hi.ui_poll.controller.out',
- ha_entity_id = latest.integration_key.integration_name,
- hi_entity_state_id = status_display_data.entity_state.id,
- hi_value = controller_value,
- raw_value = latest.value,
- )
- continue
- return controller_value_map
-
def get_all_entity_state_status_data_list( self ) -> List[ EntityStateStatusData ]:
"""
Gets the latest sensor responses for all EntityStates. Used by client
diff --git a/src/hi/apps/monitor/tests/test_status_display_data.py b/src/hi/apps/monitor/tests/test_status_display_data.py
index 07d0c100..a63864bd 100644
--- a/src/hi/apps/monitor/tests/test_status_display_data.py
+++ b/src/hi/apps/monitor/tests/test_status_display_data.py
@@ -598,7 +598,196 @@ class TestStatusDisplayData(BaseTestCase):
response1 = self._create_mock_sensor_response('VALUE1')
response2 = self._create_mock_sensor_response('VALUE2')
status_data = self._create_entity_state_status_data('ON_OFF', [response1, response2])
-
+
display_data = StatusDisplayData(status_data)
-
+
self.assertEqual(display_data.penultimate_sensor_value, 'VALUE2')
+
+
+class TestLatestDisplayLabel(BaseTestCase):
+ """``latest_display_label`` is the universal source of truth for
+ the polling-refresh display text. Unit-bearing states get the
+ combined ``DisplayValue`` string; unit-less enum states get the
+ labeled form; unit-less numeric / free-form passes through."""
+
+ def setUp(self):
+ super().setUp()
+ self.entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='SENSOR',
+ )
+
+ def _make_display_data(self, entity_state_type_str, value, units=None):
+ entity_state = EntityState.objects.create(
+ entity = self.entity,
+ entity_state_type_str = entity_state_type_str,
+ units = units,
+ )
+ response = Mock(spec=SensorResponse)
+ response.value = value
+ response.timestamp = datetime.now()
+ status_data = EntityStateStatusData(
+ entity_state = entity_state,
+ sensor_response_list = [ response ],
+ controller_data_list = [],
+ )
+ return StatusDisplayData( status_data )
+
+ def test_unit_less_enum_value_returns_labeled_form(self):
+ # ``smoke_detected`` (wire form) → ``Smoke Detected``
+ # (human-readable label) — matches what the ``value_label``
+ # template filter produces on initial render.
+ display_data = self._make_display_data(
+ 'SMOKE', str(EntityStateValue.SMOKE_DETECTED),
+ )
+ self.assertEqual( display_data.latest_display_label, 'Smoke Detected' )
+
+ def test_unit_less_enum_movement_active_returns_active(self):
+ display_data = self._make_display_data(
+ 'MOVEMENT', str(EntityStateValue.ACTIVE),
+ )
+ self.assertEqual( display_data.latest_display_label, 'Active' )
+
+ def test_unit_bearing_temperature_returns_combined_form(self):
+ # Stored canonical °C; default display unit is °F unless
+ # the test environment overrides. The exact magnitude depends
+ # on the user-preference test default — pin the structural
+ # contract (non-empty string containing a temperature unit
+ # symbol) rather than the exact magnitude.
+ display_data = self._make_display_data(
+ 'TEMPERATURE', '21', units = '°C',
+ )
+ label = display_data.latest_display_label
+ self.assertTrue( label )
+ self.assertTrue(
+ '°F' in label or '°C' in label,
+ f'expected temperature unit symbol in label, got {label!r}',
+ )
+
+ def test_unit_less_numeric_passes_through(self):
+ # A POWER_LEVEL or LIGHT_DIMMER raw value like ``"75"`` isn't
+ # an enum member; the label must equal the input unchanged.
+ display_data = self._make_display_data( 'POWER_LEVEL', '75' )
+ self.assertEqual( display_data.latest_display_label, '75' )
+
+ def test_empty_value_returns_empty_string(self):
+ # Defensive: a sensor with no responses yet has empty
+ # latest_sensor_value → label is empty (no crash, no enum
+ # lookup attempt).
+ entity_state = EntityState.objects.create(
+ entity = self.entity, entity_state_type_str = 'MOVEMENT',
+ )
+ status_data = EntityStateStatusData(
+ entity_state = entity_state,
+ sensor_response_list = [],
+ controller_data_list = [],
+ )
+ display_data = StatusDisplayData( status_data )
+ self.assertEqual( display_data.latest_display_label, '' )
+
+
+class TestToPollingUpdateDict(BaseTestCase):
+ """``to_polling_update_dict`` builds the per-EntityState row of
+ the unified ``entityStateStatusMap``. Pins the contract for
+ each kind of EntityState the polling path sees: sensor-only
+ (no ``controller`` key), unit-bearing (``magnitude`` and
+ ``unit_symbol`` present in display_value), unit-less enum
+ (``magnitude``/``unit_symbol`` absent), and the always-present
+ ``attributes`` and ``display_value`` keys."""
+
+ def setUp(self):
+ super().setUp()
+ self.entity = Entity.objects.create(
+ name = 'Test Entity', entity_type_str = 'SENSOR',
+ )
+
+ def _make_display_data(self, entity_state_type_str, value,
+ units=None, with_controller=False):
+ entity_state = EntityState.objects.create(
+ entity = self.entity,
+ entity_state_type_str = entity_state_type_str,
+ units = units,
+ )
+ response = Mock(spec=SensorResponse)
+ response.value = value
+ response.timestamp = datetime.now()
+ controller_data_list = []
+ if with_controller:
+ controller = Mock()
+ controller.entity_state = entity_state
+ controller_data_list = [ Mock(controller=controller) ]
+ status_data = EntityStateStatusData(
+ entity_state = entity_state,
+ sensor_response_list = [ response ],
+ controller_data_list = controller_data_list,
+ )
+ return StatusDisplayData( status_data )
+
+ def test_sensor_only_row_omits_controller_key(self):
+ display_data = self._make_display_data(
+ 'MOVEMENT', str(EntityStateValue.ACTIVE),
+ )
+ row = display_data.to_polling_update_dict()
+ self.assertNotIn( 'controller', row )
+
+ def test_controller_bearing_row_has_controller_value_dict(self):
+ display_data = self._make_display_data(
+ 'ON_OFF', str(EntityStateValue.ON), with_controller=True,
+ )
+ row = display_data.to_polling_update_dict()
+ self.assertIn( 'controller', row )
+ self.assertIn( 'value', row[ 'controller' ] )
+
+ def test_unit_bearing_display_value_includes_magnitude_and_unit(self):
+ display_data = self._make_display_data(
+ 'TEMPERATURE', '21', units = '°C',
+ )
+ row = display_data.to_polling_update_dict()
+ display_value = row[ 'display_value' ]
+ self.assertIn( 'text', display_value )
+ self.assertIn( 'magnitude', display_value )
+ self.assertIn( 'unit_symbol', display_value )
+
+ def test_unit_less_display_value_omits_magnitude_and_unit(self):
+ display_data = self._make_display_data(
+ 'MOVEMENT', str(EntityStateValue.ACTIVE),
+ )
+ row = display_data.to_polling_update_dict()
+ display_value = row[ 'display_value' ]
+ self.assertIn( 'text', display_value )
+ self.assertNotIn( 'magnitude', display_value )
+ self.assertNotIn( 'unit_symbol', display_value )
+
+ def test_display_value_text_is_human_readable_label(self):
+ # Same source of truth as ``value_label`` template filter —
+ # JS sets element.textContent to this string.
+ display_data = self._make_display_data(
+ 'SMOKE', str(EntityStateValue.SMOKE_DETECTED),
+ )
+ row = display_data.to_polling_update_dict()
+ self.assertEqual(
+ row[ 'display_value' ][ 'text' ], 'Smoke Detected',
+ )
+
+ def test_display_value_text_humanizes_free_form_wire_value(self):
+ # DISCRETE-typed states (HA hvac_action, fan preset, etc.)
+ # carry free-form wire values not bound to an
+ # EntityStateValue member. The polling map's
+ # ``display_value.text`` humanizes them so the sensor card
+ # displays a readable label on poll refresh — the headline
+ # behavior of #310.
+ display_data = self._make_display_data( 'DISCRETE', 'heating' )
+ row = display_data.to_polling_update_dict()
+ self.assertEqual(
+ row[ 'display_value' ][ 'text' ], 'Heating',
+ )
+
+ def test_attributes_always_present(self):
+ # Even for unrecognized values where there's no SVG style,
+ # ``attributes`` is always emitted (possibly as an empty
+ # dict) — the JS dispatcher iterates whatever keys it
+ # finds and is safe with an empty mapping.
+ display_data = self._make_display_data( 'ON_OFF', 'INVALID' )
+ row = display_data.to_polling_update_dict()
+ self.assertIn( 'attributes', row )
+ self.assertIsInstance( row[ 'attributes' ], dict )
diff --git a/src/hi/apps/monitor/tests/test_status_display_manager.py b/src/hi/apps/monitor/tests/test_status_display_manager.py
index ba3b59fd..c59bc232 100644
--- a/src/hi/apps/monitor/tests/test_status_display_manager.py
+++ b/src/hi/apps/monitor/tests/test_status_display_manager.py
@@ -1,4 +1,5 @@
import logging
+from datetime import datetime
from unittest.mock import Mock, patch
from hi.apps.entity.models import Entity, EntityState
@@ -219,18 +220,51 @@ class TestStatusDisplayManager(BaseTestCase):
entity1 = Entity.objects.create(name='Entity 1', entity_type_str='CAMERA')
entity2 = Entity.objects.create(name='Entity 2', entity_type_str='LIGHT')
entity3 = Entity.objects.create(name='Entity 3', entity_type_str='SENSOR')
-
+
entities = [entity1, entity2, entity3]
-
+
manager = StatusDisplayManager()
-
+
with patch.object(manager, '_get_entity_to_entity_status_data') as mock_method:
mock_method.return_value = {} # Empty results
-
+
result_list = manager.get_entity_status_data_list(entities)
-
+
# Should maintain same order as input
self.assertEqual(len(result_list), 3)
self.assertEqual(result_list[0].entity, entity1)
self.assertEqual(result_list[1].entity, entity2)
self.assertEqual(result_list[2].entity, entity3)
+
+ def test_get_entity_state_status_map_includes_states_without_svg_style(self):
+ # The unified map emits a row for every EntityState with a
+ # response, even those whose value produces no
+ # ``svg_status_style`` (e.g., ON_OFF with an unrecognized
+ # value). The pre-refactor ``cssClassUpdateMap`` skipped
+ # these; the unified shape carries display_value and
+ # (when applicable) controller updates which remain useful
+ # independent of icon styling, so they're always
+ # emitted with an empty ``attributes`` dict.
+ entity = Entity.objects.create(
+ name='Unrecognized State', entity_type_str='SENSOR',
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity, entity_state_type_str='ON_OFF',
+ )
+ response = Mock(spec=SensorResponse)
+ response.value = 'INVALID' # not 'on' / 'off' → no svg_status_style
+ response.timestamp = datetime.now()
+ status_data = EntityStateStatusData(
+ entity_state=entity_state,
+ sensor_response_list=[response],
+ controller_data_list=[],
+ )
+
+ manager = StatusDisplayManager()
+ with patch.object(
+ manager, 'get_all_entity_state_status_data_list',
+ return_value=[status_data]):
+ result = manager.get_entity_state_status_map()
+
+ self.assertIn(entity_state.css_class, result)
+ self.assertEqual(result[entity_state.css_class]['attributes'], {})
diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
index 13a1ba5a..737c89e7 100644
--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html
@@ -1,2 +1,2 @@
{% load entity_tags units %}
-<div class="text-center px-2" status="{{ sensor_response.value }}">{% if sensor_response.sensor.entity_state.units %}{{ sensor_response.value|as_display_value:sensor_response.sensor.entity_state }}{% else %}{{ sensor_response.value|value_label }}{% endif %}</div>
+<div class="text-center px-2" status="{{ sensor_response.value }}" display-text>{% if sensor_response.sensor.entity_state.units %}{{ sensor_response.value|as_display_value:sensor_response.sensor.entity_state }}{% else %}{{ sensor_response.value|value_label }}{% endif %}</div>
diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html
index aa559447..f0c445a3 100644
--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html
+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html
@@ -6,6 +6,6 @@ the ``as_display_value`` filter goes through ``ConsoleConverterHelper``
to produce a ``DisplayValue`` whose ``__str__`` combines the
user-display magnitude and unit symbol.
{% endcomment %}
-<div class="text-center px-2" status="{{ sensor_response.value }}">
+<div class="text-center px-2" status="{{ sensor_response.value }}" display-text>
{{ sensor_response.value|as_display_value:sensor_response.sensor.entity_state }}
</div>
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index fdab7354..2ab2a960 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -1335,6 +1335,7 @@ class HassConverter:
entity_state_type = EntityStateType.HUMIDITY,
is_controllable = False,
label = 'Current Humidity',
+ units = str(HumidityUnit.PERCENT),
))
return specs
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index c1ce3cf0..82e6c106 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -291,6 +291,7 @@ PIPELINE = {
'js_hi_grid_content': {
'source_filenames': (
'js/svg-utils.js',
+ 'js/entity_state_status.js',
'js/status.js',
'js/auto-view.js',
'js/edit-dragdrop.js',
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index fa458ebe..d02720eb 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -824,6 +824,14 @@ div[status="low"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
+div[status="smoke_clear"] {
+ color: var(--on-status-ok-color);
+ background-color: var(--status-ok-color);
+}
+div[status="smoke_detected"] {
+ color: var(--on-status-bad-color);
+ background-color: var(--status-bad-color);
+}
g[hover] {
filter: drop-shadow(0 0 10px var(--status-hover-color)) !important;
diff --git a/src/hi/static/js/controllers.js b/src/hi/static/js/controllers.js
index 56522dfe..301c6043 100644
--- a/src/hi/static/js/controllers.js
+++ b/src/hi/static/js/controllers.js
@@ -8,19 +8,12 @@
* provides (e.g., the dimmer's Off / Full convenience
* buttons that drive the brightness slider).
*
- * 2. Apply server-pushed controller values to widgets via
- * ``Hi.controllers.applyValueMap`` — called by the polling
- * layer with the ``cssControllerValueMap`` from the status
- * response. Each map entry is a class-name → value pair;
- * every element matching the class gets its widget property
- * updated (slider ``.value``, checkbox ``.checked``,
- * ``<select>`` ``.value``, etc.).
- *
- * The controller-value path is parallel to the existing CSS-class
- * status path (status drives icon styling via attributes; values
- * drive interactive widget state via DOM properties). Replaces
- * the older checkbox+select special-cases that were inlined in
- * status.js's CSS-class-update handler.
+ * 2. Apply server-pushed controller widget state via
+ * ``Hi.controllers.applyValueMap``. Each map entry is keyed
+ * by CSS class and carries a controller-state dict
+ * ({value, ...}); every element matching the class gets its
+ * widget property updated (slider ``.value``, checkbox
+ * ``.checked``, ``<select>`` ``.value``, etc.).
*/
(function() {
'use strict';
@@ -37,18 +30,19 @@
const _activeSliders = new WeakSet();
/**
- * Apply a class-name → controller-value map by finding each
+ * Apply a class-name → controller-state map by finding each
* matching element and updating the appropriate widget
* property. Only applies updates when the new value differs
* from the widget's current state — avoids interfering with
* an in-progress user interaction (e.g., a slider mid-drag
* whose optimistic update already matches the polled value).
*
- * @param {Object} controllerValueMap - { className: value }
+ * @param {Object} controllerMap - { className: { value, ... } }
*/
- Hi.controllers.applyValueMap = function( controllerValueMap ) {
- if ( !controllerValueMap ) return;
- Object.entries( controllerValueMap ).forEach( function( [ cssClass, value ] ) {
+ Hi.controllers.applyValueMap = function( controllerMap ) {
+ if ( !controllerMap ) return;
+ Object.entries( controllerMap ).forEach( function( [ cssClass, controllerDict ] ) {
+ const value = controllerDict.value;
const $elements = $( '.' + cssClass );
$elements.each( function() {
_applyValueToElement( this, value );
diff --git a/src/hi/static/js/entity_state_status.js b/src/hi/static/js/entity_state_status.js
new file mode 100644
index 00000000..eafbec98
--- /dev/null
+++ b/src/hi/static/js/entity_state_status.js
@@ -0,0 +1,85 @@
+/*
+ * Home Information - Entity-state status updates
+ *
+ * Consumes the ``entityStateStatusMap`` from the polling response
+ * and applies per-EntityState UI updates. Each map entry is keyed
+ * by CSS class and may carry:
+ *
+ * attributes DOM attributes to set on every matching element
+ * (status, stroke, fill, etc.).
+ * controller Controller widget state ({value, ...}) for the
+ * matching elements; absent for sensor-only states.
+ * display_value Display strings for the sensor card.
+ */
+(function() {
+ 'use strict';
+
+ window.Hi = window.Hi || {};
+ Hi.entityStateStatus = Hi.entityStateStatus || {};
+
+ Hi.entityStateStatus.apply = function( statusMap ) {
+ if ( ! statusMap ) return;
+ const controllerSubMap = {};
+ for ( const cssClass in statusMap ) {
+ const entry = statusMap[ cssClass ];
+ if ( entry.attributes ) {
+ _applyAttributes( cssClass, entry.attributes );
+ }
+ if ( entry.display_value ) {
+ _applyDisplay( cssClass, entry.display_value );
+ }
+ if ( entry.controller ) {
+ controllerSubMap[ cssClass ] = entry.controller;
+ }
+ }
+ Hi.controllers.applyValueMap( controllerSubMap );
+ };
+
+ function _applyAttributes( cssClass, attrMap ) {
+ // When a matched element does not carry the named
+ // attribute directly, the ``status`` attribute is
+ // forwarded to descendent ``div[status]`` elements so CSS
+ // selectors keyed on ``[status="..."]`` match through the
+ // wrapper. Other attribute names are silently ignored on
+ // that element.
+ const elements = $( '.' + cssClass );
+ for ( const attrName in attrMap ) {
+ const attrValue = attrMap[ attrName ];
+ elements.each( function() {
+ if ( this.hasAttribute( attrName ) ) {
+ const currentValue = $( this ).attr( attrName );
+ if ( attrValue != null && ( currentValue !== String( attrValue ) ) ) {
+ $( this ).attr( attrName, attrValue );
+ }
+ } else if ( attrName == 'status' ) {
+ $( this ).find( 'div[status]' ).attr( attrName, attrValue );
+ }
+ });
+ }
+ }
+
+ function _applyDisplay( cssClass, displayValue ) {
+ // Templates opt in to display refresh by tagging the
+ // target element with one of ``display-text``,
+ // ``display-magnitude``, ``display-unit``. The attribute
+ // is presence-only; the polled ``display_value`` field of
+ // the same name supplies the text. Fields absent on the
+ // server side (e.g., ``magnitude`` for unit-less states)
+ // leave the target element's existing text untouched.
+ const $scope = $( '.' + cssClass );
+ _setTextWhereAttr( $scope, 'display-text', displayValue.text );
+ _setTextWhereAttr( $scope, 'display-magnitude', displayValue.magnitude );
+ _setTextWhereAttr( $scope, 'display-unit', displayValue.unit_symbol );
+ }
+
+ function _setTextWhereAttr( $scope, attrName, text ) {
+ if ( text == null ) return;
+ const selector = '[' + attrName + ']';
+ $scope.find( selector ).addBack( selector ).each( function() {
+ if ( $( this ).text() !== text ) {
+ $( this ).text( text );
+ }
+ });
+ }
+
+})();
diff --git a/src/hi/static/js/status.js b/src/hi/static/js/status.js
index f4aa5087..d44aeb6a 100644
--- a/src/hi/static/js/status.js
+++ b/src/hi/static/js/status.js
@@ -30,8 +30,7 @@
const ServerStartTimestampAttr = 'startTimestamp';
const ServerTimestampAttr = 'timestamp';
const LastServerTimestampAttr = 'lastTimestamp';
- const CssClassUpdateMapAttr = 'cssClassUpdateMap';
- const CssControllerValueMapAttr = 'cssControllerValueMap';
+ const EntityStateStatusMapAttr = 'entityStateStatusMap';
const IdReplaceUpdateMapAttr = 'idReplaceUpdateMap';
const IdReplaceHashMapAttr = 'idReplaceHashMap';
const ConsoleLockedAttr = 'consoleLocked';
@@ -146,11 +145,8 @@
handleIdReplacements( respObj[IdReplaceUpdateMapAttr],
respObj[IdReplaceHashMapAttr] );
}
- if ( CssClassUpdateMapAttr in respObj ) {
- handleCssClassUpdates( respObj[CssClassUpdateMapAttr] );
- }
- if ( CssControllerValueMapAttr in respObj ) {
- Hi.controllers.applyValueMap( respObj[CssControllerValueMapAttr] );
+ if ( EntityStateStatusMapAttr in respObj ) {
+ Hi.entityStateStatus.apply( respObj[EntityStateStatusMapAttr] );
}
if ( TransientViewSuggestionAttr in respObj ) {
handleTransientViewSuggestion( respObj[TransientViewSuggestionAttr] );
@@ -241,43 +237,6 @@
}
}
- function handleCssClassUpdates( updateMap ) {
- // Apply attribute updates (the bucketed status string and
- // peers) for CSS-driven visual styling. Widget-state
- // updates (slider position, checkbox checked, select value)
- // come through the parallel controller-value path; see
- // ``Hi.controllers.applyValueMap`` in controllers.js.
- // The descendent ``div[status]`` text-update branch is
- // preserved here because its purpose is visual (showing
- // the bucketed status as text), not widget control.
- for ( let cssClass in updateMap ) {
- let elements = getElementsByCssClass( cssClass );
- let attrMap = updateMap[cssClass];
- for ( let attrName in attrMap ) {
- let attrValue = attrMap[attrName];
- elements.each( function() {
- if (this.hasAttribute(attrName)) {
- let currentValue = $(this).attr(attrName);
- if ( attrValue != null && ( currentValue !== String(attrValue) )) {
- $(this).attr( attrName, attrValue );
- }
- } else if ( attrName == 'status' ) {
- $(this).find('div[status]').each( function(index, element) {
- $(element).attr( attrName, attrValue );
- $(element).text( attrValue );
- });
- }
- });
- }
- }
- }
-
- function getElementsByCssClass( cssClass ) {
-
- let elements = $(`.${cssClass}`);
- return elements;
- }
-
function handlePollingError() {
var nowTime = (new Date()).getTime();
var elapsedMs = nowTime - gLastServerPollSuccessTime;