Home Information - Your home, your data, organized.
Python
Issue #300: HA binary sensors (door/window/smoke) coverage (#311)
Tony Cc65d21b77d5d
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex 262b358d..20766d70 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -204,6 +204,9 @@ class EntityStateValue(LabeledEnum):HIGH = ( 'High', '' )LOW = ( 'Low', '' )+ SMOKE_DETECTED = ( 'Smoke Detected', '' )+ SMOKE_CLEAR = ( 'Clear', '' )+# COLOR_MODE values — modes a smart bulb can be in. UNKNOWN# covers integrations that don't report a mode and cases where# the bulb hasn't yet declared one. Names follow HA's modes;@@ -314,6 +317,9 @@ class EntityStateType(LabeledEnum):EntityStateValue.IDLE ] )SATURATION = ( 'Saturation' , 'Color saturation as a percentage (0-100)',[] )+ SMOKE = ( 'Smoke' , '',+ [ EntityStateValue.SMOKE_DETECTED,+ EntityStateValue.SMOKE_CLEAR ] )SOUND_LEVEL = ( 'Sound Level' , '',[] )TEMPERATURE = ( 'Temperature' , '',diff --git a/src/hi/apps/entity/templatetags/__init__.py b/src/hi/apps/entity/templatetags/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/entity/templatetags/entity_tags.py b/src/hi/apps/entity/templatetags/entity_tags.pynew file mode 100644index 00000000..1da9c0b2--- /dev/null+++ b/src/hi/apps/entity/templatetags/entity_tags.py@@ -0,0 +1,20 @@+from django import template++from hi.apps.entity.enums import EntityStateValue++register = template.Library()+++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 valuediff --git a/src/hi/apps/entity/tests/test_entity_tags.py b/src/hi/apps/entity/tests/test_entity_tags.pynew file mode 100644index 00000000..2f2ad53e--- /dev/null+++ b/src/hi/apps/entity/tests/test_entity_tags.py@@ -0,0 +1,34 @@+import logging++from hi.apps.entity.templatetags.entity_tags import value_label+from hi.testing.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++class TestValueLabel(BaseTestCase):+ """``value_label`` resolves a stored EntityStateValue wire string+ (the lowercased enum name) to its human-readable label so+ template-rendered sensor displays show ``"Smoke Detected"``+ rather than ``"smoke_detected"``."""++ def test_resolves_underscore_separated_value(self):+ # The motivating case: multi-word values that look broken+ # in their wire form.+ self.assertEqual( value_label( 'smoke_detected' ), 'Smoke Detected' )++ def test_resolves_single_word_value(self):+ # Pre-existing single-word values (movement / open-close /+ # etc.) get capitalized labels too.+ 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.+ self.assertEqual( value_label( '72.5' ), '72.5' )+ self.assertEqual( value_label( 'arbitrary' ), 'arbitrary' )++ def test_empty_and_none_pass_through(self):+ self.assertEqual( value_label( '' ), '' )+ self.assertIsNone( value_label( None ) )diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex eb8334a9..77df717d 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -46,6 +46,10 @@ class HiModelHelper:DEFAULT_BATTERY_EVENT_WINDOW_SECS = 180DEFAULT_BATTERY_DEDUPE_WINDOW_SECS = 300DEFAULT_BATTERY_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS++ DEFAULT_SMOKE_EVENT_WINDOW_SECS = 180+ DEFAULT_SMOKE_DEDUPE_WINDOW_SECS = 300+ DEFAULT_SMOKE_ALARM_LIFETIME_SECS = Alarm.MAX_LIFETIME_SECS@classmethoddef create_blob_sensor( cls,@@ -209,6 +213,20 @@ class HiModelHelper:provides_video_stream = provides_video_stream,)+ @classmethod+ def create_smoke_sensor( cls,+ entity : Entity,+ integration_key : IntegrationKey = None,+ name : str = None ) -> Sensor:+ if not name:+ name = f'{entity.name} Smoke'+ return cls.create_sensor(+ entity = entity,+ entity_state_type = EntityStateType.SMOKE,+ name = name,+ integration_key = integration_key,+ )+@classmethoddef create_on_off_controller( cls,entity : Entity,@@ -493,6 +511,31 @@ class HiModelHelper:integration_key = integration_key,)+ @classmethod+ def create_smoke_event_definition(+ cls,+ name : str,+ entity_state : EntityState,+ integration_key : IntegrationKey = None ) -> EventDefinition:++ # Smoke is life-safety: both security levels map to CRITICAL.+ # The user's "I'm home, keep things quiet" posture (LOW) does+ # not reduce the urgency of a fire alarm.+ return EventManager().create_simple_alarm_event_definition(+ name = name,+ event_type = EventType.SECURITY,+ entity_state = entity_state,+ value = EntityStateValue.SMOKE_DETECTED,+ security_to_alarm_level = {+ SecurityLevel.HIGH: AlarmLevel.CRITICAL,+ SecurityLevel.LOW: AlarmLevel.CRITICAL,+ },+ event_window_secs = cls.DEFAULT_SMOKE_EVENT_WINDOW_SECS,+ dedupe_window_secs = cls.DEFAULT_SMOKE_DEDUPE_WINDOW_SECS,+ alarm_lifetime_secs = cls.DEFAULT_SMOKE_ALARM_LIFETIME_SECS,+ integration_key = integration_key,+ )+@classmethoddef create_battery_event_definition(cls,diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.pyindex 03f63a4e..4ef572d9 100644--- a/src/hi/apps/monitor/status_display_data.py+++ b/src/hi/apps/monitor/status_display_data.py@@ -15,9 +15,15 @@ class StatusDisplayData:RECENT_MOVEMENT_THRESHOLD_SECS = 90PAST_MOVEMENT_THRESHOLD_SECS = 180-+RECENT_OPEN_THRESHOLD_SECS = 90PAST_OPEN_THRESHOLD_SECS = 180++ # Smoke-alarm decay is longer than movement/open-close: a fire+ # event is rare and the recent / past status carries higher+ # operator significance, so the visual reminder lingers.+ RECENT_SMOKE_THRESHOLD_SECS = 600+ PAST_SMOKE_THRESHOLD_SECS = 1800def __init__( self, entity_state_status_data : EntityStateStatusData ):self._entity_state = entity_state_status_data.entity_state@@ -134,7 +140,7 @@ class StatusDisplayData:return self.latest_display_value.magnitudedef _get_svg_status_style(self):-+if self.entity_state.entity_state_type == EntityStateType.MOVEMENT:return self._get_movement_status_style()@@ -162,6 +168,9 @@ class StatusDisplayData:if self.entity_state.entity_state_type == EntityStateType.HIGH_LOW:return self._get_high_low_status_style()+ if self.entity_state.entity_state_type == EntityStateType.SMOKE:+ return self._get_smoke_status_style()+# TODO: These should map the latest value into a continuous range of colors/opacity## EntityStateType.AIR_PRESSURE@@ -214,6 +223,21 @@ class StatusDisplayData:return StatusStyle.MovementPastreturn StatusStyle.MovementIdle++ def _get_smoke_status_style( self ):++ if self.latest_sensor_value == str(EntityStateValue.SMOKE_DETECTED):+ return StatusStyle.SmokeDetected++ if self.penultimate_sensor_value == str(EntityStateValue.SMOKE_DETECTED):+ smoke_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp+ if smoke_timedelta.total_seconds() < self.RECENT_SMOKE_THRESHOLD_SECS:+ return StatusStyle.SmokeRecent++ elif smoke_timedelta.total_seconds() < self.PAST_SMOKE_THRESHOLD_SECS:+ return StatusStyle.SmokePast++ return StatusStyle.SmokeCleardef _get_on_off_status_style( self ):diff --git a/src/hi/apps/monitor/tests/test_status_display_data.py b/src/hi/apps/monitor/tests/test_status_display_data.pyindex 4110d666..07d0c100 100644--- a/src/hi/apps/monitor/tests/test_status_display_data.py+++ b/src/hi/apps/monitor/tests/test_status_display_data.py@@ -198,6 +198,93 @@ class TestStatusDisplayData(BaseTestCase):self.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)+ # SMOKE State Type Tests with Time Thresholds+ #+ # Mirrors the movement decay pattern but with longer thresholds+ # (10 min recent / 30 min past) since fire events have higher+ # operator significance and the visual reminder should linger.++ @patch('hi.apps.common.datetimeproxy.now')+ def test_smoke_state_detected_returns_smoke_detected(self, mock_now):+ mock_now.return_value = datetime(2023, 1, 1, 12, 0, 0)++ sensor_response = self._create_mock_sensor_response(+ str(EntityStateValue.SMOKE_DETECTED)+ )+ status_data = self._create_entity_state_status_data('SMOKE', [sensor_response])++ display_data = StatusDisplayData(status_data)++ self.assertEqual(display_data.svg_status_style, StatusStyle.SmokeDetected)++ @patch('hi.apps.common.datetimeproxy.now')+ def test_smoke_state_recent_within_threshold(self, mock_now):+ # Penultimate detected 5 minutes ago (within the 10-minute+ # RECENT threshold); current is clear.+ base_time = datetime(2023, 1, 1, 12, 0, 0)+ mock_now.return_value = base_time++ recent_response = self._create_mock_sensor_response(+ str(EntityStateValue.SMOKE_CLEAR), base_time,+ )+ past_response = self._create_mock_sensor_response(+ str(EntityStateValue.SMOKE_DETECTED),+ base_time - timedelta(seconds=300),+ )++ status_data = self._create_entity_state_status_data(+ 'SMOKE', [recent_response, past_response],+ )++ display_data = StatusDisplayData(status_data)++ self.assertEqual(display_data.svg_status_style, StatusStyle.SmokeRecent)++ @patch('hi.apps.common.datetimeproxy.now')+ def test_smoke_state_past_beyond_recent_within_past(self, mock_now):+ # Penultimate detected 20 minutes ago (between RECENT 10+ # min and PAST 30 min thresholds).+ base_time = datetime(2023, 1, 1, 12, 0, 0)+ mock_now.return_value = base_time++ recent_response = self._create_mock_sensor_response(+ str(EntityStateValue.SMOKE_CLEAR), base_time,+ )+ past_response = self._create_mock_sensor_response(+ str(EntityStateValue.SMOKE_DETECTED),+ base_time - timedelta(seconds=1200),+ )++ status_data = self._create_entity_state_status_data(+ 'SMOKE', [recent_response, past_response],+ )++ display_data = StatusDisplayData(status_data)++ self.assertEqual(display_data.svg_status_style, StatusStyle.SmokePast)++ @patch('hi.apps.common.datetimeproxy.now')+ def test_smoke_state_clear_after_past_threshold(self, mock_now):+ # Penultimate detected 1 hour ago (beyond PAST 30 min).+ base_time = datetime(2023, 1, 1, 12, 0, 0)+ mock_now.return_value = base_time++ recent_response = self._create_mock_sensor_response(+ str(EntityStateValue.SMOKE_CLEAR), base_time,+ )+ past_response = self._create_mock_sensor_response(+ str(EntityStateValue.SMOKE_DETECTED),+ base_time - timedelta(seconds=3600),+ )++ status_data = self._create_entity_state_status_data(+ 'SMOKE', [recent_response, past_response],+ )++ display_data = StatusDisplayData(status_data)++ self.assertEqual(display_data.svg_status_style, StatusStyle.SmokeClear)+# PRESENCE State Type Tests (similar to movement)@patch('hi.apps.common.datetimeproxy.now')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.htmlindex a449190f..d142803a 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 +1,2 @@-<div class="text-center px-2" status="{{ sensor_response.value }}">{{ sensor_response.value }}</div>+{% load entity_tags %}+<div class="text-center px-2" status="{{ sensor_response.value }}">{{ sensor_response.value|value_label }}</div>diff --git a/src/hi/hi_styles.py b/src/hi/hi_styles.pyindex 03b24b3c..a553c249 100644--- a/src/hi/hi_styles.py+++ b/src/hi/hi_styles.py@@ -487,6 +487,43 @@ class StatusStyle:fill_color = STATUS_OK_COLOR,fill_opacity = 0.15,)+ # Smoke alarm reuses the movement / open-close ``active`` /+ # ``recent`` / ``past`` / ``idle`` status_value vocabulary so+ # the existing g[status="…"] / div[status="…"] CSS rules+ # apply unchanged. The state-type-specific labeling lives in+ # the ``EntityStateValue`` enum, not the SVG status attribute.+ SmokeDetected = SvgStatusStyle(+ status_value = 'active',+ stroke_color = STATUS_ACTIVE_COLOR,+ stroke_width = DEFAULT_STROKE_WIDTH,+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,+ fill_color = STATUS_ACTIVE_COLOR,+ fill_opacity = 0.5,+ )+ SmokeRecent = SvgStatusStyle(+ status_value = 'recent',+ stroke_color = STATUS_RECENT_COLOR,+ stroke_width = DEFAULT_STROKE_WIDTH,+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,+ fill_color = STATUS_RECENT_COLOR,+ fill_opacity = 0.5,+ )+ SmokePast = SvgStatusStyle(+ status_value = 'past',+ stroke_color = STATUS_PAST_COLOR,+ stroke_width = DEFAULT_STROKE_WIDTH,+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,+ fill_color = STATUS_PAST_COLOR,+ fill_opacity = 0.5,+ )+ SmokeClear = SvgStatusStyle(+ status_value = 'idle',+ stroke_color = STATUS_OK_COLOR,+ stroke_width = DEFAULT_STROKE_WIDTH,+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,+ fill_color = STATUS_OK_COLOR,+ fill_opacity = 0.15,+ )On = SvgStatusStyle(status_value = 'on',stroke_color = 'yellow',diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex 32ef6095..124e22be 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -239,6 +239,7 @@ class HassConverter:(HassApi.BINARY_SENSOR_DOMAIN, HassApi.DOOR_DEVICE_CLASS, None): EntityStateType.OPEN_CLOSE,(HassApi.BINARY_SENSOR_DOMAIN, HassApi.GARAGE_DOOR_DEVICE_CLASS, None): EntityStateType.OPEN_CLOSE,(HassApi.BINARY_SENSOR_DOMAIN, HassApi.WINDOW_DEVICE_CLASS, None): EntityStateType.OPEN_CLOSE,+ (HassApi.BINARY_SENSOR_DOMAIN, HassApi.SMOKE_DEVICE_CLASS, None): EntityStateType.SMOKE,(HassApi.BINARY_SENSOR_DOMAIN, None, None): EntityStateType.ON_OFF, # Generic binary sensor# Sensor Domain (read-only sensors)@@ -1695,6 +1696,12 @@ class HassConverter:integration_key = integration_key,name = name,)+ elif entity_state_type == EntityStateType.SMOKE:+ sensor = HiModelHelper.create_smoke_sensor(+ entity = entity,+ integration_key = integration_key,+ name = name,+ )else:# Default fallbacksensor = HiModelHelper.create_blob_sensor(@@ -1828,6 +1835,18 @@ class HassConverter:integration_key = integration_key,name = name,)+ elif entity_state_type == EntityStateType.SMOKE:+ sensor = HiModelHelper.create_smoke_sensor(+ entity = entity,+ integration_key = integration_key,+ name = name,+ )+ if add_alarm_events:+ HiModelHelper.create_smoke_event_definition(+ name = f'{sensor.name} Alarm',+ entity_state = sensor.entity_state,+ integration_key = integration_key,+ )else:# Default fallbacksensor = HiModelHelper.create_blob_sensor(@@ -1835,7 +1854,7 @@ class HassConverter:integration_key = integration_key,name = name,)-+# Store domain payload for sensorssensor.integration_payload = domain_payloadsensor.save()@@ -1954,6 +1973,8 @@ class HassConverter:return EntityType.OPEN_CLOSE_SENSORif HassApi.MOTION_DEVICE_CLASS in device_class_set:return EntityType.MOTION_SENSOR+ if HassApi.SMOKE_DEVICE_CLASS in device_class_set:+ return EntityType.SMOKE_DETECTORif ( HassApi.LIGHT_DOMAIN in domain_setor HassApi.LIGHT_DEVICE_CLASS in device_class_set ):return EntityType.LIGHT@@ -2152,8 +2173,9 @@ class HassConverter:def _binary_sensor_value( cls, hass_state : HassState ) -> Optional[ str ]:"""Translate HA binary state (on/off) plus device_class tothe matching HI EntityStateValue: ACTIVE/IDLE for motion,- OPEN/CLOSED for doors and peers, CONNECTED/DISCONNECTED- for connectivity, LOW/HIGH for battery."""+ OPEN/CLOSED for doors and peers, SMOKE_DETECTED/SMOKE_CLEAR+ for smoke, CONNECTED/DISCONNECTED for connectivity,+ LOW/HIGH for battery."""sv = hass_state.state_value.lower()dc = hass_state.device_classif sv == HassStateValue.ON:@@ -2163,6 +2185,8 @@ class HassConverter:return str( EntityStateValue.LOW )if dc in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:return str( EntityStateValue.OPEN )+ if dc == HassApi.SMOKE_DEVICE_CLASS:+ return str( EntityStateValue.SMOKE_DETECTED )if dc == HassApi.CONNECTIVITY_DEVICE_CLASS:return str( EntityStateValue.CONNECTED )return str( EntityStateValue.ON )@@ -2173,6 +2197,8 @@ class HassConverter:return str( EntityStateValue.HIGH )if dc in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:return str( EntityStateValue.CLOSED )+ if dc == HassApi.SMOKE_DEVICE_CLASS:+ return str( EntityStateValue.SMOKE_CLEAR )if dc == HassApi.CONNECTIVITY_DEVICE_CLASS:return str( EntityStateValue.DISCONNECTED )return str( EntityStateValue.OFF )diff --git a/src/hi/services/hass/hass_models.py b/src/hi/services/hass/hass_models.pyindex abbf88d8..77f0873f 100644--- a/src/hi/services/hass/hass_models.py+++ b/src/hi/services/hass/hass_models.py@@ -104,6 +104,7 @@ class HassApi:LIGHT_DEVICE_CLASS = 'light'MOTION_DEVICE_CLASS = 'motion'OUTLET_DEVICE_CLASS = 'outlet'+ SMOKE_DEVICE_CLASS = 'smoke'TEMPERATURE_DEVICE_CLASS = 'temperature'TIMESTAMP_DEVICE_CLASS = 'timestamp'WINDOW_DEVICE_CLASS = 'window'diff --git a/src/hi/services/hass/tests/test_hass_converter_binary_sensor.py b/src/hi/services/hass/tests/test_hass_converter_binary_sensor.pynew file mode 100644index 00000000..c7903029--- /dev/null+++ b/src/hi/services/hass/tests/test_hass_converter_binary_sensor.py@@ -0,0 +1,167 @@+import logging++from django.test import TestCase++from hi.apps.entity.enums import (+ EntityStateType, EntityStateValue, EntityType,+)+from hi.apps.entity.models import EntityState+from hi.apps.event.models import EventDefinition+from hi.services.hass.hass_converter import HassConverter+from hi.services.hass.hass_metadata import HassMetaData+from hi.services.hass.hass_models import HassDevice++logging.disable(logging.CRITICAL)+++def _build_binary_sensor_device( name, device_class = None, state = 'off' ):+ """Construct a HassDevice with a single ``binary_sensor.x`` state+ of the specified device_class. Mirrors the pattern in+ ``test_hass_converter_create.py``."""+ attributes = {+ 'friendly_name': name.replace( '_', ' ' ).title(),+ }+ if device_class is not None:+ attributes[ 'device_class' ] = device_class+ api_dict = {+ 'entity_id': f'binary_sensor.{name}',+ '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 },+ }+ hass_state = HassConverter.create_hass_state( api_dict )+ device = HassDevice( device_id = name )+ device.add_state( hass_state )+ return device, hass_state+++def _value_for( hass_state ):+ value_map = HassConverter.hass_state_to_sensor_value_map( hass_state )+ return next( iter( value_map.values() ) )+++class TestSmokeBinarySensor(TestCase):+ """Smoke is the new device-class branch added for #300. Covers+ value emission, EntityState creation (regression guard for the+ fall-through-to-BLOB bug), and EntityType assignment."""++ def test_smoke_on_emits_smoke_detected(self):+ _, hass_state = _build_binary_sensor_device(+ 'kitchen_smoke', device_class = 'smoke', state = 'on',+ )+ self.assertEqual(+ _value_for( hass_state ),+ str( EntityStateValue.SMOKE_DETECTED ),+ )++ def test_smoke_off_emits_smoke_clear(self):+ _, hass_state = _build_binary_sensor_device(+ 'kitchen_smoke', device_class = 'smoke', state = 'off',+ )+ self.assertEqual(+ _value_for( hass_state ),+ str( EntityStateValue.SMOKE_CLEAR ),+ )++ def test_smoke_creates_entity_state_with_smoke_type(self):+ # Regression guard. The mapping table picks+ # ``EntityStateType.SMOKE``, but+ # ``_create_sensor_from_entity_state_type_with_params``+ # previously had no SMOKE branch and fell through to+ # ``create_blob_sensor`` — the EntityState ended up with+ # ``entity_state_type_str='blob'``, breaking every smoke-+ # specific dispatch downstream (StatusDisplayData,+ # rendering, etc.).+ device, _ = _build_binary_sensor_device(+ 'kitchen_smoke', device_class = 'smoke',+ )+ 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_str,+ str( EntityStateType.SMOKE ),+ )++ def test_smoke_assigns_smoke_detector_entity_type(self):+ device, _ = _build_binary_sensor_device(+ 'kitchen_smoke', device_class = 'smoke',+ )+ entity = HassConverter.create_models_for_hass_device(+ hass_device = device, add_alarm_events = False,+ )+ self.assertEqual( entity.entity_type, EntityType.SMOKE_DETECTOR )++ def test_smoke_creates_alarm_event_definition(self):+ # Smoke is safety-critical and warrants its own alarm rule —+ # mirrors the door/window OPEN_CLOSE and motion MOVEMENT+ # branches that wire ``create_*_event_definition`` when+ # ``add_alarm_events=True``.+ device, _ = _build_binary_sensor_device(+ 'kitchen_smoke', device_class = 'smoke',+ )+ HassConverter.create_models_for_hass_device(+ hass_device = device, add_alarm_events = True,+ )+ hass_event_defs = EventDefinition.objects.filter(+ integration_id = HassMetaData.integration_id,+ )+ self.assertEqual( hass_event_defs.count(), 1 )+++class TestDoorWindowBinarySensor(TestCase):+ """Door and window were covered before #300 via the OPEN_CLOSE+ branch, but the binary-sensor work added explicit non-Insteon+ fixtures that make these mappings load-bearing for HA-only+ setups. Test the value-emission contract directly."""++ def test_door_on_emits_open(self):+ _, hass_state = _build_binary_sensor_device(+ 'front_door', device_class = 'door', state = 'on',+ )+ self.assertEqual(+ _value_for( hass_state ), str( EntityStateValue.OPEN ),+ )++ def test_door_off_emits_closed(self):+ _, hass_state = _build_binary_sensor_device(+ 'front_door', device_class = 'door', state = 'off',+ )+ self.assertEqual(+ _value_for( hass_state ), str( EntityStateValue.CLOSED ),+ )++ def test_window_on_emits_open(self):+ _, hass_state = _build_binary_sensor_device(+ 'living_window', device_class = 'window', state = 'on',+ )+ self.assertEqual(+ _value_for( hass_state ), str( EntityStateValue.OPEN ),+ )+++class TestGenericBinarySensorFallthrough(TestCase):+ """Generic ``binary_sensor.x`` states (no device_class) fall+ through to ``EntityStateType.ON_OFF``. Adding the smoke+ mapping mustn't accidentally regress this catch-all path."""++ def test_no_device_class_emits_on(self):+ _, hass_state = _build_binary_sensor_device(+ 'unknown_thing', device_class = None, state = 'on',+ )+ self.assertEqual(+ _value_for( hass_state ), str( EntityStateValue.ON ),+ )++ def test_no_device_class_emits_off(self):+ _, hass_state = _build_binary_sensor_device(+ 'unknown_thing', device_class = None, state = 'off',+ )+ self.assertEqual(+ _value_for( hass_state ), str( EntityStateValue.OFF ),+ )diff --git a/src/hi/simulator/enums.py b/src/hi/simulator/enums.pyindex 22b2d510..0bef86ff 100644--- a/src/hi/simulator/enums.py+++ b/src/hi/simulator/enums.py@@ -113,9 +113,10 @@ class SimEntityType(LabeledEnum):OTHER = ( 'Other', '' ) # Will use generic visual elementPRESENCE_SENSOR = ( 'Presence Sensor', '' )SEWER_LINE = ( 'Sewer Wire', '' )- SHOWER = ( 'Shower', '' )- SINK = ( 'Sink', '' )+ SHOWER = ( 'Shower', '' )+ SINK = ( 'Sink', '' )SERVICE = ( 'Service' , '' )+ SMOKE_DETECTOR = ( 'Smoke Detector', '' )SPEAKER = ( 'Speaker', '' )SPINKLER_CONTROLLER = ( 'Spinkler Controller', '' )SPINKLER_VALVE = ( 'Spinkler Valve', '' ) # Controls sprinkler headsdiff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex 8bfa89cf..8d4b10ab 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -79,6 +79,7 @@ from hi.simulator.services.hass.sim_models import (HassGarageCoverFields,HassGenericCoverFields,HassInsteonDimmerLightSwitchFields,+ HassDoorContactSensorFields,HassInsteonDualBandLightSwitchFields,HassInsteonLightSwitchFields,HassInsteonMotionDetectorFields,@@ -87,8 +88,10 @@ from hi.simulator.services.hass.sim_models import (HassLockFields,HassMultiFeatureFanFields,HassSmartBulbFields,+ HassSmokeDetectorFields,HassThermostatFields,HassWindowBlindCoverFields,+ HassWindowContactSensorFields,)from hi.simulator.services.homebox.attachment_catalog import AttachmentTemplatefrom hi.simulator.services.homebox.sim_models import (@@ -352,6 +355,9 @@ class Command(BaseCommand):self._add_hass_outlet( profile, 'Zoo Outlet' , '01.BB.06' )self._add_hass_smart_bulb( profile, 'Zoo Smart Bulb' )self._add_hass_color_smart_bulb( profile, 'Zoo Color Bulb' )+ self._add_hass_door_contact( profile, 'Zoo Door Contact' )+ self._add_hass_window_contact( profile, 'Zoo Window Contact' )+ self._add_hass_smoke_detector( profile, 'Zoo Smoke Detector' )self._add_hass_lock( profile, 'Zoo Lock' )self._add_hass_garage_cover( profile, 'Zoo Garage' )self._add_hass_window_blind_cover( profile, 'Zoo Blind' )@@ -496,6 +502,33 @@ class Command(BaseCommand):fields_kwargs = {'name': name},)+ def _add_hass_door_contact(self, profile, name):+ self._create_db_entity(+ profile = profile,+ simulator_id = 'hass',+ fields_class = HassDoorContactSensorFields,+ sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,+ fields_kwargs = {'name': name},+ )++ def _add_hass_window_contact(self, profile, name):+ self._create_db_entity(+ profile = profile,+ simulator_id = 'hass',+ fields_class = HassWindowContactSensorFields,+ sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,+ fields_kwargs = {'name': name},+ )++ def _add_hass_smoke_detector(self, profile, name):+ self._create_db_entity(+ profile = profile,+ simulator_id = 'hass',+ fields_class = HassSmokeDetectorFields,+ sim_entity_type = SimEntityType.SMOKE_DETECTOR,+ fields_kwargs = {'name': name},+ )+def _add_hass_lock(self, profile, name):self._create_db_entity(profile = profile,diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.pyindex 050a10b9..4fa89c57 100644--- a/src/hi/simulator/services/hass/sim_models.py+++ b/src/hi/simulator/services/hass/sim_models.py@@ -694,6 +694,135 @@ class HassColorSmartBulbColorModeState( HassState ):return {}+# --------------------------------------------------------------------------+# Binary sensors (non-Insteon, explicit device_class)+# --------------------------------------------------------------------------+#+# Door / window contact sensors and smoke detectors are+# ``binary_sensor.x`` entities differentiated by their+# ``device_class`` attribute. Per HA convention the alarm state+# is ``'on'`` (door/window open, smoke detected); ``'off'`` is+# the normal state. The three classes are structurally similar+# but kept parallel because the underlying SimStateType differs+# (OPEN_CLOSE for door/window, ON_OFF for smoke) which drives a+# different simulator-side UI control.+++def _binary_sensor_entity_id( name : str ) -> str:+ suffix = name.lower().replace( ' ', '_' )+ return f'binary_sensor.{suffix}'+++@dataclass( frozen = True )+class HassDoorContactSensorFields( SimEntityFields ):+ """A door contact sensor (``binary_sensor`` with+ ``device_class=door``). Single OPEN_CLOSE SimState whose+ value drives HA's ``state`` (``'on'`` = open, ``'off'`` =+ closed, per HA convention)."""+ pass+++@dataclass+class HassDoorContactSensorState( HassState ):+ sim_entity_fields : HassDoorContactSensorFields+ sim_state_type : SimStateType = SimStateType.OPEN_CLOSE+ sim_state_id : str = 'contact'+ value : str = 'off'++ @property+ def name(self):+ return f'{self.entity_name} Contact'++ @property+ def entity_id(self):+ return _binary_sensor_entity_id( self.entity_name )++ @property+ def state(self):+ return 'on' if str_to_bool( self.value ) else 'off'++ @property+ def attributes(self) -> Dict[ str, str ]:+ return {+ 'device_class': 'door',+ 'friendly_name': self.entity_name,+ 'icon': 'mdi:door',+ }+++@dataclass( frozen = True )+class HassWindowContactSensorFields( SimEntityFields ):+ """A window contact sensor (``binary_sensor`` with+ ``device_class=window``). Wire shape mirrors the door variant+ aside from the device_class string."""+ pass+++@dataclass+class HassWindowContactSensorState( HassState ):+ sim_entity_fields : HassWindowContactSensorFields+ sim_state_type : SimStateType = SimStateType.OPEN_CLOSE+ sim_state_id : str = 'contact'+ value : str = 'off'++ @property+ def name(self):+ return f'{self.entity_name} Contact'++ @property+ def entity_id(self):+ return _binary_sensor_entity_id( self.entity_name )++ @property+ def state(self):+ return 'on' if str_to_bool( self.value ) else 'off'++ @property+ def attributes(self) -> Dict[ str, str ]:+ return {+ 'device_class': 'window',+ 'friendly_name': self.entity_name,+ 'icon': 'mdi:window-closed-variant',+ }+++@dataclass( frozen = True )+class HassSmokeDetectorFields( SimEntityFields ):+ """A smoke detector (``binary_sensor`` with+ ``device_class=smoke``). Single ON_OFF SimState — ``'on'``+ means smoke detected (alarm), ``'off'`` is clear, per HA+ convention."""+ pass+++@dataclass+class HassSmokeDetectorState( HassState ):+ sim_entity_fields : HassSmokeDetectorFields+ sim_state_type : SimStateType = SimStateType.ON_OFF+ sim_state_id : str = 'smoke'+ value : str = 'off'++ @property+ def name(self):+ return f'{self.entity_name} Smoke'++ @property+ def entity_id(self):+ return _binary_sensor_entity_id( self.entity_name )++ @property+ def state(self):+ return 'on' if str_to_bool( self.value ) else 'off'++ @property+ def attributes(self) -> Dict[ str, str ]:+ return {+ 'device_class': 'smoke',+ 'friendly_name': self.entity_name,+ 'icon': 'mdi:smoke-detector',+ }++@dataclass( frozen = True )class HassLockFields( SimEntityFields ):"""A lock device. Single ON_OFF SimState whose value drives@@ -1625,6 +1754,30 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [HassColorSmartBulbColorModeState,],),+ SimEntityDefinition(+ class_label = 'Door Contact Sensor',+ sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,+ sim_entity_fields_class = HassDoorContactSensorFields,+ sim_state_class_list = [+ HassDoorContactSensorState,+ ],+ ),+ SimEntityDefinition(+ class_label = 'Window Contact Sensor',+ sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,+ sim_entity_fields_class = HassWindowContactSensorFields,+ sim_state_class_list = [+ HassWindowContactSensorState,+ ],+ ),+ SimEntityDefinition(+ class_label = 'Smoke Detector',+ sim_entity_type = SimEntityType.SMOKE_DETECTOR,+ sim_entity_fields_class = HassSmokeDetectorFields,+ sim_state_class_list = [+ HassSmokeDetectorState,+ ],+ ),SimEntityDefinition(class_label = 'Lock',sim_entity_type = SimEntityType.DOOR_LOCK,diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex d7fd5b6c..fa458ebe 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -766,6 +766,9 @@ g[status="high"] {g[status="low"] {filter: drop-shadow(0 0 5px var(--status-bad-color));}+g[status="smoke_detected"] {+ filter: drop-shadow(0 0 5px var(--status-bad-color));+}div[status] {