Skip to content

Home Information - Your home, your data, organized.

Python

Issue #297: HA cover support (garage and blinds, OPEN_CLOSE and OPEN_CLOSE_POSITION) (#305)

Tony Ca1d23b6c5951
diff --git a/src/hi/apps/control/controller_manager.py b/src/hi/apps/control/controller_manager.py
index 12e77d66..ec2b3988 100644
--- a/src/hi/apps/control/controller_manager.py
+++ b/src/hi/apps/control/controller_manager.py
@@ -1,9 +1,12 @@
from asgiref.sync import sync_to_async
import logging
+from django.conf import settings
+
from hi.apps.common.singleton import Singleton
from hi.integrations.integration_manager import IntegrationManager
+from hi.testing.dev_overrides import DevOverrideManager
from .controller_history_manager import ControllerHistoryManager
from .models import Controller
@@ -34,9 +37,18 @@ class ControllerManager( Singleton ):
integration_id = controller.integration_id,
)
integration_controller = integration_gateway.get_controller()
-
+
+ integration_details = controller.get_integration_details()
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ DevOverrideManager.trace_state(
+ 'hi.control.out',
+ ha_entity_id = integration_details.key.integration_name,
+ hi_entity_state_id = controller.entity_state.id,
+ hi_value = control_value,
+ )
+
control_result = integration_controller.do_control(
- integration_details = controller.get_integration_details(),
+ integration_details = integration_details,
hi_control_value = control_value,
)
if not control_result.has_errors:
diff --git a/src/hi/apps/control/templates/control/panes/continuous_slider.html b/src/hi/apps/control/templates/control/panes/continuous_slider.html
index e85c18db..ee977749 100644
--- a/src/hi/apps/control/templates/control/panes/continuous_slider.html
+++ b/src/hi/apps/control/templates/control/panes/continuous_slider.html
@@ -12,6 +12,10 @@ Parameters:
('%', '°', 'K', or '').
- slider_class : per-slider CSS class for gradient
track styling (e.g., 'hue-slider').
+- min_label, max_label : optional static text flanking the
+ slider (e.g., 'Closed' / 'Open' for
+ a position slider). Omitted when
+ blank.
- show_presets : True to render two preset buttons
that snap the slider to its min and
max values (default: False).
@@ -21,17 +25,21 @@ Parameters:
(default: 'Max').
{% endcomment %}
<div class="{{ DIVID.CONTROLLER_SLIDER_CONTROL_CLASS }}">
- <input type="range"
- name="value"
- min="{{ slider_min }}"
- max="{{ slider_max }}"
- {% if slider_step %}step="{{ slider_step }}"{% endif %}
- value="{{ controller_data.latest_sensor_response.value|default_if_none:slider_default }}"
- class="{{ controller_data.css_class }} {{ DIVID.CONTROLLER_SLIDER_CLASS }} {{ slider_class }}"
- {{ DIVID.CONTROLLER_DISPLAY_TARGET_ATTR }}=".hi-continuous-slider-value"
- {{ DIVID.CONTROLLER_DISPLAY_FORMAT_ATTR }}="{n}{{ display_unit }}"
- onchange-async="true"
- data-controller-id="{{ controller_data.controller.id }}">
+ <div class="hi-continuous-slider-row">
+ {% if min_label %}<span class="hi-continuous-slider-extreme">{{ min_label }}</span>{% endif %}
+ <input type="range"
+ name="value"
+ min="{{ slider_min }}"
+ max="{{ slider_max }}"
+ {% if slider_step %}step="{{ slider_step }}"{% endif %}
+ value="{{ controller_data.latest_sensor_response.value|default_if_none:slider_default }}"
+ class="{{ controller_data.css_class }} {{ DIVID.CONTROLLER_SLIDER_CLASS }} {{ slider_class }}"
+ {{ DIVID.CONTROLLER_DISPLAY_TARGET_ATTR }}=".hi-continuous-slider-value"
+ {{ DIVID.CONTROLLER_DISPLAY_FORMAT_ATTR }}="{n}{{ display_unit }}"
+ onchange-async="true"
+ data-controller-id="{{ controller_data.controller.id }}">
+ {% if max_label %}<span class="hi-continuous-slider-extreme">{{ max_label }}</span>{% endif %}
+ </div>
<div class="hi-continuous-slider-display">
<span class="hi-continuous-slider-value">{{ controller_data.latest_sensor_response.value|default_if_none:slider_default }}{{ display_unit }}</span>
{% if show_presets %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_on_off.html b/src/hi/apps/control/templates/control/panes/controller_on_off.html
index b06d7c97..4a06600a 100644
--- a/src/hi/apps/control/templates/control/panes/controller_on_off.html
+++ b/src/hi/apps/control/templates/control/panes/controller_on_off.html
@@ -1,17 +1,21 @@
+{% with on_text="On" off_text="Off" %}
<div class="on-off-control">
<label class="switch-modern">
- <input type="checkbox"
- name="value"
+ <input type="checkbox"
+ name="value"
class="{{ controller_data.css_class }} switch-input"
{% if controller_data.latest_sensor_response.is_on %}checked="true"{% endif %}
status="{{ controller_data.latest_sensor_response.value }}"
+ data-on-text="{{ on_text }}"
+ data-off-text="{{ off_text }}"
onchange-async="true"
data-controller-id="{{ controller_data.controller.id }}">
<span class="switch-slider"></span>
</label>
<div class="switch-status">
<span class="status-text">
- {% if controller_data.latest_sensor_response.is_on %}On{% else %}Off{% endif %}
+ {% if controller_data.latest_sensor_response.is_on %}{{ on_text }}{% else %}{{ off_text }}{% endif %}
</span>
</div>
</div>
+{% endwith %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_open_close.html b/src/hi/apps/control/templates/control/panes/controller_open_close.html
new file mode 100644
index 00000000..46f0c982
--- /dev/null
+++ b/src/hi/apps/control/templates/control/panes/controller_open_close.html
@@ -0,0 +1,22 @@
+{% with on_text="Open" off_text="Closed" %}
+<div class="on-off-control">
+ <label class="switch-modern">
+ <input type="checkbox"
+ name="value"
+ value="open"
+ class="{{ controller_data.css_class }} switch-input"
+ {% if controller_data.latest_sensor_response.is_open %}checked="true"{% endif %}
+ status="{{ controller_data.latest_sensor_response.value }}"
+ data-on-text="{{ on_text }}"
+ data-off-text="{{ off_text }}"
+ onchange-async="true"
+ data-controller-id="{{ controller_data.controller.id }}">
+ <span class="switch-slider"></span>
+ </label>
+ <div class="switch-status">
+ <span class="status-text">
+ {% if controller_data.latest_sensor_response.is_open %}{{ on_text }}{% else %}{{ off_text }}{% endif %}
+ </span>
+ </div>
+</div>
+{% endwith %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_open_close_position.html b/src/hi/apps/control/templates/control/panes/controller_open_close_position.html
new file mode 100644
index 00000000..4d66262f
--- /dev/null
+++ b/src/hi/apps/control/templates/control/panes/controller_open_close_position.html
@@ -0,0 +1 @@
+{% include "control/panes/continuous_slider.html" with slider_min=0 slider_max=100 slider_default=0 display_unit="% open" slider_class="open-close-position-slider" min_label="Closed" max_label="Open" %}
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 4bf9cab5..975b5ffa 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -78,6 +78,7 @@ class EntityType(LabeledEnum):
MOTOR = ( 'Motor', '' )
NETWORK_SWITCH = ( 'Network Switch', '' )
ON_OFF_SWITCH = ( 'On/Off Switch', '' )
+ OPEN_CLOSE_ACTUATOR = ( 'Open/Close Actuator', '' ) # Controls things that open/close
OPEN_CLOSE_SENSOR = ( 'Open/Close Sensor', '' )
OTHER = ( 'Other', '' ) # Will use generic visual element
OVEN = ( 'Oven', '' )
@@ -299,7 +300,10 @@ class EntityStateType(LabeledEnum):
EntityStateValue.OFF ] )
OPEN_CLOSE = ( 'Open/Close' , '',
[ EntityStateValue.OPEN,
- EntityStateValue.CLOSED ] )
+ EntityStateValue.CLOSED ] )
+ OPEN_CLOSE_POSITION = ( 'Open/Close Position',
+ 'Continuous open/close position as a percentage (0=closed, 100=open)',
+ [] )
PRESENCE = ( 'Presence' , '',
[ EntityStateValue.ACTIVE,
EntityStateValue.IDLE ] )
@@ -462,6 +466,7 @@ class EntityGroupType(LabeledEnum):
EntityType.WALL_SWITCH,
})
OTHER = ( 'Other', '', {
+ EntityType.OPEN_CLOSE_ACTUATOR,
EntityType.OTHER,
})
OUTDOORS = ( 'Outdoors', '', {
diff --git a/src/hi/apps/entity/templates/entity/svg/type.open_close_actuator.svg b/src/hi/apps/entity/templates/entity/svg/type.open_close_actuator.svg
new file mode 100644
index 00000000..2b5eaf53
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/svg/type.open_close_actuator.svg
@@ -0,0 +1,25 @@
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+
+<!-- Motor housing -->
+<rect x="6" y="22" width="26" height="20" rx="3" fill="#d8d8d8" stroke="#555" stroke-width="2"/>
+
+<!-- Cooling fins -->
+<line x1="14" y1="24" x2="14" y2="40" stroke="#888" stroke-width="1"/>
+<line x1="20" y1="24" x2="20" y2="40" stroke="#888" stroke-width="1"/>
+<line x1="26" y1="24" x2="26" y2="40" stroke="#888" stroke-width="1"/>
+
+<!-- Push rod -->
+<rect x="32" y="29" width="18" height="6" rx="1" fill="#bbb" stroke="#555" stroke-width="1.5"/>
+
+<!-- Rod end clevis -->
+<rect x="50" y="26" width="6" height="12" rx="1" fill="#888" stroke="#555" stroke-width="1.5"/>
+
+<!-- Bidirectional motion arrows above the rod -->
+<line x1="36" y1="16" x2="56" y2="16" stroke="#1976d2" stroke-width="2.5" stroke-linecap="round"/>
+<line x1="36" y1="16" x2="40" y2="12" stroke="#1976d2" stroke-width="2.5" stroke-linecap="round"/>
+<line x1="36" y1="16" x2="40" y2="20" stroke="#1976d2" stroke-width="2.5" stroke-linecap="round"/>
+<line x1="56" y1="16" x2="52" y2="12" stroke="#1976d2" stroke-width="2.5" stroke-linecap="round"/>
+<line x1="56" y1="16" x2="52" y2="20" stroke="#1976d2" stroke-width="2.5" stroke-linecap="round"/>
+
+<!-- Status LED on motor -->
+<circle cx="11" cy="32" r="2" fill="#4caf50"/>
diff --git a/src/hi/apps/location/enums.py b/src/hi/apps/location/enums.py
index 4ac36147..c237d01c 100644
--- a/src/hi/apps/location/enums.py
+++ b/src/hi/apps/location/enums.py
@@ -42,6 +42,7 @@ class LocationViewType(LabeledEnum):
[ EntityStateType.MOVEMENT,
EntityStateType.PRESENCE,
EntityStateType.OPEN_CLOSE,
+ EntityStateType.OPEN_CLOSE_POSITION,
EntityStateType.ON_OFF,
EntityStateType.LIGHT_DIMMER,
],
@@ -52,6 +53,7 @@ class LocationViewType(LabeledEnum):
[ EntityStateType.MOVEMENT,
EntityStateType.PRESENCE,
EntityStateType.OPEN_CLOSE,
+ EntityStateType.OPEN_CLOSE_POSITION,
EntityStateType.ON_OFF,
EntityStateType.LIGHT_DIMMER,
EntityStateType.LIGHT_LEVEL,
diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.py
index c1068ed7..f5a77c41 100644
--- a/src/hi/apps/model_helper.py
+++ b/src/hi/apps/model_helper.py
@@ -242,6 +242,42 @@ class HiModelHelper:
integration_key = integration_key,
)
+ @classmethod
+ def create_open_close_controller( cls,
+ entity : Entity,
+ integration_key : IntegrationKey = None,
+ name : str = None,
+ is_sensed : bool = True ) -> Controller:
+ if not name:
+ name = f'{entity.name} Controller'
+ return cls.create_controller(
+ entity = entity,
+ entity_state_type = EntityStateType.OPEN_CLOSE,
+ name = name,
+ is_sensed = is_sensed,
+ integration_key = integration_key,
+ )
+
+ @classmethod
+ def create_open_close_position_controller(
+ cls,
+ entity : Entity,
+ integration_key : IntegrationKey = None,
+ name : str = None,
+ is_sensed : bool = True ) -> Controller:
+ if not name:
+ name = f'{entity.name} Position'
+ # Continuous position 0-100 (closed at 0, open above).
+ value_range = { 'min': 0, 'max': 100 }
+ return cls.create_controller(
+ entity = entity,
+ entity_state_type = EntityStateType.OPEN_CLOSE_POSITION,
+ name = name,
+ is_sensed = is_sensed,
+ integration_key = integration_key,
+ value_range_str = json.dumps( value_range ),
+ )
+
@classmethod
def create_discrete_controller( cls,
entity : Entity,
diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.py
index 4487ab57..78700b34 100644
--- a/src/hi/apps/monitor/status_display_data.py
+++ b/src/hi/apps/monitor/status_display_data.py
@@ -124,6 +124,9 @@ class StatusDisplayData:
if self.entity_state.entity_state_type == EntityStateType.OPEN_CLOSE:
return self._get_open_close_status_style()
+
+ if self.entity_state.entity_state_type == EntityStateType.OPEN_CLOSE_POSITION:
+ return self._get_open_close_position_status_style()
if self.entity_state.entity_state_type == EntityStateType.CONNECTIVITY:
return self._get_connectivity_status_style()
@@ -191,6 +194,23 @@ class StatusDisplayData:
def _get_light_dimmer_status_style( self ):
return StatusStyle.light_dimmer( self.latest_sensor_value )
+ def _get_open_close_position_status_style( self ):
+ # Discretize the continuous position into three visual
+ # buckets, mirroring the dimmer pattern (off / dim / on).
+ # A continuous color gradient would require per-value CSS
+ # rules; three buckets keep the SVG palette finite while
+ # still distinguishing closed, partially-open, and
+ # fully-open states.
+ try:
+ position = int( float( self.latest_sensor_value ) )
+ except ( TypeError, ValueError ):
+ position = 0
+ if position <= 0:
+ return StatusStyle.Closed
+ if position < 75:
+ return StatusStyle.OpenPartial
+ return StatusStyle.Open
+
def _get_open_close_status_style( self ):
if self.latest_sensor_value == str(EntityStateValue.OPEN):
diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.py
index 8289f924..443c6689 100644
--- a/src/hi/apps/monitor/status_display_manager.py
+++ b/src/hi/apps/monitor/status_display_manager.py
@@ -1,6 +1,9 @@
+import dataclasses
from cachetools import TTLCache
from typing import Dict, List, Set, Sequence
+from django.conf import settings
+
from hi.apps.control.transient_models import ControllerData
from hi.apps.common.singleton import Singleton
from hi.apps.entity.enums import EntityStateType
@@ -10,6 +13,7 @@ from hi.apps.location.svg_item_factory import SvgItemFactory
from hi.apps.sense.models import Sensor
from hi.apps.sense.sensor_response_manager import SensorResponseMixin
from hi.apps.sense.transient_models import SensorResponse
+from hi.testing.dev_overrides import DevOverrideManager
from .status_display_data import StatusDisplayData
from .transient_models import EntityStatusData, EntityStateStatusData
@@ -36,6 +40,15 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
if status_display_data.should_skip:
continue
css_class_update_map[status_display_data.css_class] = status_display_data.attribute_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',
+ 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,
+ )
continue
return css_class_update_map
@@ -58,6 +71,15 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
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
@@ -447,14 +469,24 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
sensor_list = sensor_list,
)
+ # Apply overrides into a fresh dict so neither the
+ # SensorResponse objects nor the response lists owned by
+ # SensorResponseManager's cache are touched. Mutating
+ # them would persist the override past its TTL.
+ result = dict()
for sensor, sensor_response_list in sensor_to_sensor_response_list.items():
if ( not sensor_response_list
or ( sensor.entity_state.id not in self._status_value_overrides )):
+ result[ sensor ] = sensor_response_list
continue
- sensor_response_list[0].value = self._status_value_overrides[sensor.entity_state.id]
+ overridden = dataclasses.replace(
+ sensor_response_list[ 0 ],
+ value = self._status_value_overrides[ sensor.entity_state.id ],
+ )
+ result[ sensor ] = [ overridden, *sensor_response_list[ 1: ] ]
continue
- return sensor_to_sensor_response_list
+ return result
def add_entity_state_value_override( self,
entity_state : EntityState,
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 2fdd778f..28e3652b 100644
--- a/src/hi/apps/monitor/tests/test_status_display_data.py
+++ b/src/hi/apps/monitor/tests/test_status_display_data.py
@@ -306,6 +306,56 @@ class TestStatusDisplayData(BaseTestCase):
self.assertEqual(display_data.svg_status_style, StatusStyle.Closed)
+ # OPEN_CLOSE_POSITION State Type Tests (continuous-position cover)
+
+ def test_open_close_position_zero_returns_closed_style(self):
+ sensor_response = self._create_mock_sensor_response('0')
+ status_data = self._create_entity_state_status_data(
+ 'OPEN_CLOSE_POSITION', [ sensor_response ],
+ )
+
+ display_data = StatusDisplayData( status_data )
+
+ self.assertEqual( display_data.svg_status_style, StatusStyle.Closed )
+
+ def test_open_close_position_partial_returns_open_partial_style(self):
+ # Mid-range positions land in the partial bucket, mirroring
+ # the dimmer's three-bucket discretization.
+ for position in ( '1', '50', '74' ):
+ with self.subTest( position=position ):
+ sensor_response = self._create_mock_sensor_response( position )
+ status_data = self._create_entity_state_status_data(
+ 'OPEN_CLOSE_POSITION', [ sensor_response ],
+ )
+
+ display_data = StatusDisplayData( status_data )
+
+ self.assertEqual( display_data.svg_status_style, StatusStyle.OpenPartial )
+
+ def test_open_close_position_high_returns_open_style(self):
+ for position in ( '75', '90', '100' ):
+ with self.subTest( position=position ):
+ sensor_response = self._create_mock_sensor_response( position )
+ status_data = self._create_entity_state_status_data(
+ 'OPEN_CLOSE_POSITION', [ sensor_response ],
+ )
+
+ display_data = StatusDisplayData( status_data )
+
+ self.assertEqual( display_data.svg_status_style, StatusStyle.Open )
+
+ def test_open_close_position_non_numeric_returns_closed_style(self):
+ # Defensive: a malformed value shouldn't crash the
+ # display path; treat as closed.
+ sensor_response = self._create_mock_sensor_response( 'garbage' )
+ status_data = self._create_entity_state_status_data(
+ 'OPEN_CLOSE_POSITION', [ sensor_response ],
+ )
+
+ display_data = StatusDisplayData( status_data )
+
+ self.assertEqual( display_data.svg_status_style, StatusStyle.Closed )
+
# Edge Cases and Default Behavior Tests
def test_no_sensor_data_returns_default_style(self):
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 78a2c03a..ba3b59fd 100644
--- a/src/hi/apps/monitor/tests/test_status_display_manager.py
+++ b/src/hi/apps/monitor/tests/test_status_display_manager.py
@@ -139,6 +139,81 @@ class TestStatusDisplayManager(BaseTestCase):
self.assertIsNone(latest_response)
+ def test_override_does_not_mutate_cached_sensor_response(self):
+ """Regression for the cache-poisoning bug: applying a value
+ override must not modify the SensorResponse owned by
+ SensorResponseManager's cache, otherwise the override
+ persists past its TTL."""
+ from hi.integrations.transient_models import IntegrationKey
+ from datetime import datetime
+
+ entity = Entity.objects.create( name='Test Entity', entity_type_str='CAMERA' )
+ entity_state = EntityState.objects.create(
+ entity=entity, entity_state_type_str='OPEN_CLOSE_POSITION',
+ )
+ sensor = Sensor.objects.create(
+ name='Test Sensor', entity_state=entity_state, sensor_type_str='DEFAULT',
+ )
+ cached_response = SensorResponse(
+ integration_key=IntegrationKey(
+ integration_id='hass', integration_name='cover.test',
+ ),
+ value='30',
+ timestamp=datetime( 2026, 1, 1 ),
+ sensor=sensor,
+ )
+
+ manager = StatusDisplayManager()
+ manager._status_value_overrides.clear()
+ manager.add_entity_state_value_override( entity_state, '99' )
+
+ with patch.object(
+ manager.sensor_response_manager(),
+ 'get_all_latest_sensor_responses',
+ ) as mock_helper:
+ mock_helper.return_value = { sensor: [ cached_response ] }
+ manager._get_latest_sensor_responses_helper()
+
+ self.assertEqual(
+ cached_response.value, '30',
+ 'Override application must not mutate the cached SensorResponse',
+ )
+
+ def test_override_returns_overridden_value_via_copy(self):
+ """The override must surface in the returned response list
+ even though the cached object is left intact."""
+ from hi.integrations.transient_models import IntegrationKey
+ from datetime import datetime
+
+ entity = Entity.objects.create( name='Test Entity', entity_type_str='CAMERA' )
+ entity_state = EntityState.objects.create(
+ entity=entity, entity_state_type_str='OPEN_CLOSE_POSITION',
+ )
+ sensor = Sensor.objects.create(
+ name='Test Sensor', entity_state=entity_state, sensor_type_str='DEFAULT',
+ )
+ cached_response = SensorResponse(
+ integration_key=IntegrationKey(
+ integration_id='hass', integration_name='cover.test',
+ ),
+ value='30',
+ timestamp=datetime( 2026, 1, 1 ),
+ sensor=sensor,
+ )
+
+ manager = StatusDisplayManager()
+ manager._status_value_overrides.clear()
+ manager.add_entity_state_value_override( entity_state, '99' )
+
+ with patch.object(
+ manager.sensor_response_manager(),
+ 'get_all_latest_sensor_responses',
+ ) as mock_helper:
+ mock_helper.return_value = { sensor: [ cached_response ] }
+ result = manager._get_latest_sensor_responses_helper()
+
+ self.assertEqual( result[ sensor ][ 0 ].value, '99' )
+
def test_get_entity_status_data_list_preserves_order(self):
"""Test entity status data list maintains input entity order."""
entity1 = Entity.objects.create(name='Entity 1', entity_type_str='CAMERA')
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index e280a5a1..0bc80822 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -4,12 +4,15 @@ from cachetools import TTLCache
import logging
from typing import Dict, List, Optional
+from django.conf import settings
+
from hi.apps.common.redis_client import get_redis_client
from hi.apps.common.singleton import Singleton
from hi.apps.event.event_mixins import EventMixin
from hi.apps.event.transient_models import EntityStateTransition
from hi.integrations.transient_models import IntegrationKey
+from hi.testing.dev_overrides import DevOverrideManager
from .models import Sensor
from .sensor_history_manager import SensorHistoryMixin
@@ -112,6 +115,14 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
if cached_value:
previous_sensor_response = SensorResponse.from_string( cached_value )
if latest_sensor_response.value == previous_sensor_response.value:
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ sensor = latest_sensor_response.sensor
+ DevOverrideManager.trace_state(
+ 'hi.sensor.skip',
+ ha_entity_id = integration_key.integration_name,
+ hi_entity_state_id = sensor.entity_state.id if sensor else None,
+ hi_value = latest_sensor_response.value,
+ )
continue
entity_state_transition = await self._create_entity_state_transition(
@@ -120,7 +131,25 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
)
if entity_state_transition:
entity_state_transition_list.append( entity_state_transition )
-
+
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ sensor = latest_sensor_response.sensor
+ DevOverrideManager.trace_state(
+ 'hi.sensor.commit',
+ ha_entity_id = integration_key.integration_name,
+ hi_entity_state_id = sensor.entity_state.id if sensor else None,
+ hi_value = f'{previous_sensor_response.value} -> {latest_sensor_response.value}',
+ )
+ else:
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ sensor = latest_sensor_response.sensor
+ DevOverrideManager.trace_state(
+ 'hi.sensor.first',
+ ha_entity_id = integration_key.integration_name,
+ hi_entity_state_id = sensor.entity_state.id if sensor else None,
+ hi_value = latest_sensor_response.value,
+ )
+
changed_sensor_response_list.append( latest_sensor_response )
continue
@@ -215,8 +244,6 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
if not sensor_response_list:
return
- self._latest_sensor_data_dirty = True
-
await self._add_sensors( sensor_response_list = sensor_response_list )
sensor_history_manager = await self.sensor_history_manager_async()
@@ -224,8 +251,8 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
# This also has side effect of populating sensor_history_id
await sensor_history_manager.add_to_sensor_history(
sensor_response_list = sensor_response_list,
- )
-
+ )
+
pipeline = self._redis_client.pipeline()
for sensor_response in sensor_response_list:
list_cache_key = self.to_sensor_response_list_cache_key( sensor_response.integration_key )
@@ -236,6 +263,15 @@ class SensorResponseManager( Singleton, SensorHistoryMixin, EventMixin ):
continue
pipeline.execute()
+ # Flag the in-memory map stale only after Redis is
+ # updated. Setting it earlier opens a window where a
+ # concurrent reader rebuilds the map from pre-update
+ # Redis and clears the flag, leaving the in-memory map
+ # stuck on the stale value until the next commit. A
+ # reader that runs between ``pipeline.execute()`` and
+ # this assignment can still see one stale poll, but
+ # next-call recovery is automatic.
+ self._latest_sensor_data_dirty = True
return
def to_sensor_response_list_cache_key( self, integration_key : IntegrationKey ) -> str:
diff --git a/src/hi/apps/sense/tests/test_sensor_response_manager.py b/src/hi/apps/sense/tests/test_sensor_response_manager.py
index b581d9f9..44aa17b1 100644
--- a/src/hi/apps/sense/tests/test_sensor_response_manager.py
+++ b/src/hi/apps/sense/tests/test_sensor_response_manager.py
@@ -140,6 +140,49 @@ class AsyncSensorResponseManagerTestCase(AsyncTaskTestCase):
deserialized = SensorResponse.from_string(serialized)
self.assertEqual(new_response.value, deserialized.value)
+ def test_dirty_flag_set_only_after_redis_pipeline_executes(self):
+ """Regression for the cache-poisoning race: setting the
+ dirty flag before the Redis write let a concurrent reader
+ rebuild the in-memory map from pre-update Redis state and
+ clear the flag, leaving the map permanently stuck on the
+ stale value. Assert the flag is still False at the moment
+ ``pipeline.execute()`` runs and True after."""
+ observed_dirty_at_execute = []
+
+ async def run():
+ sensor_response = SensorResponse(
+ integration_key=self.integration_key,
+ value='on',
+ timestamp=timezone.now(),
+ )
+
+ mock_pipeline = Mock()
+
+ def capture_dirty_state():
+ observed_dirty_at_execute.append(
+ self.manager._latest_sensor_data_dirty,
+ )
+ return []
+
+ mock_pipeline.execute.side_effect = capture_dirty_state
+
+ with patch.object( self.manager, '_redis_client' ) as mock_redis:
+ mock_redis.pipeline.return_value = mock_pipeline
+ self.manager._latest_sensor_data_dirty = False
+ await self.manager._add_latest_sensor_responses( [ sensor_response ] )
+
+ import asyncio
+ asyncio.get_event_loop().run_until_complete( run() )
+
+ self.assertEqual(
+ observed_dirty_at_execute, [ False ],
+ 'Dirty flag was set before the Redis pipeline executed',
+ )
+ self.assertTrue(
+ self.manager._latest_sensor_data_dirty,
+ 'Dirty flag must be True after the Redis pipeline executes',
+ )
+
def test_redis_caching_operations_use_correct_commands(self):
"""Test Redis cache key generation follows expected pattern."""
diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.py
index 7c9760c3..17387a5a 100644
--- a/src/hi/apps/sense/transient_models.py
+++ b/src/hi/apps/sense/transient_models.py
@@ -50,6 +50,9 @@ class SensorResponse:
def is_on(self):
return bool( self.value == str(EntityStateValue.ON) )
+ def is_open(self):
+ return bool( self.value == str(EntityStateValue.OPEN) )
+
@property
def video_browse_url(self) -> str:
if self.has_video_stream and self.sensor_history_id:
diff --git a/src/hi/hi_styles.py b/src/hi/hi_styles.py
index d31eb4d0..03b24b3c 100644
--- a/src/hi/hi_styles.py
+++ b/src/hi/hi_styles.py
@@ -316,6 +316,7 @@ class EntityStyle:
EntityType.MOTOR,
EntityType.NETWORK_SWITCH,
EntityType.ON_OFF_SWITCH,
+ EntityType.OPEN_CLOSE_ACTUATOR,
EntityType.OPEN_CLOSE_SENSOR,
EntityType.OVEN,
EntityType.PLANT,
@@ -526,6 +527,18 @@ class StatusStyle:
fill_color = STATUS_PAST_COLOR,
fill_opacity = 0.5,
)
+ # Partially-open spatial state for continuous-position covers.
+ # Distinct from ``OpenRecent`` (temporal decay after a recent
+ # open) so spatial and temporal semantics don't share a name,
+ # even though the visual palette is intentionally aligned.
+ OpenPartial = SvgStatusStyle(
+ status_value = 'partial',
+ stroke_color = STATUS_RECENT_COLOR,
+ stroke_width = DEFAULT_STROKE_WIDTH,
+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,
+ fill_color = STATUS_RECENT_COLOR,
+ fill_opacity = 0.5,
+ )
Closed = SvgStatusStyle(
status_value = 'closed',
stroke_color = STATUS_IDLE_COLOR,
diff --git a/src/hi/services/hass/enums.py b/src/hi/services/hass/enums.py
index b66a5387..3ead03c7 100644
--- a/src/hi/services/hass/enums.py
+++ b/src/hi/services/hass/enums.py
@@ -56,3 +56,7 @@ class HassStateValue:
OFF = 'off'
LOCKED = 'locked'
UNLOCKED = 'unlocked'
+ OPEN = 'open'
+ CLOSED = 'closed'
+ OPENING = 'opening'
+ CLOSING = 'closing'
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index c4514121..fb39eed0 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -210,9 +210,13 @@ class HassConverter:
# Switch Domain
(HassApi.SWITCH_DOMAIN, None, None): EntityStateType.ON_OFF,
- # Cover Domain (blinds, curtains, garage doors)
+ # Cover Domain (blinds, curtains, garage doors). Covers
+ # that report ``current_position`` are routed to
+ # OPEN_CLOSE_POSITION (continuous slider) by the lookup
+ # logic, not via this table — these entries cover only
+ # the discrete open/close case.
(HassApi.COVER_DOMAIN, HassApi.DOOR_DEVICE_CLASS, None): EntityStateType.OPEN_CLOSE,
- (HassApi.COVER_DOMAIN, HassApi.GARAGE_DOOR_DEVICE_CLASS, None): EntityStateType.OPEN_CLOSE,
+ (HassApi.COVER_DOMAIN, HassApi.GARAGE_DEVICE_CLASS, None): EntityStateType.OPEN_CLOSE,
(HassApi.COVER_DOMAIN, HassApi.WINDOW_DEVICE_CLASS, None): EntityStateType.OPEN_CLOSE,
(HassApi.COVER_DOMAIN, None, None): EntityStateType.OPEN_CLOSE, # Default for covers
@@ -287,6 +291,14 @@ class HassConverter:
'position': 'percentage', # 0-100
},
},
+ (HassApi.COVER_DOMAIN, EntityStateType.OPEN_CLOSE_POSITION): {
+ 'on_service': HassApi.OPEN_COVER_SERVICE,
+ 'off_service': HassApi.CLOSE_COVER_SERVICE,
+ 'set_service': HassApi.SET_COVER_POSITION_SERVICE,
+ 'parameters': {
+ 'position': 'percentage', # 0-100
+ },
+ },
# Fan Domain Services
(HassApi.FAN_DOMAIN, EntityStateType.ON_OFF): {
@@ -931,11 +943,19 @@ class HassConverter:
@classmethod
def _determine_entity_state_type_from_mapping( cls, hass_state: HassState ) -> EntityStateType:
"""Use mapping table to determine EntityStateType from HassState"""
-
+
domain = hass_state.domain
device_class = hass_state.device_class
has_brightness = cls._has_brightness_capability( hass_state )
-
+
+ # Position-aware override for covers: a cover that
+ # reports ``current_position`` is structurally a
+ # continuous slider (closed at 0, open above) — like a
+ # dimmer, not a binary toggle. Skip the discrete
+ # open/close mapping and use the continuous type.
+ if domain == HassApi.COVER_DOMAIN and cls._has_position_capability( hass_state ):
+ return EntityStateType.OPEN_CLOSE_POSITION
+
# Try exact match first
mapping_key = (domain, device_class, has_brightness)
if mapping_key in cls.HASS_STATE_TO_ENTITY_STATE_TYPE_MAPPING:
@@ -1201,6 +1221,14 @@ class HassConverter:
return True
return False
+ @classmethod
+ def _has_position_capability( cls, hass_state: HassState ) -> bool:
+ """True when an HA cover state reports ``current_position``,
+ meaning the cover is a continuous-position device (blind,
+ slider shade) rather than a binary open/close (garage,
+ door)."""
+ return hass_state.attributes.get( 'current_position' ) is not None
+
@classmethod
def _is_controllable_domain_and_type( cls, domain: str, entity_state_type: EntityStateType ) -> bool:
"""Check if this domain+type combination is controllable"""
@@ -1222,6 +1250,18 @@ class HassConverter:
integration_key = integration_key,
name = name,
)
+ elif entity_state_type == EntityStateType.OPEN_CLOSE:
+ controller = HiModelHelper.create_open_close_controller(
+ entity = entity,
+ integration_key = integration_key,
+ name = name,
+ )
+ elif entity_state_type == EntityStateType.OPEN_CLOSE_POSITION:
+ controller = HiModelHelper.create_open_close_position_controller(
+ entity = entity,
+ integration_key = integration_key,
+ name = name,
+ )
elif entity_state_type == EntityStateType.LIGHT_DIMMER:
controller = HiModelHelper.create_light_dimmer_controller(
entity = entity,
@@ -1568,13 +1608,18 @@ class HassConverter:
return EntityType.ON_OFF_SWITCH
if HassApi.LOCK_DOMAIN in domain_set:
return EntityType.DOOR_LOCK
- # HA covers are doors / windows / garage doors / blinds /
- # awnings / etc. Without a device-class refinement that maps
- # cleanly to HI's specific types, OPEN_CLOSE_SENSOR is the
- # least-wrong default; the operator can change it post-import
- # to DOOR / WINDOW / GARAGE_DOOR if appropriate.
+ # HA covers are the *control mechanism* (motor / opener)
+ # for doors / windows / garage doors / blinds / awnings /
+ # gates / etc. The thing being controlled (the door, the
+ # window) is a separate floor-plan element; what HA
+ # exposes here is the actuator. ``GARAGE_DOOR_OPENER``
+ # already specializes the most common case;
+ # ``OPEN_CLOSE_ACTUATOR`` is the generic fall-through for
+ # every other cover device class.
if HassApi.COVER_DOMAIN in domain_set:
- return EntityType.OPEN_CLOSE_SENSOR
+ if HassApi.GARAGE_DEVICE_CLASS in device_class_set:
+ return EntityType.GARAGE_DOOR_OPENER
+ return EntityType.OPEN_CLOSE_ACTUATOR
# Fan domain has no HA-side device class to distinguish
# ceiling vs exhaust; CEILING_FAN is the more common case.
if HassApi.FAN_DOMAIN in domain_set:
@@ -1630,6 +1675,8 @@ class HassConverter:
return cls._binary_sensor_to_sensor_value_map( hass_state )
if domain == HassApi.LOCK_DOMAIN:
return cls._lock_to_sensor_value_map( hass_state )
+ if domain == HassApi.COVER_DOMAIN:
+ return cls._cover_to_sensor_value_map( hass_state )
return cls._passthrough_to_sensor_value_map( hass_state )
@classmethod
@@ -1757,6 +1804,25 @@ class HassConverter:
return {}
return { cls.hass_state_to_integration_key( hass_state ) : value }
+ @classmethod
+ def _cover_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ """Cover domain: when ``current_position`` is reported,
+ the EntityState is OPEN_CLOSE_POSITION (continuous slider)
+ and the numeric position is the canonical value. Without
+ position, the EntityState is OPEN_CLOSE (binary toggle)
+ and HA's discrete state string passes through unchanged.
+ Transitional ``'opening'`` / ``'closing'`` states pass
+ through as well; downstream display logic falls back to
+ the closed style for unrecognized values."""
+ if cls._has_position_capability( hass_state ):
+ try:
+ position = int( float( hass_state.attributes[ 'current_position' ] ) )
+ except ( TypeError, ValueError ):
+ return {}
+ return { cls.hass_state_to_integration_key( hass_state ) : str( position ) }
+ return cls._passthrough_to_sensor_value_map( hass_state )
+
@classmethod
def _passthrough_to_sensor_value_map(
cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
diff --git a/src/hi/services/hass/hass_models.py b/src/hi/services/hass/hass_models.py
index 419ab01a..210e64cb 100644
--- a/src/hi/services/hass/hass_models.py
+++ b/src/hi/services/hass/hass_models.py
@@ -90,10 +90,12 @@ class HassApi:
UNIT_OF_MEASUREMENT_ATTR = 'unit_of_measurement'
BATTERY_DEVICE_CLASS = 'battery'
+ BLIND_DEVICE_CLASS = 'blind' # cover domain
CONNECTIVITY_DEVICE_CLASS = 'connectivity'
DOOR_DEVICE_CLASS = 'door'
ENUM_DEVICE_CLASS = 'enum'
- GARAGE_DOOR_DEVICE_CLASS = 'garage_door'
+ GARAGE_DEVICE_CLASS = 'garage' # cover domain
+ GARAGE_DOOR_DEVICE_CLASS = 'garage_door' # binary_sensor domain
HUMIDITY_DEVICE_CLASS = 'humidity'
LIGHT_DEVICE_CLASS = 'light'
MOTION_DEVICE_CLASS = 'motion'
diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.py
index 8259bf23..90abb850 100644
--- a/src/hi/services/hass/monitors.py
+++ b/src/hi/services/hass/monitors.py
@@ -1,11 +1,14 @@
import logging
+from django.conf import settings
+
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.alert.enums import AlarmLevel
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
from hi.apps.sense.sensor_response_manager import SensorResponseMixin
from hi.apps.sense.transient_models import SensorResponse
from hi.apps.system.provider_info import ProviderInfo
+from hi.testing.dev_overrides import DevOverrideManager
from .hass_converter import HassConverter
from .hass_mixins import HassMixin
@@ -94,6 +97,14 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):
for hass_state in id_to_hass_state_map.values():
value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ if settings.DEBUG and settings.DEBUG_TRACE_STATE:
+ DevOverrideManager.trace_state(
+ 'hi.ha_poll.in',
+ ha_entity_id = hass_state.entity_id,
+ ha_value = hass_state.state_value,
+ device_class = hass_state.device_class,
+ value_map = { str(k): v for k, v in value_map.items() },
+ )
for integration_key, sensor_value_str in value_map.items():
if not sensor_value_str:
continue
diff --git a/src/hi/services/hass/tests/test_hass_converter_cover.py b/src/hi/services/hass/tests/test_hass_converter_cover.py
new file mode 100644
index 00000000..d5cc1f74
--- /dev/null
+++ b/src/hi/services/hass/tests/test_hass_converter_cover.py
@@ -0,0 +1,248 @@
+import logging
+
+from django.test import TestCase
+
+from hi.apps.control.models import Controller
+from hi.apps.entity.enums import EntityStateType, EntityType
+from hi.apps.entity.models import EntityState
+from hi.services.hass.hass_converter import HassConverter
+from hi.services.hass.hass_models import HassApi, HassDevice, HassServiceCall
+
+logging.disable(logging.CRITICAL)
+
+
+def _make_cover_api_dict(
+ entity_id='cover.example',
+ state='closed',
+ device_class=None,
+ current_position=None,
+ friendly_name=None ):
+ attributes = {}
+ if friendly_name:
+ attributes[ 'friendly_name' ] = friendly_name
+ if device_class is not None:
+ attributes[ 'device_class' ] = device_class
+ if current_position is not None:
+ attributes[ 'current_position' ] = current_position
+ return {
+ 'entity_id': entity_id,
+ 'state': state,
+ 'attributes': attributes,
+ 'last_changed': '2026-01-01T00:00:00+00:00',
+ 'last_reported': '2026-01-01T00:00:00+00:00',
+ 'last_updated': '2026-01-01T00:00:00+00:00',
+ 'context': { 'id': 'ctx', 'parent_id': None, 'user_id': None },
+ }
+
+
+def _make_cover_hass_state( **kwargs ):
+ return HassConverter.create_hass_state( _make_cover_api_dict( **kwargs ) )
+
+
+def _build_cover_device( device_id, **kwargs ):
+ api_dict = _make_cover_api_dict( entity_id=f'cover.{device_id}', **kwargs )
+ hass_state = HassConverter.create_hass_state( api_dict )
+ device = HassDevice( device_id=device_id )
+ device.add_state( hass_state )
+ return device
+
+
+class TestCoverEntityStateTypeMapping(TestCase):
+ """``_determine_entity_state_type_from_mapping`` must split
+ covers into the discrete OPEN_CLOSE family and the continuous
+ OPEN_CLOSE_POSITION family based on whether the HA state
+ reports ``current_position``."""
+
+ def test_garage_without_position_is_open_close(self):
+ hass_state = _make_cover_hass_state( device_class='garage' )
+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )
+ self.assertEqual( result, EntityStateType.OPEN_CLOSE )
+
+ def test_blind_with_position_is_open_close_position(self):
+ hass_state = _make_cover_hass_state(
+ device_class='blind', current_position=42, state='open',
+ )
+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )
+ self.assertEqual( result, EntityStateType.OPEN_CLOSE_POSITION )
+
+ def test_no_device_class_no_position_falls_through_to_open_close(self):
+ hass_state = _make_cover_hass_state()
+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )
+ self.assertEqual( result, EntityStateType.OPEN_CLOSE )
+
+ def test_position_override_beats_device_class_specialization(self):
+ # A garage cover that *does* report current_position is
+ # routed to OPEN_CLOSE_POSITION even though the device-class
+ # mapping table would otherwise pick OPEN_CLOSE.
+ hass_state = _make_cover_hass_state(
+ device_class='garage', current_position=80, state='open',
+ )
+ result = HassConverter._determine_entity_state_type_from_mapping( hass_state )
+ self.assertEqual( result, EntityStateType.OPEN_CLOSE_POSITION )
+
+
+class TestCoverInboundStateTranslation(TestCase):
+ """``_cover_to_sensor_value_map`` must emit numeric position
+ when present and otherwise pass HA's discrete state through
+ unchanged (including transitional ``opening`` / ``closing``)."""
+
+ def test_position_is_emitted_as_numeric_string(self):
+ hass_state = _make_cover_hass_state(
+ device_class='blind', current_position=42, state='open',
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ self.assertEqual( list( value_map.values() )[ 0 ], '42' )
+
+ def test_position_zero_is_emitted_not_dropped(self):
+ # str('0') is non-empty so monitors.py's truthiness check
+ # passes through; the regression risk is treating '0' as
+ # falsy upstream and skipping the commit.
+ hass_state = _make_cover_hass_state(
+ device_class='blind', current_position=0, state='closed',
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ self.assertEqual( list( value_map.values() )[ 0 ], '0' )
+
+ def test_discrete_state_passes_through_when_no_position(self):
+ for state in ( 'open', 'closed', 'opening', 'closing' ):
+ with self.subTest( state=state ):
+ hass_state = _make_cover_hass_state(
+ device_class='garage', state=state,
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ self.assertEqual( list( value_map.values() )[ 0 ], state )
+
+ def test_non_numeric_position_returns_empty(self):
+ # Defensive: HA shouldn't produce non-numeric positions,
+ # but we don't want to crash the poll loop if it does.
+ hass_state = _make_cover_hass_state(
+ device_class='blind', current_position='garbage', state='open',
+ )
+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )
+ self.assertEqual( value_map, {} )
+
+
+class TestCoverEntityTypeRouting(TestCase):
+ """``hass_device_to_entity_type`` routes garage covers to the
+ specialized GARAGE_DOOR_OPENER and every other cover device
+ class to the generic OPEN_CLOSE_ACTUATOR."""
+
+ def test_garage_routes_to_garage_door_opener(self):
+ device = _build_cover_device( 'main_garage', device_class='garage' )
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_type( device ),
+ EntityType.GARAGE_DOOR_OPENER,
+ )
+
+ def test_blind_routes_to_open_close_actuator(self):
+ device = _build_cover_device( 'living_room_blind', device_class='blind' )
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_type( device ),
+ EntityType.OPEN_CLOSE_ACTUATOR,
+ )
+
+ def test_no_device_class_routes_to_open_close_actuator(self):
+ device = _build_cover_device( 'unspecified_cover' )
+ self.assertEqual(
+ HassConverter.hass_device_to_entity_type( device ),
+ EntityType.OPEN_CLOSE_ACTUATOR,
+ )
+
+
+class TestCoverImport(TestCase):
+ """End-to-end import of cover devices: the right
+ EntityStateType, controller type, and outbound payload land
+ on the imported models."""
+
+ def test_garage_imports_with_open_close_state(self):
+ device = _build_cover_device( 'garage_a', device_class='garage' )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device,
+ add_alarm_events=False,
+ )
+ states = list( EntityState.objects.filter( entity=entity ) )
+ self.assertEqual( len( states ), 1 )
+ self.assertEqual( states[ 0 ].entity_state_type, EntityStateType.OPEN_CLOSE )
+
+ controllers = list( Controller.objects.filter( entity_state=states[ 0 ] ) )
+ self.assertEqual( len( controllers ), 1 )
+ payload = controllers[ 0 ].integration_payload
+ self.assertEqual( payload.get( 'on_service' ), HassApi.OPEN_COVER_SERVICE )
+ self.assertEqual( payload.get( 'off_service' ), HassApi.CLOSE_COVER_SERVICE )
+
+ def test_blind_with_position_imports_with_open_close_position_state(self):
+ device = _build_cover_device(
+ 'blind_a', device_class='blind',
+ current_position=50, state='open',
+ )
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device,
+ add_alarm_events=False,
+ )
+ states = list( EntityState.objects.filter( entity=entity ) )
+ self.assertEqual( len( states ), 1 )
+ self.assertEqual(
+ states[ 0 ].entity_state_type, EntityStateType.OPEN_CLOSE_POSITION,
+ )
+
+ controllers = list( Controller.objects.filter( entity_state=states[ 0 ] ) )
+ self.assertEqual( len( controllers ), 1 )
+ payload = controllers[ 0 ].integration_payload
+ self.assertEqual(
+ payload.get( 'set_service' ), HassApi.SET_COVER_POSITION_SERVICE,
+ )
+
+
+class TestCoverOutboundDispatch(TestCase):
+ """``hi_value_to_hass_service_call`` for cover-domain payloads:
+ string ``open`` / ``closed`` route to the discrete open/close
+ services; numeric values route to set_cover_position."""
+
+ def _payload(self, *, with_set_service=True):
+ payload = {
+ 'domain': 'cover',
+ 'is_controllable': True,
+ 'on_service': HassApi.OPEN_COVER_SERVICE,
+ 'off_service': HassApi.CLOSE_COVER_SERVICE,
+ 'parameters': { 'position': 'percentage' },
+ }
+ if with_set_service:
+ payload[ 'set_service' ] = HassApi.SET_COVER_POSITION_SERVICE
+ return payload
+
+ def test_open_routes_to_open_cover_service(self):
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='cover.front',
+ hi_control_value='open',
+ domain_payload=self._payload( with_set_service=False ),
+ )
+ self.assertEqual( service_call, HassServiceCall(
+ domain='cover',
+ service=HassApi.OPEN_COVER_SERVICE,
+ hass_entity_id='cover.front',
+ ))
+
+ def test_closed_routes_to_close_cover_service(self):
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='cover.front',
+ hi_control_value='closed',
+ domain_payload=self._payload( with_set_service=False ),
+ )
+ self.assertEqual( service_call, HassServiceCall(
+ domain='cover',
+ service=HassApi.CLOSE_COVER_SERVICE,
+ hass_entity_id='cover.front',
+ ))
+
+ def test_numeric_routes_to_set_cover_position(self):
+ service_call = HassConverter.hi_value_to_hass_service_call(
+ hass_substate_id='cover.blind',
+ hi_control_value='42',
+ domain_payload=self._payload(),
+ )
+ self.assertEqual( service_call, HassServiceCall(
+ domain='cover',
+ service=HassApi.SET_COVER_POSITION_SERVICE,
+ hass_entity_id='cover.blind',
+ service_data={ 'position': 42 },
+ ))
diff --git a/src/hi/services/hass/tests/test_hass_converter_entity_type.py b/src/hi/services/hass/tests/test_hass_converter_entity_type.py
index 1af16f2d..d62b9913 100644
--- a/src/hi/services/hass/tests/test_hass_converter_entity_type.py
+++ b/src/hi/services/hass/tests/test_hass_converter_entity_type.py
@@ -77,13 +77,13 @@ class HassDeviceToEntityTypeTests( TestCase ):
EntityType.DOOR_LOCK,
)
- def test_cover_domain_maps_to_open_close_sensor( self ):
+ def test_cover_domain_maps_to_open_close_actuator( self ):
device = _make_device(
entity_id = 'cover.bedroom_blinds', friendly_name = 'Bedroom Blinds',
)
self.assertEqual(
HassConverter.hass_device_to_entity_type( device ),
- EntityType.OPEN_CLOSE_SENSOR,
+ EntityType.OPEN_CLOSE_ACTUATOR,
)
def test_fan_domain_maps_to_ceiling_fan( self ):
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index 671f1239..c1ce3cf0 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -409,3 +409,17 @@ DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = False
# For testing UI error display of the various attribute editing form errors.
DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS = False
+
+# Per-state tracing for debugging value flow across the HA
+# integration and the simulator. The master switch is
+# ``DEBUG_TRACE_STATE``; main-code call sites short-circuit on
+# it for zero overhead when off. When on, the trace dispatcher
+# consults ``DEBUG_TRACE_HA_ENTITY_IDS`` (HA entity_ids; matched
+# against the integration_name with any ``~suffix`` stripped, so
+# a single entry like ``cover.x`` catches its substate variants)
+# and ``DEBUG_TRACE_HI_ENTITY_STATE_IDS`` (HI EntityState PKs)
+# for granularity. ``settings.DEBUG`` must also be True. See
+# ``hi.testing.dev_overrides.StateTraceManager``.
+DEBUG_TRACE_STATE = False
+DEBUG_TRACE_HA_ENTITY_IDS = [ ] # strings / integration_key.name
+DEBUG_TRACE_HI_ENTITY_STATE_IDS = [ ] # ints / EntityState database ids
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index a2dac566..35133672 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -129,6 +129,11 @@ LOGGING = {
'handlers': ['console' ],
'level': 'INFO',
},
+ 'hi.state_trace': {
+ 'handlers': ['console' ],
+ 'level': 'INFO',
+ 'propagate': False,
+ },
'django.template': {
'handlers': ['console'],
'level': 'INFO', # Changed from DEBUG to INFO to reduce verbose variable lookup messages
@@ -156,3 +161,11 @@ DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = False # Set to True to enable
# For testing UI error display of the various attribute editing form errors.
DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS = False
+
+# Per-state tracing for debugging value flow. Set
+# ``DEBUG_TRACE_STATE = True`` and populate one or both id lists
+# with the specific HA entity_ids and/or HI EntityState PKs to
+# instrument.
+DEBUG_TRACE_STATE = False
+DEBUG_TRACE_HA_ENTITY_IDS = [] # strings / integration_key.name
+DEBUG_TRACE_HI_ENTITY_STATE_IDS = [] # ints / EntityState database ids
diff --git a/src/hi/simulator/enums.py b/src/hi/simulator/enums.py
index dee4b058..009c5fb7 100644
--- a/src/hi/simulator/enums.py
+++ b/src/hi/simulator/enums.py
@@ -92,6 +92,7 @@ class SimEntityType(LabeledEnum):
LIGHT_SENSOR = ( 'Light Sensor', '' )
MOTION_SENSOR = ( 'Motion Sensor', '' )
NETWORK_SWITCH = ( 'Network Switch', '' )
+ OPEN_CLOSE_ACTUATOR = ( 'Open/Close Actuator', '' )
OPEN_CLOSE_SENSOR = ( 'Open/Close Sensor', '' )
OTHER = ( 'Other', '' ) # Will use generic visual element
PRESENCE_SENSOR = ( 'Presence Sensor', '' )
diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.py
index 84a6e21f..809d0551 100644
--- a/src/hi/simulator/management/commands/seed_sim_profiles.py
+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py
@@ -75,6 +75,8 @@ from hi.simulator.enums import SimEntityType
from hi.simulator.models import DbSimEntity, SimProfile
from hi.simulator.services.hass.sim_models import (
HassColorSmartBulbFields,
+ HassGarageCoverFields,
+ HassGenericCoverFields,
HassInsteonDimmerLightSwitchFields,
HassInsteonDualBandLightSwitchFields,
HassInsteonLightSwitchFields,
@@ -83,6 +85,7 @@ from hi.simulator.services.hass.sim_models import (
HassInsteonOutletFields,
HassLockFields,
HassSmartBulbFields,
+ HassWindowBlindCoverFields,
)
from hi.simulator.services.homebox.attachment_catalog import AttachmentTemplate
from hi.simulator.services.homebox.sim_models import (
@@ -347,6 +350,9 @@ class Command(BaseCommand):
self._add_hass_smart_bulb( profile, 'Zoo Smart Bulb' )
self._add_hass_color_smart_bulb( profile, 'Zoo Color Bulb' )
self._add_hass_lock( profile, 'Zoo Lock' )
+ self._add_hass_garage_cover( profile, 'Zoo Garage' )
+ self._add_hass_window_blind_cover( profile, 'Zoo Blind' )
+ self._add_hass_generic_cover( profile, 'Zoo Cover' )
return profile.db_sim_entities.count()
def _build_volume(self, profile: SimProfile) -> int:
@@ -487,6 +493,33 @@ class Command(BaseCommand):
fields_kwargs = {'name': name},
)
+ def _add_hass_garage_cover(self, profile, name):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassGarageCoverFields,
+ sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
+ fields_kwargs = {'name': name},
+ )
+
+ def _add_hass_window_blind_cover(self, profile, name):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassWindowBlindCoverFields,
+ sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
+ fields_kwargs = {'name': name},
+ )
+
+ def _add_hass_generic_cover(self, profile, name):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassGenericCoverFields,
+ sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
+ fields_kwargs = {'name': name},
+ )
+
def _add_homebox_item(self, profile, name, **fields_kwargs):
kwargs = {'name': name}
kwargs.update(fields_kwargs)
diff --git a/src/hi/simulator/services/hass/service_dispatchers.py b/src/hi/simulator/services/hass/service_dispatchers.py
index a60f5097..948dd544 100644
--- a/src/hi/simulator/services/hass/service_dispatchers.py
+++ b/src/hi/simulator/services/hass/service_dispatchers.py
@@ -28,7 +28,13 @@ from typing import Any, Dict, List, Optional, Tuple
from hi.simulator.enums import SimStateType
-from .sim_models import HassColorSmartBulbFields, HassLockFields
+from .sim_models import (
+ HassColorSmartBulbFields,
+ HassGarageCoverFields,
+ HassGenericCoverFields,
+ HassLockFields,
+ HassWindowBlindCoverFields,
+)
class HassServiceDispatcher:
@@ -167,6 +173,52 @@ class HassServiceDispatcher:
return [ ( 'lock', 'off' ) ]
return []
+ @staticmethod
+ def _discrete_cover( sim_entity,
+ domain : str,
+ service : str,
+ payload : Dict[ str, Any ],
+ ) -> List[ Tuple[ str, str ] ]:
+ """Discrete open/close cover (no position attribute):
+ ``open_cover`` / ``close_cover`` toggle the ON_OFF
+ SimState. Used by every cover whose HA shape is binary
+ — garage doors, generic covers, and any future cover
+ device class without ``current_position``."""
+ if domain != 'cover':
+ return []
+ if service == 'open_cover':
+ return [ ( 'cover', 'on' ) ]
+ if service == 'close_cover':
+ return [ ( 'cover', 'off' ) ]
+ return []
+
+ @staticmethod
+ def _window_blind_cover( sim_entity,
+ domain : str,
+ service : str,
+ payload : Dict[ str, Any ],
+ ) -> List[ Tuple[ str, str ] ]:
+ """Window blind cover: ``open_cover`` / ``close_cover``
+ snap to 100 / 0; ``set_cover_position`` writes the
+ payload's ``position`` value (0-100) to the CONTINUOUS
+ SimState."""
+ if domain != 'cover':
+ return []
+ if service == 'open_cover':
+ return [ ( 'position', '100' ) ]
+ if service == 'close_cover':
+ return [ ( 'position', '0' ) ]
+ if service == 'set_cover_position':
+ position = payload.get( 'position' )
+ if position is None:
+ return []
+ try:
+ position_int = int( float( position ) )
+ except ( TypeError, ValueError ):
+ return []
+ return [ ( 'position', str( position_int ) ) ]
+ return []
+
@staticmethod
def _extract_brightness_value_str( payload : Dict[ str, Any ] ) -> Optional[ str ]:
"""Read brightness from an HA service-call payload as a
@@ -193,5 +245,8 @@ class HassServiceDispatcher:
# objects exist as references. Keyed off SimEntityFields class.
HassServiceDispatcher._REGISTRY = {
HassColorSmartBulbFields: HassServiceDispatcher._color_smart_bulb,
+ HassGarageCoverFields: HassServiceDispatcher._discrete_cover,
+ HassGenericCoverFields: HassServiceDispatcher._discrete_cover,
HassLockFields: HassServiceDispatcher._lock,
+ HassWindowBlindCoverFields: HassServiceDispatcher._window_blind_cover,
}
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 4e80a8fd..66d81434 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -737,6 +737,142 @@ class HassLockState( HassState ):
}
+@dataclass( frozen = True )
+class HassGarageCoverFields( SimEntityFields ):
+ """Garage door cover. Discrete open/closed; no position
+ attribute (real garage doors are typically on/off)."""
+ pass
+
+
+def _cover_entity_id( name : str ) -> str:
+ suffix = name.lower().replace( ' ', '_' )
+ return f'cover.{suffix}'
+
+
+@dataclass
+class HassGarageCoverState( HassState ):
+ """Internally ON_OFF (open == on); the ``state`` property
+ maps to HA's cover-domain wire strings ``'open'`` /
+ ``'closed'``."""
+
+ sim_entity_fields : HassGarageCoverFields
+ sim_state_type : SimStateType = SimStateType.ON_OFF
+ sim_state_id : str = 'cover'
+ value : str = 'off'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Cover'
+
+ @property
+ def entity_id(self):
+ return _cover_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'open' if str_to_bool( self.value ) else 'closed'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'friendly_name': self.entity_name,
+ 'device_class': 'garage',
+ }
+
+
+@dataclass( frozen = True )
+class HassGenericCoverFields( SimEntityFields ):
+ """Generic cover with no device_class. Discrete
+ open/closed, no position attribute. Exercises the
+ converter's ``(cover, None, None)`` fall-through mapping
+ so future cover device classes that aren't explicitly
+ listed get tested by the same fixture path."""
+ pass
+
+
+@dataclass
+class HassGenericCoverState( HassState ):
+ """Internally ON_OFF (open == on); the ``state`` property
+ maps to HA's cover-domain wire strings ``'open'`` /
+ ``'closed'``. No ``device_class`` attribute is emitted."""
+
+ sim_entity_fields : HassGenericCoverFields
+ sim_state_type : SimStateType = SimStateType.ON_OFF
+ sim_state_id : str = 'cover'
+ value : str = 'off'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Cover'
+
+ @property
+ def entity_id(self):
+ return _cover_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ return 'open' if str_to_bool( self.value ) else 'closed'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'friendly_name': self.entity_name,
+ }
+
+
+@dataclass( frozen = True )
+class HassWindowBlindCoverFields( SimEntityFields ):
+ """Window blind cover with position. Single CONTINUOUS
+ SimState (0-100 percent). The ``state`` property derives
+ open/closed from the position; the ``current_position``
+ attribute carries the numeric value."""
+ pass
+
+
+@dataclass
+class HassWindowBlindCoverState( HassState ):
+ sim_entity_fields : HassWindowBlindCoverFields
+ sim_state_type : SimStateType = SimStateType.CONTINUOUS
+ sim_state_id : str = 'position'
+ value : str = '0'
+
+ @property
+ def min_value(self):
+ return 0
+
+ @property
+ def max_value(self):
+ return 100
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Position'
+
+ @property
+ def entity_id(self):
+ return _cover_entity_id( self.entity_name )
+
+ @property
+ def state(self):
+ try:
+ position = int( float( self.value ) )
+ except ( TypeError, ValueError ):
+ position = 0
+ return 'open' if position > 0 else 'closed'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ try:
+ position = int( float( self.value ) )
+ except ( TypeError, ValueError ):
+ position = 0
+ return {
+ 'friendly_name': self.entity_name,
+ 'device_class': 'blind',
+ 'current_position': position,
+ }
+
+
HASS_SIM_ENTITY_DEFINITION_LIST = [
SimEntityDefinition(
class_label = 'Insteon Switch',
@@ -826,4 +962,28 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [
HassLockState,
],
),
+ SimEntityDefinition(
+ class_label = 'Cover (garage)',
+ sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
+ sim_entity_fields_class = HassGarageCoverFields,
+ sim_state_class_list = [
+ HassGarageCoverState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Cover (window blind)',
+ sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
+ sim_entity_fields_class = HassWindowBlindCoverFields,
+ sim_state_class_list = [
+ HassWindowBlindCoverState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Cover (generic, no device_class)',
+ sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
+ sim_entity_fields_class = HassGenericCoverFields,
+ sim_state_class_list = [
+ HassGenericCoverState,
+ ],
+ ),
]
diff --git a/src/hi/static/css/control.css b/src/hi/static/css/control.css
index f88e33e7..4c54bfff 100644
--- a/src/hi/static/css/control.css
+++ b/src/hi/static/css/control.css
@@ -181,6 +181,19 @@
transform: scale(1.1);
}
+.hi-continuous-slider-row {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding-right: 0.5rem;
+}
+
+.hi-continuous-slider-extreme {
+ font-size: 0.8rem;
+ color: var(--text-color, #333);
+ white-space: nowrap;
+}
+
.hi-continuous-slider-display {
display: flex;
align-items: center;
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index 817a0d51..9496d225 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -712,15 +712,15 @@ path.hover-target[hover] + path.hi-path-open {
}
g[status="active"] {
- outline: 2px solid var(--status-active-color);
filter: drop-shadow(0 0 5px var(--status-active-color));
}
g[status="recent"] {
- outline: 2px solid var(--status-recent-color);
+ filter: drop-shadow(0 0 5px var(--status-recent-color));
+}
+g[status="partial"] {
filter: drop-shadow(0 0 5px var(--status-recent-color));
}
g[status="past"] {
- outline: 2px solid var(--status-past-color);
filter: drop-shadow(0 0 5px var(--status-past-color));
}
@@ -795,6 +795,10 @@ div[status="past"] {
color: var(--on-status-past-color);
background-color: var(--status-past-color);
}
+div[status="partial"] {
+ color: var(--on-status-recent-color);
+ background-color: var(--status-recent-color);
+}
div[status="open"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
diff --git a/src/hi/static/js/controllers.js b/src/hi/static/js/controllers.js
index ac03cc17..606ef35c 100644
--- a/src/hi/static/js/controllers.js
+++ b/src/hi/static/js/controllers.js
@@ -58,10 +58,11 @@
return;
}
if ( type === 'checkbox' ) {
- const checked = _coerceCheckboxValue( value );
+ const checked = _coerceCheckboxValue( element, value );
if ( element.checked !== checked ) {
element.checked = checked;
}
+ _syncCheckboxStatusText( element, checked );
return;
}
}
@@ -102,18 +103,48 @@
$display.text( format.replace( '{n}', slider.value ) );
}
+ function _syncCheckboxStatusText( checkbox, checked ) {
+ // Mirror a checkbox's checked-state into a paired text
+ // label (e.g., the "On"/"Off" caption under a toggle).
+ // Labels are carried as ``data-on-text`` and
+ // ``data-off-text`` on the checkbox so different
+ // controller variants can use domain-specific wording
+ // (e.g., "Open"/"Closed", "Locked"/"Unlocked"). The
+ // status text lives in a sibling ``.status-text`` within
+ // the enclosing ``.on-off-control`` container — opt-in:
+ // checkboxes without the data attributes or container
+ // are silently skipped so unrelated checkboxes are
+ // unaffected.
+ const onText = checkbox.getAttribute( 'data-on-text' );
+ const offText = checkbox.getAttribute( 'data-off-text' );
+ if ( ! onText || ! offText ) return;
+ const $statusText = $( checkbox ).closest( '.on-off-control' )
+ .find( '.status-text' );
+ if ( ! $statusText.length ) return;
+ $statusText.text( checked ? onText : offText );
+ }
+
function _setIfDifferent( element, prop, newValue ) {
if ( element[ prop ] !== newValue ) {
element[ prop ] = newValue;
}
}
- function _coerceCheckboxValue( value ) {
+ function _coerceCheckboxValue( element, value ) {
+ // The truthy wire value comes from the checkbox's own
+ // ``value`` attribute (server-rendered), so each domain's
+ // vocabulary lives in templates rather than duplicated
+ // here. Browsers default unset checkbox ``value`` to
+ // ``'on'``, which is exactly what ON_OFF needs;
+ // OPEN_CLOSE templates set ``value="open"``. ``true`` /
+ // ``1`` remain accepted as universal truthy strings.
if ( typeof value === 'boolean' ) return value;
if ( typeof value === 'number' ) return value !== 0;
if ( typeof value === 'string' ) {
const lowered = value.toLowerCase();
- return lowered === 'on' || lowered === 'true' || lowered === '1';
+ const truthy = ( element.value || 'on' ).toLowerCase();
+ if ( lowered === truthy ) return true;
+ return lowered === 'true' || lowered === '1';
}
return Boolean( value );
}
diff --git a/src/hi/testing/dev_overrides.py b/src/hi/testing/dev_overrides.py
index 6e096179..e1cd69c2 100644
--- a/src/hi/testing/dev_overrides.py
+++ b/src/hi/testing/dev_overrides.py
@@ -1,5 +1,6 @@
import logging
import random
+from typing import Any, Optional
from django.conf import settings
from django.forms.utils import ErrorList
@@ -7,6 +8,7 @@ from django.forms.utils import ErrorList
from hi.apps.attribute.transient_models import AttributeEditFormData
logger = logging.getLogger(__name__)
+trace_logger = logging.getLogger('hi.state_trace')
class DevOverrideManager:
@@ -96,5 +98,92 @@ class DevOverrideManager:
# Always return False to simulate validation failure
return False
-
-
+
+ @classmethod
+ def trace_state( cls,
+ label : str,
+ ha_entity_id : Optional[ str ] = None,
+ hi_entity_state_id : Optional[ int ] = None,
+ ha_value : Any = None,
+ hi_value : Any = None,
+ **kwargs : Any ) -> None:
+ if not StateTraceManager.is_traced(
+ ha_entity_id = ha_entity_id,
+ hi_entity_state_id = hi_entity_state_id ):
+ return
+ StateTraceManager.emit(
+ label = label,
+ ha_entity_id = ha_entity_id,
+ hi_entity_state_id = hi_entity_state_id,
+ ha_value = ha_value,
+ hi_value = hi_value,
+ **kwargs,
+ )
+
+
+class StateTraceManager:
+ """
+ Per-state tracing for debugging value flow across the HA
+ integration and the simulator.
+
+ Reached from main code only via ``DevOverrideManager.trace_state``;
+ main-code sites short-circuit on
+ ``settings.DEBUG and settings.DEBUG_TRACE_STATE`` so this class
+ is only consulted when tracing is on.
+
+ Granularity is set by ``DEBUG_TRACE_HA_ENTITY_IDS`` (HA
+ entity_ids; the matcher strips any ``~suffix`` so a single
+ entry like ``'cover.x'`` catches its substate variants) and
+ ``DEBUG_TRACE_HI_ENTITY_STATE_IDS`` (HI EntityState PKs).
+ Output goes to the dedicated ``hi.state_trace`` logger at
+ INFO so verbosity can be scoped independently of other
+ loggers.
+ """
+
+ @classmethod
+ def is_traced( cls,
+ ha_entity_id : Optional[ str ] = None,
+ hi_entity_state_id : Optional[ int ] = None ) -> bool:
+ if ha_entity_id:
+ target = ha_entity_id.split( '~', 1 )[ 0 ]
+ if target in settings.DEBUG_TRACE_HA_ENTITY_IDS:
+ return True
+ if hi_entity_state_id is not None:
+ if hi_entity_state_id in settings.DEBUG_TRACE_HI_ENTITY_STATE_IDS:
+ return True
+ return False
+
+ # Tabular column widths. Generous so common values fit without
+ # disrupting alignment; long values overflow the slot and
+ # disrupt only their own row, not subsequent ones.
+ LABEL_W = 28
+ HA_ID_W = 32
+ HA_VAL_W = 14
+ HI_ID_W = 6
+ HI_VAL_W = 36
+
+ @classmethod
+ def emit( cls,
+ label : str,
+ ha_entity_id : Optional[ str ] = None,
+ hi_entity_state_id : Optional[ int ] = None,
+ ha_value : Any = None,
+ hi_value : Any = None,
+ **kwargs : Any ) -> None:
+ ha_id_str = ha_entity_id or ''
+ hi_id_str = '' if hi_entity_state_id is None else str( hi_entity_state_id )
+ ha_val_str = '' if ha_value is None else str( ha_value )
+ hi_val_str = '' if hi_value is None else str( hi_value )
+ extras_str = ' '.join( f'{k}={v}' for k, v in kwargs.items() )
+ line = (
+ f'{label:<{cls.LABEL_W}} | '
+ f'{ha_id_str:<{cls.HA_ID_W}} | '
+ f'{ha_val_str:<{cls.HA_VAL_W}} | '
+ f'{hi_id_str:<{cls.HI_ID_W}} | '
+ f'{hi_val_str:<{cls.HI_VAL_W}} | '
+ f'{extras_str}'
+ )
+ trace_logger.info( line.rstrip() )
+
+
+