Skip to content

Home Information - Your home, your data, organized.

Python

Implement view-dependent one-click control for LocationViews (#180)

Tony Ce6aea9d5f5c7
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md
index cfac1d6c..201537c2 100644
--- a/docs/CLAUDE.md
+++ b/docs/CLAUDE.md
@@ -2,6 +2,10 @@
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+## Development Context - Our Prime Directive
+
+In all the code we write, we strive for extremely well factored code. We are thoughtful about responsibility boundaries, encapsulation, readability and maintainability. We do not write the first code we can think of to solve the problem or meet the requirements: we find a well factored version that does the job.
+
## Quick Reference - Common Process Checkpoints
**Before Starting Development:**
diff --git a/src/hi/apps/common/svg_models.py b/src/hi/apps/common/svg_models.py
index 5da2374a..e2f7dd72 100644
--- a/src/hi/apps/common/svg_models.py
+++ b/src/hi/apps/common/svg_models.py
@@ -212,7 +212,7 @@ class SvgStatusStyle:
stroke_dasharray : List[ int ]
fill_color : str
fill_opacity : float
-
+
def to_dict(self):
result = {
'status': self.status_value,
diff --git a/src/hi/apps/control/controller_manager.py b/src/hi/apps/control/controller_manager.py
index 7cca52f2..f9132f37 100644
--- a/src/hi/apps/control/controller_manager.py
+++ b/src/hi/apps/control/controller_manager.py
@@ -4,9 +4,10 @@ import logging
from hi.apps.common.singleton import Singleton
from hi.integrations.integration_manager import IntegrationManager
-from hi.integrations.transient_models import IntegrationControlResult
+from .controller_history_manager import ControllerHistoryManager
from .models import Controller
+from .transient_models import ControllerOutcome
logger = logging.getLogger(__name__)
@@ -26,7 +27,7 @@ class ControllerManager( Singleton ):
def do_control( self,
controller : Controller,
- control_value : str ) -> IntegrationControlResult:
+ control_value : str ) -> ControllerOutcome:
logger.debug( f'Controller action: {controller} = {control_value}' )
integration_gateway = IntegrationManager().get_integration_gateway(
@@ -38,11 +39,21 @@ class ControllerManager( Singleton ):
integration_details = controller.get_integration_details(),
control_value = control_value,
)
- return control_result
+ if not control_result.has_errors:
+ ControllerHistoryManager().add_to_controller_history(
+ controller = controller,
+ value = control_result.new_value,
+ )
+
+ return ControllerOutcome(
+ controller = controller,
+ new_value = control_result.new_value,
+ error_list = control_result.error_list,
+ )
async def do_control_async( self,
controller : Controller,
- control_value : str ) -> IntegrationControlResult:
+ control_value : str ) -> ControllerOutcome:
return await sync_to_async( self.do_control )(
controller = controller,
control_value = control_value,
diff --git a/src/hi/apps/control/enums.py b/src/hi/apps/control/enums.py
index 1d877706..d04fcdd7 100644
--- a/src/hi/apps/control/enums.py
+++ b/src/hi/apps/control/enums.py
@@ -1,6 +1,32 @@
+from typing import List
+
from hi.apps.common.enums import LabeledEnum
+from hi.apps.entity.enums import EntityStateType
class ControllerType(LabeledEnum):
DEFAULT = ( 'Default', '' ) # EntityState will define behavior
+
+
+class OneClickContextType(LabeledEnum):
+
+ DEFAULT = (
+ 'Default',
+ '',
+ [
+ EntityStateType.ON_OFF,
+ EntityStateType.LIGHT_DIMMER,
+ EntityStateType.OPEN_CLOSE,
+ EntityStateType.HIGH_LOW,
+ ],
+ )
+
+ def __init__( self,
+ label : str,
+ description : str,
+ priority_list : List[ EntityStateType ] ):
+ super().__init__( label, description )
+ self.priority_list = priority_list
+ return
+
diff --git a/src/hi/apps/control/one_click_control_service.py b/src/hi/apps/control/one_click_control_service.py
new file mode 100644
index 00000000..3948ae54
--- /dev/null
+++ b/src/hi/apps/control/one_click_control_service.py
@@ -0,0 +1,135 @@
+import logging
+from typing import Optional
+
+from hi.apps.control.controller_manager import ControllerManager
+from hi.apps.control.models import Controller
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.location.enums import LocationViewType
+from hi.apps.monitor.status_display_manager import StatusDisplayManager
+
+from .transient_models import ControllerOutcome
+
+logger = logging.getLogger(__name__)
+
+
+class OneClickNotSupported(Exception):
+ """Raised when EntityStateType doesn't support one-click control."""
+ pass
+
+
+class OneClickError(Exception):
+ """Raised when EntityStateType has erro being set."""
+ pass
+
+
+class OneClickControlService:
+ """
+ Service responsible for complete one-click control flow:
+ - Priority resolution and controller selection
+ - Current state detection for proper toggle behavior
+ - Control execution and outcome reporting
+ """
+
+ # Although we can cycle through a value enumeration of any length to
+ # have a one-click behavior. This is not going to be useful past a
+ # certain point, so we best limit one-click behavior to simpler
+ # controllers.
+ #
+ ONE_CLICK_CHOICE_LIMIT = 3
+
+ def execute_one_click_control(
+ self,
+ entity : Entity,
+ location_view_type : LocationViewType = None ) -> ControllerOutcome:
+ """
+ Execute complete one-click control flow: decision, state detection, execution.
+ Convenience wrapper around ControllerManager.do_control().
+ Raises OneClickNotSupported if control cannot be attempted.
+ """
+ controller = self._find_controller(
+ entity = entity,
+ location_view_type = location_view_type,
+ )
+ current_value = self._get_current_state_value(
+ entity_state = controller.entity_state,
+ )
+ target_value = self._determine_control_value(
+ entity_state = controller.entity_state,
+ current_value = current_value,
+ )
+ logger.debug( f'Calling control: {entity} : {current_value} -> {target_value}' )
+
+ return ControllerManager().do_control(
+ controller = controller,
+ control_value = target_value,
+ )
+
+ def _find_controller( self,
+ entity : Entity,
+ location_view_type : LocationViewType = None ) -> Controller:
+ """Find highest priority EntityState that has controllers and is supported.
+
+ We only want one-click controls to apply the entity state being
+ used in the display status. Thus, we make sure we use the same
+ logic to pick the entity state, then see if it has a controller.
+ """
+
+ if not location_view_type:
+ location_view_type = LocationViewType.default()
+ priority_list = location_view_type.entity_state_type_priority_list
+
+ entity_state_list = StatusDisplayManager().get_entity_state_list_for_status(
+ entity = entity,
+ entity_state_type_priority_list = priority_list,
+ )
+
+ for entity_state in entity_state_list:
+ if entity_state.entity_state_type:
+ controller = entity_state.controllers.first()
+ if controller:
+ return controller
+ continue
+
+ raise OneClickNotSupported(f'No priority states found for {entity}')
+
+ def _get_current_state_value( self, entity_state: EntityState ) -> Optional[str]:
+ try:
+ sensor_response = StatusDisplayManager().get_latest_sensor_response(
+ entity_state = entity_state,
+ )
+ if sensor_response:
+ logger.debug( f'Latest response: {entity_state}'
+ f' = {sensor_response.value}' )
+ current_state_value = sensor_response.value
+
+ # Normalize the value in case non-discrete and toggle-able (e.g., dimmers)
+ return entity_state.to_toggle_value(
+ actual_value = current_state_value,
+ )
+ logger.debug( f'No latest response for: {entity_state}' )
+ except Exception as e:
+ logger.warning( f'Problem getting latest response for: {entity_state} - {e}' )
+ pass
+ return None
+
+ def _determine_control_value( self,
+ entity_state : EntityState,
+ current_value : Optional[str] ) -> str:
+ toggle_state_value_list = entity_state.toggle_values()
+ logger.debug( f' Next for {current_value} : {toggle_state_value_list}' )
+ if not toggle_state_value_list:
+ raise OneClickNotSupported(f'No toggle value list found for {entity_state}')
+
+ if len(toggle_state_value_list) > self.ONE_CLICK_CHOICE_LIMIT:
+ raise OneClickNotSupported(f'Too many values to toggle for {entity_state}')
+
+ for idx, toggle_state_value in enumerate( toggle_state_value_list ):
+ if toggle_state_value != current_value:
+ continue
+
+ next_idx = idx + 1
+ if next_idx < len(toggle_state_value_list):
+ return toggle_state_value_list[next_idx]
+ return toggle_state_value_list[0]
+
+ return toggle_state_value_list[0]
diff --git a/src/hi/apps/control/tests/test_controller_manager.py b/src/hi/apps/control/tests/test_controller_manager.py
index 4fa155a8..d7b8f349 100644
--- a/src/hi/apps/control/tests/test_controller_manager.py
+++ b/src/hi/apps/control/tests/test_controller_manager.py
@@ -3,7 +3,9 @@ from unittest.mock import Mock, patch
import asyncio
from hi.apps.control.controller_manager import ControllerManager
+from hi.apps.control.controller_history_manager import ControllerHistoryManager
from hi.apps.control.models import Controller
+from hi.apps.control.transient_models import ControllerOutcome
from hi.apps.entity.models import Entity, EntityState
from hi.integrations.transient_models import IntegrationControlResult
from hi.testing.base_test_case import BaseTestCase
@@ -80,7 +82,7 @@ class TestControllerManager(BaseTestCase):
result = manager.do_control(controller=controller, control_value='on')
# Test actual return value and behavior
- self.assertIsInstance(result, IntegrationControlResult)
+ self.assertIsInstance(result, ControllerOutcome)
self.assertFalse(result.has_errors)
self.assertEqual(result.new_value, 'on')
self.assertEqual(result.error_list, [])
@@ -134,15 +136,17 @@ class TestControllerManager(BaseTestCase):
result = manager.do_control(controller=controller, control_value='on')
# Test that error information is properly returned
- self.assertIsInstance(result, IntegrationControlResult)
+ self.assertIsInstance(result, ControllerOutcome)
self.assertTrue(result.has_errors)
self.assertEqual(result.error_list, ['Device is offline', 'Connection timeout'])
self.assertEqual(result.new_value, '')
return
@patch.object(ControllerManager, '_instance', None)
+ @patch.object(ControllerHistoryManager, '_instance', None)
+ @patch('hi.apps.control.controller_history_manager.ControllerHistory.objects.create')
@patch('hi.apps.control.controller_manager.IntegrationManager')
- def test_do_control_async_returns_same_result_as_sync(self, mock_integration_manager_class):
+ def test_do_control_async_returns_same_result_as_sync(self, mock_integration_manager_class, mock_history_create):
"""Test async control returns identical result to sync version."""
entity = Entity.objects.create(
name='Test Dimmer',
@@ -153,14 +157,22 @@ class TestControllerManager(BaseTestCase):
entity_state_type_str='DISCRETE'
)
- controller = Controller.objects.create(
- name='Bedroom Dimmer',
+ controller_sync = Controller.objects.create(
+ name='Bedroom Dimmer Sync',
entity_state=entity_state,
controller_type_str='DEFAULT',
integration_id='zigbee_integration',
integration_name='Zigbee Integration'
)
+ controller_async = Controller.objects.create(
+ name='Bedroom Dimmer Async',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='zigbee_integration',
+ integration_name='Zigbee Integration Async'
+ )
+
# Mock successful dimmer control
mock_control_result = IntegrationControlResult(
new_value='75',
@@ -178,10 +190,10 @@ class TestControllerManager(BaseTestCase):
# Test both sync and async produce same result
manager = ControllerManager()
- sync_result = manager.do_control(controller=controller, control_value='75')
+ sync_result = manager.do_control(controller=controller_sync, control_value='75')
async def run_async_test():
- return await manager.do_control_async(controller=controller, control_value='75')
+ return await manager.do_control_async(controller=controller_async, control_value='75')
async_result = asyncio.run(run_async_test())
diff --git a/src/hi/apps/control/tests/test_views.py b/src/hi/apps/control/tests/test_views.py
index e22942ba..7abc380a 100644
--- a/src/hi/apps/control/tests/test_views.py
+++ b/src/hi/apps/control/tests/test_views.py
@@ -22,6 +22,10 @@ class TestControllerView(SyncViewTestCase):
def setUp(self):
super().setUp()
+ # Reset singleton managers for proper test isolation
+ ControllerManager._instance = None
+ ControllerHistoryManager._instance = None
+ StatusDisplayManager._instance = None
# Create test entity and controller
self.entity = Entity.objects.create(
name='Test Light',
@@ -35,30 +39,31 @@ class TestControllerView(SyncViewTestCase):
self.controller = Controller.objects.create(
entity_state=self.entity_state,
controller_type_str='SWITCH',
+ integration_id='test_integration',
+ integration_name='test_switch',
integration_payload='{"device_id": "test_device"}'
)
- @patch.object(ControllerManager, 'do_control')
- @patch.object(StatusDisplayManager, 'add_entity_state_value_override')
- @patch.object(ControllerHistoryManager, 'add_to_controller_history')
- def test_post_control_success(self, mock_add_history, mock_add_override, mock_do_control):
+ @patch('hi.apps.control.controller_manager.IntegrationManager')
+ def test_post_control_success(self, mock_integration_manager):
"""Test successful controller action."""
- mock_result = Mock()
- mock_result.has_errors = False
- mock_result.error_list = []
- mock_do_control.return_value = mock_result
+ from hi.integrations.transient_models import IntegrationControlResult
+
+ # Mock at the system boundary - the integration gateway
+ mock_manager = Mock()
+ mock_integration_manager.return_value = mock_manager
+ mock_gateway = Mock()
+ mock_manager.get_integration_gateway.return_value = mock_gateway
+ mock_gateway.get_controller.return_value.do_control.return_value = IntegrationControlResult(
+ new_value='ON',
+ error_list=[]
+ )
url = reverse('control_controller', kwargs={'controller_id': self.controller.id})
response = self.client.post(url, {'value': 'ON'})
+ # Should successfully execute control
self.assertSuccessResponse(response)
- mock_do_control.assert_called_once_with(
- controller=self.controller,
- control_value='ON'
- )
- # Should add override and history when successful
- mock_add_override.assert_called_once()
- mock_add_history.assert_called_once()
@patch.object(ControllerManager, 'do_control')
@patch.object(StatusDisplayManager, 'add_entity_state_value_override')
diff --git a/src/hi/apps/control/transient_models.py b/src/hi/apps/control/transient_models.py
index d83be166..5a846202 100644
--- a/src/hi/apps/control/transient_models.py
+++ b/src/hi/apps/control/transient_models.py
@@ -16,3 +16,14 @@ class ControllerData:
def css_class(self):
return self.controller.entity_state.css_class
+
+@dataclass
+class ControllerOutcome:
+ controller : Controller
+ new_value : str
+ error_list : List[ str ] = None
+
+ @property
+ def has_errors(self):
+ return bool( self.error_list )
+
diff --git a/src/hi/apps/control/views.py b/src/hi/apps/control/views.py
index 4249f8b2..a9571643 100644
--- a/src/hi/apps/control/views.py
+++ b/src/hi/apps/control/views.py
@@ -9,7 +9,6 @@ from hi.apps.monitor.status_display_manager import StatusDisplayManager
from hi.hi_async_view import HiModalView
-from .controller_history_manager import ControllerHistoryManager
from .control_mixins import ControllerMixin
from .models import Controller, ControllerHistory
from .view_mixins import ControlViewMixin
@@ -38,7 +37,7 @@ class ControllerView( View, ControlViewMixin, ControllerMixin ):
if control_value is None:
control_value = self._get_value_for_missing_input( controller = controller )
- control_result = self.controller_manager().do_control(
+ controller_outcome = self.controller_manager().do_control(
controller = controller,
control_value = control_value,
)
@@ -54,30 +53,26 @@ class ControllerView( View, ControlViewMixin, ControllerMixin ):
#
# 2) We temporarily override the value in the
# StatusDisplayManager. This is to guard against the UI/client
- # polling happening beforee the server has been able to update
+ # polling happening before the server has been able to update
# itrs values. This override is temporary and expires in a
# time just longer than the polling intervals' maximum gaps.
- if control_result.has_errors:
+ if controller_outcome.has_errors:
override_sensor_value = None
else:
override_sensor_value = control_value
StatusDisplayManager().add_entity_state_value_override(
entity_state = controller.entity_state,
- override_value = control_value,
- )
- ControllerHistoryManager().add_to_controller_history(
- controller = controller,
- value = control_value,
+ override_value = override_sensor_value,
)
response_context = request.POST.get('response_context', 'page')
- in_modal_context = bool(response_context == 'modal')
+ in_modal_context = bool( response_context == 'modal' )
return self.controller_data_response(
request = request,
controller = controller,
- error_list = control_result.error_list,
+ error_list = controller_outcome.error_list,
override_sensor_value = override_sensor_value,
in_modal_context = in_modal_context,
)
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index dc311a81..3abc0a9d 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -1,4 +1,4 @@
-from typing import Set
+from typing import List, Set, Tuple
from hi.apps.common.enums import LabeledEnum
@@ -148,13 +148,35 @@ class EntityType(LabeledEnum):
return self in self.get_open_path_types()
+class EntityStateValue(LabeledEnum):
+
+ ACTIVE = ( 'Active', '' )
+ IDLE = ( 'Idle', '' )
+
+ ON = ( 'On', '' )
+ OFF = ( 'Off', '' )
+
+ OPEN = ( 'Open', '' )
+ CLOSED = ( 'Closed', '' )
+
+ CONNECTED = ( 'Connected', '' )
+ DISCONNECTED = ( 'Disconnected', '' )
+
+ HIGH = ( 'High', '' )
+ LOW = ( 'Low', '' )
+
+
class EntityStateType(LabeledEnum):
# General types
- DISCRETE = ( 'Discrete' , 'Single value, fixed set of possible values' )
- CONTINUOUS = ( 'Continuous' , 'For single value with a float type value' )
- MULTVALUED = ( 'Multi-valued' , 'Provides multiple name-value pairs' )
- BLOB = ( 'Blob' , 'Provides blob of uninterpreted data' )
+ DISCRETE = ( 'Discrete' , 'Single value, fixed set of possible values',
+ [] )
+ CONTINUOUS = ( 'Continuous' , 'For single value with a float type value',
+ [] )
+ MULTIVALUED = ( 'Multi-valued' , 'Provides multiple name-value pairs',
+ [] )
+ BLOB = ( 'Blob' , 'Provides blob of uninterpreted data',
+ [] )
# Specific types
#
@@ -162,25 +184,63 @@ class EntityStateType(LabeledEnum):
# name-value pairs. However, by being more specific, we can provide
# more specific visual and processing for the sensors/controllers.
- AIR_PRESSURE = ( 'Air Pressure' , '' )
- BANDWIDTH_USAGE = ( 'Bandwidth Usage' , '' )
- CONNECTIVITY = ( 'Connectivity' , '' )
- DATETIME = ( 'Date/Time' , '' )
- ELECTRIC_USAGE = ( 'Electric Usage' , '' )
- HIGH_LOW = ( 'High/Low' , '' )
- HUMIDITY = ( 'Humidity' , '' )
- LIGHT_DIMMER = ( 'Light Dimmer' , 'Controllable light brightness (0-100%)' )
- LIGHT_LEVEL = ( 'Light Level' , '' )
- MOISTURE = ( 'Moisture' , '' )
- MOVEMENT = ( 'Movement' , '' )
- ON_OFF = ( 'On/Off' , '' )
- OPEN_CLOSE = ( 'Open/Close' , '' )
- PRESENCE = ( 'Presence' , '' )
- SOUND_LEVEL = ( 'Sound Level' , '' )
- TEMPERATURE = ( 'Temperature' , '' )
- WATER_FLOW = ( 'Water Flow' , '' )
- WIND_SPEED = ( 'Wind Speed' , '' )
+ AIR_PRESSURE = ( 'Air Pressure' , '',
+ [] )
+ BANDWIDTH_USAGE = ( 'Bandwidth Usage' , '',
+ [] )
+ CONNECTIVITY = ( 'Connectivity' , '',
+ [ EntityStateValue.CONNECTED,
+ EntityStateValue.DISCONNECTED ] )
+ DATETIME = ( 'Date/Time' , '',
+ [] )
+ ELECTRIC_USAGE = ( 'Electric Usage' , '',
+ [] )
+ HIGH_LOW = ( 'High/Low' , '',
+ [ EntityStateValue.HIGH,
+ EntityStateValue.LOW ] )
+ HUMIDITY = ( 'Humidity' , '',
+ [] )
+ LIGHT_DIMMER = ( 'Light Dimmer' , 'Controllable light brightness (0-100)',
+ [] )
+ LIGHT_LEVEL = ( 'Light Level' , '',
+ [] )
+ MOISTURE = ( 'Moisture' , '',
+ [] )
+ MOVEMENT = ( 'Movement' , '',
+ [ EntityStateValue.ACTIVE,
+ EntityStateValue.IDLE ] )
+ ON_OFF = ( 'On/Off' , '',
+ [ EntityStateValue.ON,
+ EntityStateValue.OFF ] )
+ OPEN_CLOSE = ( 'Open/Close' , '',
+ [ EntityStateValue.OPEN,
+ EntityStateValue.CLOSED ] )
+ PRESENCE = ( 'Presence' , '',
+ [ EntityStateValue.ACTIVE,
+ EntityStateValue.IDLE ] )
+ SOUND_LEVEL = ( 'Sound Level' , '',
+ [] )
+ TEMPERATURE = ( 'Temperature' , '',
+ [] )
+ WATER_FLOW = ( 'Water Flow' , '',
+ [] )
+ WIND_SPEED = ( 'Wind Speed' , '',
+ [] )
+
+ def __init__( self,
+ label : str,
+ description : str,
+ entity_state_value_list : List[ EntityStateValue ] ):
+ super().__init__( label, description )
+ self.entity_state_value_list = entity_state_value_list
+ return
+ def choices(self) -> List[ Tuple[str, str] ]:
+ return [ ( str(x), x.label ) for x in self.entity_state_value_list ]
+
+ def toggle_values(self) -> List[str]:
+ return [ str(x) for x in self.entity_state_value_list ]
+
def value_template_name(self):
"""
Template used to render a sensor's value for this state. Create the
@@ -198,45 +258,7 @@ class EntityStateType(LabeledEnum):
"entity/panes/controller_value_default.html"
"""
return f'control/panes/controller_{self.name.lower()}.html'
-
-
-class EntityStateValue(LabeledEnum):
-
- ACTIVE = ( 'Active', '' )
- IDLE = ( 'Idle', '' )
-
- ON = ( 'On', '' )
- OFF = ( 'Off', '' )
- OPEN = ( 'Open', '' )
- CLOSED = ( 'Closed', '' )
-
- CONNECTED = ( 'Connected', '' )
- DISCONNECTED = ( 'Disconnected', '' )
-
- HIGH = ( 'High', '' )
- LOW = ( 'Low', '' )
-
- @classmethod
- def entity_state_value_choices(cls):
- return {
- EntityStateType.CONNECTIVITY: [ ( str(x), x.label )
- for x in [ EntityStateValue.CONNECTED,
- EntityStateValue.DISCONNECTED ]],
- EntityStateType.HIGH_LOW: [ ( str(x), x.label )
- for x in [ EntityStateValue.HIGH,
- EntityStateValue.LOW ]],
- EntityStateType.MOVEMENT: [ ( str(x), x.label )
- for x in [ EntityStateValue.ACTIVE,
- EntityStateValue.IDLE ]],
- EntityStateType.ON_OFF: [ ( str(x), x.label )
- for x in [ EntityStateValue.ON,
- EntityStateValue.OFF ]],
- EntityStateType.OPEN_CLOSE: [ ( str(x), x.label )
- for x in [ EntityStateValue.OPEN,
- EntityStateValue.CLOSED ]],
- }
-
class TemperatureUnit(LabeledEnum):
diff --git a/src/hi/apps/entity/migrations/0008_fix_multvalued_typo.py b/src/hi/apps/entity/migrations/0008_fix_multvalued_typo.py
new file mode 100644
index 00000000..7cd26853
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0008_fix_multvalued_typo.py
@@ -0,0 +1,33 @@
+# Generated by Django 4.2.24 on 2025-09-11 15:28
+
+from django.db import migrations
+
+
+def fix_multivalued_typo(apps, schema_editor):
+ """Fix typo: change 'multivalued' to 'multivalued' in entity_state_type_str"""
+ EntityState = apps.get_model('entity', 'EntityState')
+ EntityState.objects.filter(entity_state_type_str='multivalued').update(
+ entity_state_type_str='multivalued'
+ )
+
+
+def reverse_fix_multivalued_typo(apps, schema_editor):
+ """Reverse fix: change 'multivalued' back to 'multivalued'"""
+ EntityState = apps.get_model('entity', 'EntityState')
+ EntityState.objects.filter(entity_state_type_str='multivalued').update(
+ entity_state_type_str='multivalued'
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0007_video_stream_data_migration"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ fix_multivalued_typo,
+ reverse_fix_multivalued_typo,
+ ),
+ ]
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index c178a74a..9f720988 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -1,5 +1,5 @@
import json
-from typing import Dict
+from typing import Dict, List, Tuple
from django.db import models
@@ -17,7 +17,6 @@ from hi.enums import ItemType
from .enums import (
EntityType,
EntityStateType,
- EntityStateValue,
)
@@ -202,21 +201,58 @@ class EntityState( models.Model ):
self.value_range_str = json.dumps( value_dict )
return
- def choices(self):
+ def choices(self) -> List[ Tuple[str,str] ]:
if self.value_range_str:
try:
value_range = json.loads( self.value_range_str )
+ if (( len(value_range) == 2 )
+ and ( 'min' in value_range )
+ and ( 'max' in value_range )):
+ return list()
if isinstance( value_range, dict ):
- return [ ( k, v ) for k, v in value_range.items() ]
+ return [ ( str(k), str(v) ) for k, v in value_range.items() ]
if isinstance( value_range, list ):
- return [ ( x, x ) for x in value_range ]
+ return [ ( str(x), str(x) ) for x in value_range ]
except json.JSONDecodeError:
pass
+ return self.entity_state_type.choices()
- choices_map = EntityStateValue.entity_state_value_choices()
- return choices_map.get( self.entity_state_type, [] )
+ def toggle_values(self) -> List[str]:
+ if self.value_range_str:
+ try:
+ # Special case for min/max types to allow toggling extremes (e.g., dimmer switches)
+ value_range = json.loads( self.value_range_str )
+ if (( len(value_range) == 2 )
+ and ( 'min' in value_range )
+ and ( 'max' in value_range )):
+ return [ str(value_range['min']), str(value_range['max']) ]
+
+ if isinstance( value_range, dict ):
+ return [ str(k) for k, v in value_range.items() ]
+ if isinstance( value_range, list ):
+ return [ str(x) for x in value_range ]
+ except json.JSONDecodeError:
+ pass
+ return self.entity_state_type.toggle_values()
+ def to_toggle_value( self, actual_value : str ) -> str:
+ # Special case for min/max types to allow toggling extremes (e.g., dimmer switches)
+ if self.value_range_str:
+ try:
+ value_range = json.loads( self.value_range_str )
+ if (( len(value_range) == 2 )
+ and ( 'min' in value_range )
+ and ( 'max' in value_range )):
+ min_value = value_range['min']
+ max_value = value_range['max']
+ if actual_value and ( float(actual_value) > float(min_value) ):
+ return str(max_value)
+ return str(min_value)
+ except ( TypeError, ValueError, json.JSONDecodeError ):
+ pass
+ return actual_value
+
class EntityStateDelegation(models.Model):
"""An EntityState associated with a Sensor or Controller is often serving
representing the state of some other entity. In those cases, the entity
diff --git a/src/hi/apps/entity/tests/test_enums.py b/src/hi/apps/entity/tests/test_enums.py
index a838ad7a..44b57c35 100644
--- a/src/hi/apps/entity/tests/test_enums.py
+++ b/src/hi/apps/entity/tests/test_enums.py
@@ -3,7 +3,6 @@ import logging
from hi.apps.entity.enums import (
EntityType,
EntityStateType,
- EntityStateValue,
EntityGroupType,
)
from hi.testing.base_test_case import BaseTestCase
@@ -35,59 +34,9 @@ class TestEntityStateType(BaseTestCase):
self.assertNotEqual(temperature_template, controller_template)
# Complex state types should work correctly
- multivalued_template = EntityStateType.MULTVALUED.value_template_name()
+ multivalued_template = EntityStateType.MULTIVALUED.value_template_name()
self.assertTrue(multivalued_template.startswith('sense/panes/sensor_value_'))
- self.assertIn('multvalued', multivalued_template)
-
- return
-
-
-class TestEntityStateValue(BaseTestCase):
-
- def test_entity_state_value_choices_provide_ui_options(self):
- """Test state value choices mapping - provides UI with appropriate options for each state type."""
- choices = EntityStateValue.entity_state_value_choices()
-
- # Verify that different state types have appropriate choice sets
- self.assertIn(EntityStateType.ON_OFF, choices)
- self.assertIn(EntityStateType.CONNECTIVITY, choices)
- self.assertIn(EntityStateType.MOVEMENT, choices)
- self.assertIn(EntityStateType.OPEN_CLOSE, choices)
- self.assertIn(EntityStateType.HIGH_LOW, choices)
-
- # Test ON_OFF state provides binary choices
- on_off_choices = choices[EntityStateType.ON_OFF]
- self.assertEqual(len(on_off_choices), 2)
-
- # Choices should be tuples of (value, label)
- choice_values = [choice[0] for choice in on_off_choices]
- choice_labels = [choice[1] for choice in on_off_choices]
-
- # Should include both on and off options
- self.assertIn('on', choice_values)
- self.assertIn('off', choice_values)
-
- # Labels should be user-friendly
- self.assertIn('On', choice_labels)
- self.assertIn('Off', choice_labels)
-
- # Test connectivity state has appropriate network-related choices
- connectivity_choices = choices[EntityStateType.CONNECTIVITY]
- connectivity_values = [choice[0] for choice in connectivity_choices]
- self.assertIn('connected', connectivity_values)
- self.assertIn('disconnected', connectivity_values)
-
- # Test movement state has activity-related choices
- movement_choices = choices[EntityStateType.MOVEMENT]
- movement_values = [choice[0] for choice in movement_choices]
- self.assertIn('active', movement_values)
- self.assertIn('idle', movement_values)
-
- # Test open/close state has position-related choices
- open_close_choices = choices[EntityStateType.OPEN_CLOSE]
- open_close_values = [choice[0] for choice in open_close_choices]
- self.assertIn('open', open_close_values)
- self.assertIn('closed', open_close_values)
+ self.assertIn('multivalued', multivalued_template)
return
diff --git a/src/hi/apps/location/edit/forms.py b/src/hi/apps/location/edit/forms.py
index 3e25fd81..0d52a4b6 100644
--- a/src/hi/apps/location/edit/forms.py
+++ b/src/hi/apps/location/edit/forms.py
@@ -71,34 +71,20 @@ class LocationEditForm( forms.ModelForm ):
}
-class LocationViewAddForm(forms.Form):
+class LocationViewAddForm( forms.ModelForm ):
# N.B. When adding a LocationView, we use limited field options to keep
# it simpler.
- name = forms.CharField(
- label = 'View Name',
- required = True,
- )
-
-
-class LocationViewEditForm( forms.ModelForm ):
-
class Meta:
model = LocationView
fields = (
'name',
'location_view_type_str',
'svg_style_name_str',
- 'svg_view_box_str',
- 'svg_rotate',
- 'order_id',
)
widgets = {
'name': forms.TextInput( attrs={'class': 'form-control'} ),
- 'svg_view_box_str': forms.TextInput( attrs={'class': 'form-control'} ),
- 'svg_rotate': forms.NumberInput( attrs={'class': 'form-control'} ),
- 'order_id': forms.NumberInput( attrs={'class': 'form-control'} ),
}
location_view_type_str = forms.ChoiceField(
@@ -115,6 +101,22 @@ class LocationViewEditForm( forms.ModelForm ):
required = True,
widget = forms.Select( attrs = { 'class' : 'custom-select' } ),
)
+
+
+class LocationViewEditForm( LocationViewAddForm ):
+
+ class Meta( LocationViewAddForm.Meta ):
+ fields = LocationViewAddForm.Meta.fields + (
+ 'svg_view_box_str',
+ 'svg_rotate',
+ 'order_id',
+ )
+ widgets = {
+ **LocationViewAddForm.Meta.widgets,
+ 'svg_view_box_str': forms.TextInput( attrs={'class': 'form-control'} ),
+ 'svg_rotate': forms.NumberInput( attrs={'class': 'form-control'} ),
+ 'order_id': forms.NumberInput( attrs={'class': 'form-control'} ),
+ }
class LocationViewGeometryForm( forms.ModelForm ):
diff --git a/src/hi/apps/location/edit/tests/test_views.py b/src/hi/apps/location/edit/tests/test_views.py
index 141d054a..44fad58e 100644
--- a/src/hi/apps/location/edit/tests/test_views.py
+++ b/src/hi/apps/location/edit/tests/test_views.py
@@ -415,7 +415,9 @@ class TestLocationViewAddView(DualModeViewTestCase):
Location.objects.exclude(id=self.location.id).delete()
url = reverse('location_edit_location_view_add')
- response = self.client.post(url, {'name': 'New View'})
+ response = self.client.post(url, {'name': 'New View',
+ 'location_view_type_str': 'default',
+ 'svg_style_name_str': 'color' })
# Expect JSON response for antinode.js
self.assertEqual(response.status_code, 200)
diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.py
index 9e74c57c..084470b3 100644
--- a/src/hi/apps/location/edit/views.py
+++ b/src/hi/apps/location/edit/views.py
@@ -302,11 +302,13 @@ class LocationViewAddView( HiModalView ):
'location_view_add_form': location_view_add_form,
}
return self.modal_response( request, context )
-
try:
+ temp_location_view = location_view_add_form.save( commit = False )
location_view = LocationManager().create_location_view(
location = current_location,
- name = location_view_add_form.cleaned_data.get('name'),
+ name = temp_location_view.name,
+ location_view_type = temp_location_view.location_view_type,
+ svg_style_name = temp_location_view.svg_style_name,
)
except ValueError as e:
raise BadRequest( str(e) )
diff --git a/src/hi/apps/location/enums.py b/src/hi/apps/location/enums.py
index a3b93fa4..4ac36147 100644
--- a/src/hi/apps/location/enums.py
+++ b/src/hi/apps/location/enums.py
@@ -20,6 +20,8 @@ class LocationViewType(LabeledEnum):
[ EntityStateType.MOVEMENT,
EntityStateType.PRESENCE,
EntityStateType.OPEN_CLOSE,
+ EntityStateType.ON_OFF,
+ EntityStateType.LIGHT_DIMMER,
EntityStateType.LIGHT_LEVEL,
EntityStateType.SOUND_LEVEL,
EntityStateType.TEMPERATURE,
@@ -40,44 +42,26 @@ class LocationViewType(LabeledEnum):
[ EntityStateType.MOVEMENT,
EntityStateType.PRESENCE,
EntityStateType.OPEN_CLOSE,
+ EntityStateType.ON_OFF,
+ EntityStateType.LIGHT_DIMMER,
],
)
- LIGHTS = (
- 'Lights',
+ AUTOMATION = (
+ 'Automation',
'',
- [ EntityStateType.LIGHT_LEVEL,
- ],
- )
- SOUNDS = (
- 'Sounds',
- '',
- [ EntityStateType.SOUND_LEVEL,
- ],
- )
- CLIMATE = (
- 'Climate',
- '',
- [ EntityStateType.TEMPERATURE,
- EntityStateType.HIGH_LOW,
- EntityStateType.HUMIDITY,
- EntityStateType.MOISTURE,
- EntityStateType.WIND_SPEED,
- EntityStateType.AIR_PRESSURE,
- ],
- )
- ENERGY = (
- 'Energy',
- '',
- [ EntityStateType.ELECTRIC_USAGE,
- EntityStateType.WATER_FLOW,
+ [ EntityStateType.MOVEMENT,
+ EntityStateType.PRESENCE,
+ EntityStateType.OPEN_CLOSE,
+ EntityStateType.ON_OFF,
+ EntityStateType.LIGHT_DIMMER,
+ EntityStateType.LIGHT_LEVEL,
+ EntityStateType.CONNECTIVITY,
EntityStateType.HIGH_LOW,
+ EntityStateType.SOUND_LEVEL,
+ EntityStateType.DISCRETE,
+ EntityStateType.CONTINUOUS,
],
)
- SUPPRESS = (
- 'Suppress',
- '',
- [],
- )
class SvgItemType(LabeledEnum):
diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.py
index d165cef9..4adee6bd 100644
--- a/src/hi/apps/location/location_manager.py
+++ b/src/hi/apps/location/location_manager.py
@@ -10,7 +10,7 @@ from hi.apps.common.singleton import Singleton
from hi.apps.common.svg_models import SvgViewBox
from hi.apps.monitor.status_display_manager import StatusDisplayManager
-from .enums import LocationViewType
+from .enums import LocationViewType, SvgStyleName
from .location_view_data import LocationViewData
from .models import (
Location,
@@ -104,20 +104,29 @@ class LocationManager(Singleton):
os.makedirs( directory, exist_ok = True )
return
- def create_location_view( self,
- location : Location,
- name : str ) -> LocationView:
+ def create_location_view(
+ self,
+ location : Location,
+ name : str,
+ location_view_type : LocationViewType = None,
+ svg_style_name : SvgStyleName = None ) -> LocationView:
+ if location_view_type is None:
+ location_view_type = LocationViewType.default()
+ if svg_style_name is None:
+ svg_style_name = SvgStyleName.default()
+
last_location_view = location.views.order_by( '-order_id' ).first()
if last_location_view:
order_id = last_location_view.order_id + 1
else:
order_id = 0
-
+
return LocationView.objects.create(
location = location,
- location_view_type_str = str(LocationViewType.default()),
+ location_view_type_str = str(location_view_type),
name = name,
+ svg_style_name_str = str( svg_style_name ),
svg_view_box_str = str( location.svg_view_box ),
svg_rotate = Decimal( 0.0 ),
order_id = order_id,
diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_add_form.html b/src/hi/apps/location/templates/location/edit/panes/location_view_add_form.html
index f0579597..5429fe1d 100644
--- a/src/hi/apps/location/templates/location/edit/panes/location_view_add_form.html
+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_add_form.html
@@ -13,8 +13,31 @@
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<label for="{{ location_view_add_form.name.id_for_label }}"
- class="input-group-text">{{ location_view_add_form.name.label }}</label>
+ class="input-group-text">{{ location_view_add_form.name.label }}</label>
</div>
{{ location_view_add_form.name }}
<small class="form-error text-danger"> {{ location_view_add_form.name.errors }}</small>
</div>
+
+<div class=" hi-custom-select">
+ <div class="input-group mb-2 mr-sm-2">
+ <div class="input-group-prepend">
+ <label for="{{ location_view_add_form.location_view_type_str.id_for_label }}"
+ class="input-group-text">{{ location_view_add_form.location_view_type_str.label_tag }}</label>
+ </div>
+ {{ location_view_add_form.location_view_type_str }}
+ </div>
+ {{ location_view_add_form.location_view_type_str.errors }}
+</div>
+
+<div class="hi-custom-select">
+ <div class="input-group mb-2 mr-sm-2">
+ <div class="input-group-prepend">
+ <div for="{{ location_view_add_form.svg_style_name_str.id_for_label }}"
+ class="input-group-text">{{ location_view_add_form.svg_style_name_str.label_tag }}</div>
+ </div>
+ {{ location_view_add_form.svg_style_name_str }}
+ </div>
+ {{ location_view_add_form.svg_style_name_str.errors }}
+</div>
+
diff --git a/src/hi/apps/location/tests/test_enums.py b/src/hi/apps/location/tests/test_enums.py
index 947f9eec..3b178b4a 100644
--- a/src/hi/apps/location/tests/test_enums.py
+++ b/src/hi/apps/location/tests/test_enums.py
@@ -1,109 +1,11 @@
import logging
-from hi.apps.location.enums import LocationViewType, SvgItemType, SvgStyleName
-from hi.apps.entity.enums import EntityStateType
+from hi.apps.location.enums import LocationViewType, SvgStyleName
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
-class TestLocationViewType(BaseTestCase):
-
- def test_location_view_type_entity_state_priority_lists(self):
- """Test entity state type priority lists - critical for sensor display ordering."""
- # DEFAULT should have comprehensive list
- default_priorities = LocationViewType.DEFAULT.entity_state_type_priority_list
- self.assertGreater(len(default_priorities), 5)
- self.assertIn(EntityStateType.MOVEMENT, default_priorities)
- self.assertIn(EntityStateType.TEMPERATURE, default_priorities)
-
- # SECURITY should focus on security-related states
- security_priorities = LocationViewType.SECURITY.entity_state_type_priority_list
- self.assertIn(EntityStateType.MOVEMENT, security_priorities)
- self.assertIn(EntityStateType.PRESENCE, security_priorities)
- self.assertIn(EntityStateType.OPEN_CLOSE, security_priorities)
-
- # CLIMATE should focus on climate-related states
- climate_priorities = LocationViewType.CLIMATE.entity_state_type_priority_list
- self.assertIn(EntityStateType.TEMPERATURE, climate_priorities)
- self.assertIn(EntityStateType.HUMIDITY, climate_priorities)
- self.assertIn(EntityStateType.AIR_PRESSURE, climate_priorities)
-
- # SUPPRESS should have empty list
- suppress_priorities = LocationViewType.SUPPRESS.entity_state_type_priority_list
- self.assertEqual(len(suppress_priorities), 0)
- return
-
- def test_location_view_type_specialization_logic(self):
- """Test view type specialization - business logic for filtering sensor types."""
- # Each view type should have unique focus
- view_types = [
- (LocationViewType.SECURITY, [EntityStateType.MOVEMENT, EntityStateType.PRESENCE]),
- (LocationViewType.LIGHTS, [EntityStateType.LIGHT_LEVEL]),
- (LocationViewType.SOUNDS, [EntityStateType.SOUND_LEVEL]),
- (LocationViewType.ENERGY, [EntityStateType.ELECTRIC_USAGE, EntityStateType.WATER_FLOW]),
- ]
-
- for view_type, expected_states in view_types:
- with self.subTest(view_type=view_type):
- priorities = view_type.entity_state_type_priority_list
- for expected_state in expected_states:
- self.assertIn(expected_state, priorities)
- return
-
- def test_location_view_type_labels(self):
- """Test LocationViewType labels - important for UI display."""
- self.assertEqual(LocationViewType.DEFAULT.label, 'Default')
- self.assertEqual(LocationViewType.SECURITY.label, 'Security')
- self.assertEqual(LocationViewType.LIGHTS.label, 'Lights')
- self.assertEqual(LocationViewType.CLIMATE.label, 'Climate')
- self.assertEqual(LocationViewType.ENERGY.label, 'Energy')
- self.assertEqual(LocationViewType.SUPPRESS.label, 'Suppress')
- return
-
-
-class TestSvgItemType(BaseTestCase):
-
- def test_svg_item_type_classification_properties(self):
- """Test SvgItemType classification logic - critical for SVG rendering."""
- # ICON should be icon, not path
- self.assertTrue(SvgItemType.ICON.is_icon)
- self.assertFalse(SvgItemType.ICON.is_path)
- self.assertFalse(SvgItemType.ICON.is_path_closed)
-
- # OPEN_PATH should be path, not icon, not closed
- self.assertFalse(SvgItemType.OPEN_PATH.is_icon)
- self.assertTrue(SvgItemType.OPEN_PATH.is_path)
- self.assertFalse(SvgItemType.OPEN_PATH.is_path_closed)
-
- # CLOSED_PATH should be path, not icon, and closed
- self.assertFalse(SvgItemType.CLOSED_PATH.is_icon)
- self.assertTrue(SvgItemType.CLOSED_PATH.is_path)
- self.assertTrue(SvgItemType.CLOSED_PATH.is_path_closed)
- return
-
- def test_svg_item_type_path_detection_logic(self):
- """Test is_path property logic - critical for SVG path processing."""
- path_types = [SvgItemType.OPEN_PATH, SvgItemType.CLOSED_PATH]
- non_path_types = [SvgItemType.ICON]
-
- for svg_type in path_types:
- with self.subTest(svg_type=svg_type):
- self.assertTrue(svg_type.is_path)
-
- for svg_type in non_path_types:
- with self.subTest(svg_type=svg_type):
- self.assertFalse(svg_type.is_path)
- return
-
- def test_svg_item_type_labels(self):
- """Test SvgItemType labels - important for UI display."""
- self.assertEqual(SvgItemType.ICON.label, 'Icon')
- self.assertEqual(SvgItemType.OPEN_PATH.label, 'Open Path ')
- self.assertEqual(SvgItemType.CLOSED_PATH.label, 'Closed Path ')
- return
-
-
class TestSvgStyleName(BaseTestCase):
def test_svg_style_name_template_generation(self):
@@ -169,42 +71,10 @@ class TestSvgStyleName(BaseTestCase):
self.assertEqual(len(set(css_names)), len(all_styles))
return
- def test_location_view_type_filtering_behavior(self):
- """Test how view types would filter entity states in real scenarios."""
- # Test that specialized views are truly subsets of DEFAULT
- default_states = set(LocationViewType.DEFAULT.entity_state_type_priority_list)
-
- specialized_views = [
- LocationViewType.SECURITY, LocationViewType.LIGHTS, LocationViewType.SOUNDS,
- LocationViewType.CLIMATE, LocationViewType.ENERGY
- ]
-
- for view_type in specialized_views:
- view_states = set(view_type.entity_state_type_priority_list)
- # Each specialized view should be a subset of DEFAULT
- self.assertTrue(view_states.issubset(default_states),
- f'{view_type} states should be subset of DEFAULT states')
-
- # Specialized views should have fewer states than DEFAULT
- self.assertLess(len(view_states), len(default_states),
- f'{view_type} should filter down from DEFAULT')
-
- # Test that LIGHTS view only includes lighting-related states
- lights_states = set(LocationViewType.LIGHTS.entity_state_type_priority_list)
- non_lighting_states = {EntityStateType.MOVEMENT, EntityStateType.ELECTRIC_USAGE,
- EntityStateType.TEMPERATURE, EntityStateType.WATER_FLOW}
-
- # LIGHTS should not include non-lighting states
- intersection = lights_states.intersection(non_lighting_states)
- self.assertEqual(len(intersection), 0,
- 'LIGHTS view should not include non-lighting entity states')
- return
-
def test_enum_string_conversion_consistency(self):
"""Test enum string representations work correctly for database storage."""
# Test LocationViewType string conversion
- view_types = [LocationViewType.DEFAULT, LocationViewType.SECURITY,
- LocationViewType.CLIMATE, LocationViewType.SUPPRESS]
+ view_types = [LocationViewType.DEFAULT, LocationViewType.AUTOMATION]
for view_type in view_types:
# String representation should be lowercase of enum name
diff --git a/src/hi/apps/location/tests/test_models.py b/src/hi/apps/location/tests/test_models.py
index 59531702..0dc37e1d 100644
--- a/src/hi/apps/location/tests/test_models.py
+++ b/src/hi/apps/location/tests/test_models.py
@@ -172,8 +172,8 @@ class TestLocation(BaseTestCase):
)
security_view = LocationView.objects.create(
location=location,
- location_view_type_str='SECURITY',
- name='Security View',
+ location_view_type_str='AUTOMATION',
+ name='Automation View',
svg_view_box_str='0 0 75 75',
svg_rotate=45,
svg_style_name_str='GREYSCALE'
@@ -214,8 +214,8 @@ class TestLocationView(BaseTestCase):
location_view = LocationView.objects.create(
location=location,
- location_view_type_str='SECURITY',
- name='Security View',
+ location_view_type_str='AUTOMATION',
+ name='Automation View',
svg_view_box_str='0 0 50 50',
svg_rotate=45,
svg_style_name_str='GREYSCALE'
@@ -225,21 +225,21 @@ class TestLocationView(BaseTestCase):
view_type = location_view.location_view_type
style_name = location_view.svg_style_name
- self.assertEqual(view_type, LocationViewType.SECURITY)
+ self.assertEqual(view_type, LocationViewType.AUTOMATION)
self.assertEqual(style_name, SvgStyleName.GREYSCALE)
- self.assertEqual(view_type.label, 'Security')
+ self.assertEqual(view_type.label, 'Automation')
self.assertEqual(style_name.label, 'Grey Scale ')
# Test setter conversions work correctly
- location_view.location_view_type = LocationViewType.CLIMATE
+ location_view.location_view_type = LocationViewType.AUTOMATION
location_view.svg_style_name = SvgStyleName.COLOR
- self.assertEqual(location_view.location_view_type_str, 'climate')
+ self.assertEqual(location_view.location_view_type_str, 'automation')
self.assertEqual(location_view.svg_style_name_str, 'color')
# Test that enum business logic is accessible
- climate_priorities = location_view.location_view_type.entity_state_type_priority_list
- self.assertGreater(len(climate_priorities), 0)
+ automation_priorities = location_view.location_view_type.entity_state_type_priority_list
+ self.assertGreater(len(automation_priorities), 0)
return
def test_location_view_cascade_deletion_from_location(self):
@@ -389,8 +389,8 @@ class TestLocationAttribute(BaseTestCase):
# Create view with different viewbox (zoomed in)
zoomed_view = LocationView.objects.create(
location=location,
- location_view_type_str='SECURITY',
- name='Zoomed Security View',
+ location_view_type_str='AUTOMATION',
+ name='Zoomed Automation View',
svg_view_box_str='100 100 200 200',
svg_rotate=0,
svg_style_name_str='COLOR'
@@ -433,9 +433,7 @@ class TestLocationAttribute(BaseTestCase):
# Create views of different types with varied configurations
views_config = [
('DEFAULT', 'Main View', '0 0 1000 800', 0, 'COLOR'),
- ('SECURITY', 'Security Zone', '200 200 600 400', 0, 'GREYSCALE'),
- ('CLIMATE', 'Climate Monitor', '100 500 800 200', 45, 'COLOR'),
- ('LIGHTS', 'Lighting Control', '0 0 500 400', 90, 'GREYSCALE'),
+ ('AUTOMATION', 'Automation Zone', '200 200 600 400', 0, 'GREYSCALE'),
]
created_views = []
@@ -453,7 +451,7 @@ class TestLocationAttribute(BaseTestCase):
# Verify all views exist and have correct configurations
all_views = LocationView.objects.filter(location=location).order_by('order_id')
- self.assertEqual(len(all_views), 4)
+ self.assertEqual(len(all_views), 2)
# Verify each view maintains its distinct configuration
for view, expected_config in zip(all_views, views_config):
diff --git a/src/hi/apps/location/tests/test_transient_models.py b/src/hi/apps/location/tests/test_transient_models.py
index 5c41eb1c..d877406a 100644
--- a/src/hi/apps/location/tests/test_transient_models.py
+++ b/src/hi/apps/location/tests/test_transient_models.py
@@ -166,8 +166,8 @@ class TestLocationViewEditModeData(BaseTestCase):
location_view = LocationView.objects.create(
location=location,
- location_view_type_str='SECURITY',
- name='Security View',
+ location_view_type_str='AUTOMATION',
+ name='Automation View',
svg_view_box_str='50 50 200 200',
svg_rotate=45,
svg_style_name_str='GREYSCALE'
@@ -181,7 +181,7 @@ class TestLocationViewEditModeData(BaseTestCase):
# Test that form can handle enum field updates
update_data = {
- 'name': 'Updated Security View',
+ 'name': 'Updated Automation View',
'location_view_type_str': 'CLIMATE',
'svg_view_box_str': '25 25 250 250',
'svg_rotate': 90,
diff --git a/src/hi/apps/location/tests/test_views.py b/src/hi/apps/location/tests/test_views.py
index 8b683949..5d9c28a7 100644
--- a/src/hi/apps/location/tests/test_views.py
+++ b/src/hi/apps/location/tests/test_views.py
@@ -1,10 +1,14 @@
import logging
-from unittest.mock import patch
+from unittest.mock import patch, Mock
from django.urls import reverse
from hi.apps.collection.models import Collection
-from hi.apps.entity.models import Entity
+from hi.apps.control.models import Controller
+from hi.apps.control.one_click_control_service import (
+ OneClickNotSupported,
+)
+from hi.apps.entity.models import Entity, EntityState
from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import Location, LocationView
from hi.enums import ViewType
@@ -170,6 +174,12 @@ class TestLocationViewView(DualModeViewTestCase):
def test_force_synchronous_exception_handling(self):
"""Test that ForceSynchronousException is properly handled."""
+ # Set up initial view parameters
+ self.setSessionViewParameters(
+ view_type=ViewType.LOCATION_VIEW,
+ location_view=self.location_view
+ )
+
# This would typically be tested by mocking should_force_sync_request
# but the method is on the view class, making it complex to mock directly
url = reverse('location_view', kwargs={'location_view_id': self.location_view.id})
@@ -180,6 +190,12 @@ class TestLocationViewView(DualModeViewTestCase):
def test_session_parameters_updated(self):
"""Test that view parameters are properly updated in session."""
+ # Set up initial view parameters
+ self.setSessionViewParameters(
+ view_type=ViewType.LOCATION_VIEW,
+ location_view=self.location_view
+ )
+
url = reverse('location_view', kwargs={'location_view_id': self.location_view.id})
response = self.client.get(url)
@@ -411,36 +427,172 @@ class TestLocationViewEditModeViewGet(AsyncViewTestCase):
class TestLocationItemStatusView(SyncViewTestCase):
"""
- Tests for LocationItemInfoView - demonstrates item type delegation testing.
- This view redirects to appropriate info views based on item type.
+ Tests for LocationItemStatusView - demonstrates one-click control and fallback behavior.
+ This view executes one-click control based on LocationViewType or falls back to status modals.
"""
def setUp(self):
super().setUp()
- # Create test entity and collection
+
+ # Create test location and location views
+ self.location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ self.automation_view = LocationView.objects.create(
+ location=self.location,
+ name='Automation View',
+ location_view_type_str='AUTOMATION',
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0.0,
+ order_id=1
+ )
+
+ self.default_view = LocationView.objects.create(
+ location=self.location,
+ name='Default View',
+ location_view_type_str='DEFAULT',
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0.0,
+ order_id=2
+ )
+
+ # Create test entity with controllable state
self.entity = Entity.objects.create(
- name='Test Entity',
+ name='Test Light',
entity_type_str='LIGHT'
)
+
+ self.entity_state = EntityState.objects.create(
+ entity=self.entity,
+ entity_state_type_str='ON_OFF',
+ name='Power State'
+ )
+
+ self.controller = Controller.objects.create(
+ name='Light Switch',
+ entity_state=self.entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_integration',
+ integration_name='test_switch'
+ )
+
+ # Create collection for fallback testing
self.collection = Collection.objects.create(
name='Test Collection',
collection_type_str='ROOM',
collection_view_type_str='MAIN'
)
- def test_entity_info_redirect(self):
- """Test redirecting to entity status for entity items."""
+ @patch('hi.apps.control.one_click_control_service.ControllerManager')
+ def test_view_parameters_required_for_automation_view(self, mock_controller_manager):
+ """Test that view_parameters are required for AUTOMATION view processing."""
+ from hi.enums import ItemType
+ from hi.apps.control.transient_models import ControllerOutcome
+
+ # Mock at the system boundary - the controller manager
+ mock_manager = Mock()
+ mock_controller_manager.return_value = mock_manager
+ mock_manager.do_control.return_value = ControllerOutcome(
+ controller=self.controller,
+ new_value='ON',
+ error_list=[]
+ )
+
+ # Set up automation view context (this test verifies the flow works with proper setup)
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.automation_view.id
+ session.save()
+
+ html_id = ItemType.ENTITY.html_id(self.entity.id)
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url)
+
+ # Should successfully execute control and return SVG attribute update response
+ self.assertEqual(response.status_code, 200)
+ data = response.json()
+ self.assertIn('setAttributes', data)
+
+ @patch('hi.apps.control.one_click_control_service.ControllerManager')
+ def test_automation_view_with_controllable_entity_executes_control(self, mock_controller_manager):
+ """Test that AUTOMATION view executes control for entity with controllable states."""
from hi.enums import ItemType
+ from hi.apps.control.transient_models import ControllerOutcome
+
+ # Mock at the system boundary - the controller manager
+ mock_manager = Mock()
+ mock_controller_manager.return_value = mock_manager
+ mock_manager.do_control.return_value = ControllerOutcome(
+ controller=self.controller,
+ new_value='ON',
+ error_list=[]
+ )
+
+ # Set up automation view context
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.automation_view.id
+ session.save()
+
html_id = ItemType.ENTITY.html_id(self.entity.id)
url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url)
+
+ # Should successfully execute control and return SVG attribute update response
+ self.assertEqual(response.status_code, 200)
+ data = response.json()
+ self.assertIn('setAttributes', data)
+
+ def test_one_click_control_entity_not_found(self):
+ """Test handling of nonexistent entity."""
+ from hi.enums import ItemType
+ html_id = ItemType.ENTITY.html_id(99999) # Nonexistent entity
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
response = self.client.get(url)
+ # EntityViewMixin raises Http404 for nonexistent entities
+ self.assertEqual(response.status_code, 404)
+ def test_falls_back_to_status_modal_when_entity_has_no_controllable_states(self):
+ """Test fallback to status modal when entity has no controllable state matching LocationViewType."""
+ from hi.enums import ItemType
+
+ # Create entity with no controllers
+ uncontrollable_entity = Entity.objects.create(
+ name='Sensor Only',
+ entity_type_str='SENSOR'
+ )
+
+ # Add state but no controllers
+ EntityState.objects.create(
+ entity=uncontrollable_entity,
+ entity_state_type_str='TEMPERATURE',
+ name='Temperature Reading'
+ )
+
+ # Set up automation view context
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.automation_view.id
+ session.save()
+
+ html_id = ItemType.ENTITY.html_id(uncontrollable_entity.id)
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url)
+
+ # Should fall back to entity status modal
self.assertEqual(response.status_code, 302)
- expected_url = reverse('entity_status', kwargs={'entity_id': self.entity.id})
+ expected_url = reverse('entity_status', kwargs={'entity_id': uncontrollable_entity.id})
self.assertEqual(response.url, expected_url)
- def test_collection_info_redirect(self):
- """Test redirecting to collection view for collection items."""
+ def test_collection_always_redirects_to_collection_view(self):
+ """Test that collections always redirect to collection view (no one-click control)."""
from hi.enums import ItemType
html_id = ItemType.COLLECTION.html_id(self.collection.id)
url = reverse('location_item_status', kwargs={'html_id': html_id})
@@ -452,18 +604,14 @@ class TestLocationItemStatusView(SyncViewTestCase):
def test_unknown_item_type_returns_400(self):
"""Test that unknown item types return BadRequest."""
- # Use an invalid html_id format to trigger BadRequest
url = reverse('location_item_status', kwargs={'html_id': 'hi-unknown-1'})
response = self.client.get(url)
-
self.assertEqual(response.status_code, 400)
def test_invalid_item_id_returns_400(self):
"""Test that invalid item IDs return BadRequest."""
- # Use an invalid html_id format to trigger BadRequest
url = reverse('location_item_status', kwargs={'html_id': 'invalid-format'})
response = self.client.get(url)
-
self.assertEqual(response.status_code, 400)
def test_post_not_allowed(self):
@@ -472,9 +620,85 @@ class TestLocationItemStatusView(SyncViewTestCase):
html_id = ItemType.ENTITY.html_id(self.entity.id)
url = reverse('location_item_status', kwargs={'html_id': html_id})
response = self.client.post(url)
-
self.assertEqual(response.status_code, 405)
+ def test_default_view_type_skips_service_and_redirects_to_status(self):
+ """Test that DEFAULT LocationViewType skips OneClickControlService and redirects to status."""
+ from hi.enums import ItemType
+
+ # Set up DEFAULT view context
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.default_view.id
+ session.save()
+
+ html_id = ItemType.ENTITY.html_id(self.entity.id)
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url)
+
+ # Should redirect directly to entity status for DEFAULT view type
+ self.assertEqual(response.status_code, 302)
+ expected_url = reverse('entity_status', kwargs={'entity_id': self.entity.id})
+ self.assertEqual(response.url, expected_url)
+
+ @patch('hi.apps.control.one_click_control_service.ControllerManager')
+ def test_automation_view_calls_service_for_entity_control(self, mock_controller_manager):
+ """Test that AUTOMATION LocationViewType calls OneClickControlService for entity control."""
+ from hi.enums import ItemType
+ from hi.apps.control.transient_models import ControllerOutcome
+
+ # Mock at the system boundary - the controller manager
+ mock_manager = Mock()
+ mock_controller_manager.return_value = mock_manager
+ mock_manager.do_control.return_value = ControllerOutcome(
+ controller=self.controller,
+ new_value='ON',
+ error_list=[]
+ )
+
+ # Set up automation view context
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.automation_view.id
+ session.save()
+
+ html_id = ItemType.ENTITY.html_id(self.entity.id)
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url)
+
+ # Should successfully execute control and return SVG attribute update response
+ self.assertEqual(response.status_code, 200)
+ data = response.json()
+ self.assertIn('setAttributes', data)
+
+ @patch('hi.apps.location.views.OneClickControlService')
+ def test_automation_view_handles_unsupported_exception(self, mock_service_class):
+ """Test that OneClickNotSupported falls back to status modal."""
+ from hi.enums import ItemType
+
+ # Mock service to raise unsupported exception - this is legitimate boundary testing
+ mock_service = Mock()
+ mock_service_class.return_value = mock_service
+ mock_service.execute_one_click_control.side_effect = OneClickNotSupported("No controllable states")
+
+ # Set up automation view context
+ session = self.client.session
+ session['view_type'] = str(ViewType.LOCATION_VIEW)
+ session['location_view_id'] = self.automation_view.id
+ session.save()
+
+ html_id = ItemType.ENTITY.html_id(self.entity.id)
+ url = reverse('location_item_status', kwargs={'html_id': html_id})
+
+ response = self.client.get(url)
+
+ # Should still redirect to entity status (graceful fallback)
+ self.assertEqual(response.status_code, 302)
+ expected_url = reverse('entity_status', kwargs={'entity_id': self.entity.id})
+ self.assertEqual(response.url, expected_url)
+
class TestLocationItemEditModeView(SyncViewTestCase):
"""
diff --git a/src/hi/apps/location/view_mixins.py b/src/hi/apps/location/view_mixins.py
index 1f3fa278..d11fb16c 100644
--- a/src/hi/apps/location/view_mixins.py
+++ b/src/hi/apps/location/view_mixins.py
@@ -1,8 +1,12 @@
from django.core.exceptions import BadRequest
-from django.http import Http404
+from django.http import Http404, HttpResponse
+import hi.apps.common.antinode as antinode
+from hi.apps.entity.models import Entity
from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import Location, LocationView
+from hi.apps.monitor.status_display_data import StatusDisplayData
+from hi.apps.monitor.status_display_manager import StatusDisplayManager
class LocationViewMixin:
@@ -36,3 +40,24 @@ class LocationViewMixin:
)
except LocationView.DoesNotExist:
raise Http404( request )
+
+ def get_entity_svg_update_reponse( self, entity : Entity ) -> HttpResponse:
+ """ For updating a single entity in the location view vis antinode reponse """
+
+ entity_status_data = StatusDisplayManager().get_entity_status_data(
+ entity = entity,
+ )
+ set_attributes_map = dict()
+ for entity_state_status_data in entity_status_data.entity_state_status_data_list:
+ status_display_data = StatusDisplayData(
+ entity_state_status_data = entity_state_status_data,
+ )
+ selector = f'.{status_display_data.css_class}'
+ set_attributes_map.update({
+ selector: status_display_data.attribute_dict
+ })
+ continue
+ return antinode.response(
+ set_attributes_map = set_attributes_map,
+ )
+
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index 94ecb5d3..5f1274ec 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -7,14 +7,24 @@ from django.shortcuts import reverse
from django.views.generic import View
from hi.apps.common.utils import is_ajax
+import hi.apps.common.antinode as antinode
from hi.apps.attribute.view_mixins import AttributeEditViewMixin
+from hi.apps.control.one_click_control_service import (
+ OneClickControlService,
+ OneClickError,
+ OneClickNotSupported,
+)
+from hi.apps.entity.models import Entity
+from hi.apps.entity.view_mixins import EntityViewMixin
+from hi.apps.monitor.status_display_manager import StatusDisplayManager
from hi.enums import ItemType, ViewType
from hi.exceptions import ForceSynchronousException
from hi.hi_async_view import HiModalView
from hi.hi_grid_view import HiGridView
from hi.views import page_not_found_response
+from .enums import LocationViewType
from .location_attribute_edit_context import LocationAttributeItemEditContext
from .location_manager import LocationManager
from .models import LocationView, LocationAttribute
@@ -91,7 +101,7 @@ class LocationSwitchView( View, LocationViewMixin ):
return HttpResponseRedirect( redirect_url )
-class LocationItemStatusView( View ):
+class LocationItemStatusView( View, LocationViewMixin, EntityViewMixin ):
def get(self, request, *args, **kwargs):
try:
@@ -100,16 +110,68 @@ class LocationItemStatusView( View ):
raise BadRequest( 'Bad item id.' )
if item_type == ItemType.ENTITY:
- redirect_url = reverse( 'entity_status', kwargs = { 'entity_id': item_id } )
- return HttpResponseRedirect( redirect_url )
+ entity = self.get_entity( request, entity_id = item_id )
+ return self._handle_entity( request = request, entity = entity )
- if item_type == ItemType.COLLECTION:
- redirect_url = reverse( 'collection_view', kwargs = { 'collection_id': item_id } )
- return HttpResponseRedirect( redirect_url )
+ elif item_type == ItemType.COLLECTION:
+ url = reverse( 'collection_view', kwargs = { 'collection_id': item_id } )
+ return HttpResponseRedirect( url )
raise BadRequest( f'Unknown item type "{item_type}".' )
+
+ def _handle_entity(self, request : HttpRequest, entity : Entity ):
+
+ location_view_id = request.view_parameters.location_view_id
+ location_view = LocationView.objects.get( id = location_view_id )
+ if location_view.location_view_type not in [ LocationViewType.AUTOMATION ]:
+ return self._entity_status_response(
+ request = request,
+ entity = entity,
+ )
+ try:
+ logger.debug( f'Trying one-click: {entity}' )
+ controller_outcome = OneClickControlService().execute_one_click_control(
+ entity = entity,
+ location_view_type = location_view.location_view_type,
+ )
+ if controller_outcome.has_errors:
+ raise OneClickError(
+ ' '.join( controller_outcome.error_list )
+ )
+
+ status_display_manager = StatusDisplayManager()
+ override_sensor_value = controller_outcome.new_value
+ status_display_manager.add_entity_state_value_override(
+ entity_state = controller_outcome.controller.entity_state,
+ override_value = override_sensor_value,
+ )
+ return self.get_entity_svg_update_reponse( entity = entity )
+ except OneClickNotSupported:
+ return self._entity_status_response(
+ request = request,
+ entity = entity,
+ )
+
+ except OneClickError as e:
+ # Fall back to status modal when one-click control is not supported
+ logger.warning( f'One-click control failed: {e}' )
+ return antinode.modal_from_template(
+ request = request,
+ template_name = 'modals/internal_error.html',
+ context = {
+ 'modal_title': entity.name,
+ 'error_message': str(e),
+ },
+ status = 500,
+ )
+
+ def _entity_status_response( self, request : HttpRequest, entity : Entity ):
+ url = reverse( 'entity_status', kwargs = { 'entity_id': entity.id } )
+ return HttpResponseRedirect( url )
+
+
class LocationEditView( HiModalView, LocationViewMixin, AttributeEditViewMixin ):
"""
This view uses a dual response pattern:
diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.py
index 3f938223..14c69dac 100644
--- a/src/hi/apps/model_helper.py
+++ b/src/hi/apps/model_helper.py
@@ -27,7 +27,7 @@ class HiModelHelper:
EXCLUDE_FROM_SENSOR_HISTORY = {
EntityStateType.DATETIME,
EntityStateType.BLOB,
- EntityStateType.MULTVALUED,
+ EntityStateType.MULTIVALUED,
}
DEFAULT_CONNECTIVITY_EVENT_WINDOW_SECS = 180
@@ -69,7 +69,7 @@ class HiModelHelper:
name = f'{entity.name} Values'
return cls.create_sensor(
entity = entity,
- entity_state_type = EntityStateType.MULTVALUED,
+ entity_state_type = EntityStateType.MULTIVALUED,
name = name,
integration_key = integration_key,
)
diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.py
index bce62f96..2286f730 100644
--- a/src/hi/apps/monitor/status_display_data.py
+++ b/src/hi/apps/monitor/status_display_data.py
@@ -82,6 +82,9 @@ class StatusDisplayData:
if self.entity_state.entity_state_type == EntityStateType.ON_OFF:
return self._get_on_off_status_style()
+ if self.entity_state.entity_state_type == EntityStateType.LIGHT_DIMMER:
+ return self._get_light_dimmer_status_style()
+
if self.entity_state.entity_state_type == EntityStateType.OPEN_CLOSE:
return self._get_open_close_status_style()
@@ -148,6 +151,9 @@ class StatusDisplayData:
return StatusStyle.Off
return None
+ def _get_light_dimmer_status_style( self ):
+ return StatusStyle.light_dimmer( self.latest_sensor_value )
+
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 1f25adad..bf3ee745 100644
--- a/src/hi/apps/monitor/status_display_manager.py
+++ b/src/hi/apps/monitor/status_display_manager.py
@@ -5,7 +5,6 @@ from hi.apps.control.transient_models import ControllerData
from hi.apps.common.singleton import Singleton
from hi.apps.entity.enums import EntityStateType
from hi.apps.entity.models import Entity, EntityState
-from hi.apps.location.enums import LocationViewType
from hi.apps.location.models import LocationView
from hi.apps.location.svg_item_factory import SvgItemFactory
from hi.apps.sense.models import Sensor
@@ -26,7 +25,7 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
ttl = self.STATUS_VALUE_OVERRIDES_SECS,
)
return
-
+
def get_status_css_class_update_map( self ) -> Dict[ str, str ]:
entity_state_status_data_list = self.get_all_entity_state_status_data_list()
@@ -198,7 +197,7 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
self,
entity_states : Sequence[ EntityState ] ) -> Dict[ EntityState, EntityStateStatusData ]:
- # Collect all the sensors for al the input EntityStates, so we can
+ # Collect all the sensors for all the input EntityStates, so we can
# issue one fetch of the latest SensorData.
#
entity_state_to_sensor_list = dict()
@@ -264,10 +263,6 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
really only represent one thing at a time (visually).
"""
- location_view_type = location_view.location_view_type
- if location_view_type == LocationViewType.SUPPRESS:
- return dict()
-
entity_to_entity_state_list = self._get_entity_to_entity_state_list(
location_view = location_view,
entities = entities,
@@ -304,14 +299,12 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
LocationView.
"""
location_view_type = location_view.location_view_type
- if location_view_type == LocationViewType.SUPPRESS:
- return dict()
entity_state_type_priority_list = location_view_type.entity_state_type_priority_list
entity_to_entity_state_list = dict()
for entity in entities:
- entity_state_list = self._get_entity_state_list_for_status(
+ entity_state_list = self.get_entity_state_list_for_status(
entity = entity,
entity_state_type_priority_list = entity_state_type_priority_list,
)
@@ -321,7 +314,7 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
return entity_to_entity_state_list
- def _get_entity_state_list_for_status(
+ def get_entity_state_list_for_status(
self,
entity : Entity,
entity_state_type_priority_list : List[ EntityStateType ] ) -> List[ EntityState ]:
@@ -336,7 +329,7 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
all_entity_states = [ x.entity_state for x in delegations_queryset ]
all_entity_states.extend( entity.states.all() )
- # Gather all possible EntityStateType for the Entity and its pricipals.
+ # Gather all possible EntityStateType for the Entity and its principals.
entity_state_list_map = dict()
for entity_state in all_entity_states:
if entity_state.entity_state_type not in entity_state_list_map:
@@ -347,21 +340,20 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
if not entity_state_list_map:
return None
- entity_state_type_for_status = self._get_entity_state_type_for_status(
+ entity_state_type_for_status = self.get_entity_state_type_for_status(
entity_state_types = entity_state_list_map.keys(),
entity_state_type_priority_list = entity_state_type_priority_list,
)
entity_state_list = entity_state_list_map.get( entity_state_type_for_status )
-
return entity_state_list
- def _get_entity_state_type_for_status(
+ def get_entity_state_type_for_status(
self,
entity_state_types : Sequence[ EntityStateType ],
entity_state_type_priority_list : List[ EntityStateType ] ) -> EntityStateType:
"""
Determines the single EntityStateType that is the highest display priority
- from the given priority list.
+ from the given priority list. This defined what status will be visually displayed.
"""
for priority_entity_state_type in entity_state_type_priority_list:
diff --git a/src/hi/apps/weather/daily_weather_tracker.py b/src/hi/apps/weather/daily_weather_tracker.py
index 2095606f..5a086902 100644
--- a/src/hi/apps/weather/daily_weather_tracker.py
+++ b/src/hi/apps/weather/daily_weather_tracker.py
@@ -244,8 +244,8 @@ class DailyWeatherTracker(Singleton):
f"max={field_stats.get('max', {}).get('value', 'None')}°C, "
f"new_value={value}°C")
else:
- logger.warning(f"Temperature {value}°C not recorded"
- f" - no min/max update needed for {date_key}")
+ logger.debug( f"Temperature {value}°C not recorded"
+ f" - no min/max update needed for {date_key}")
except Exception as e:
logger.exception(f"Error recording {field_name} value: {e}")
diff --git a/src/hi/hi_styles.py b/src/hi/hi_styles.py
index 8dbd878b..22fb870e 100644
--- a/src/hi/hi_styles.py
+++ b/src/hi/hi_styles.py
@@ -523,3 +523,27 @@ class StatusStyle:
fill_color = cls.DEFAULT_FILL_COLOR,
fill_opacity = cls.DEFAULT_FILL_OPACITY,
)
+
+ @classmethod
+ def light_dimmer( cls, status_value_str : str ):
+ try:
+ status_value = int(status_value_str)
+ except (TypeError, ValueError):
+ status_value = 0
+
+ opacity = status_value / 100.0
+ if status_value < 15:
+ new_value = 'off'
+ elif status_value < 85:
+ new_value = 'dim'
+ else:
+ new_value = 'on'
+
+ return SvgStatusStyle(
+ status_value = new_value,
+ stroke_color = 'yellow',
+ stroke_width = cls.DEFAULT_STROKE_WIDTH,
+ stroke_dasharray = cls.DEFAULT_STROKE_DASHARRAY,
+ fill_color = 'yellow',
+ fill_opacity = opacity,
+ )
diff --git a/src/hi/services/hass/hass_controller.py b/src/hi/services/hass/hass_controller.py
index fa7fbd53..c8e723bd 100644
--- a/src/hi/services/hass/hass_controller.py
+++ b/src/hi/services/hass/hass_controller.py
@@ -15,7 +15,8 @@ class HassController( IntegrationController, HassMixin ):
def do_control( self,
integration_details : IntegrationDetails,
control_value : str ) -> IntegrationControlResult:
- logger.debug( f'HAss do_control ENTRY: integration_details={integration_details}, control_value={control_value}' )
+ logger.debug( f'HAss do_control ENTRY: integration_details={integration_details},'
+ f' control_value={control_value}' )
try:
entity_id = integration_details.key.integration_name
domain_payload = integration_details.payload or {}
@@ -27,7 +28,10 @@ class HassController( IntegrationController, HassMixin ):
)
logger.debug( f'HAss do_control converted value: {hass_state_value}' )
- return self._do_control_with_services( entity_id, control_value, hass_state_value, domain_payload )
+ return self._do_control_with_services( entity_id,
+ control_value,
+ hass_state_value,
+ domain_payload )
except Exception as e:
logger.warning( f'Exception in HAss do_control: {e}' )
return IntegrationControlResult(
@@ -35,7 +39,10 @@ class HassController( IntegrationController, HassMixin ):
error_list = [ str(e) ],
)
- def _do_control_with_set_state( self, hass_state_id: str, control_value: str, hass_state_value: str ) -> IntegrationControlResult:
+ def _do_control_with_set_state( self,
+ hass_state_id : str,
+ control_value : str,
+ hass_state_value : str ) -> IntegrationControlResult:
"""
Legacy method using Home Assistant set_state API.
@@ -51,7 +58,8 @@ class HassController( IntegrationController, HassMixin ):
# If we get here, the HTTP call succeeded (set_state raises exception on failure)
error_list = list()
- logger.debug( f'HAss set state SUCCESS: {hass_state_id}={hass_state_value}, response_data={response_data}' )
+ logger.debug( f'HAss set state SUCCESS: {hass_state_id}={hass_state_value},'
+ f' response_data={response_data}' )
return IntegrationControlResult(
new_value = control_value,
error_list = error_list,
@@ -69,23 +77,37 @@ class HassController( IntegrationController, HassMixin ):
if not domain:
# Fallback to parsing from entity_id if payload missing
if '.' not in hass_state_id:
- logger.warning( f'Invalid hass_state_id format and no domain payload: {hass_state_id}' )
+ logger.warning( f'Invalid hass_state_id format and no domain payload:'
+ f' {hass_state_id}' )
return IntegrationControlResult(
new_value = None,
error_list = [f'Invalid entity_id format: {hass_state_id}'],
)
domain = hass_state_id.split('.', 1)[0]
- logger.warning( f'Missing domain payload for {hass_state_id}, using parsed domain: {domain}' )
+ logger.warning( f'Missing domain payload for {hass_state_id},'
+ f' using parsed domain: {domain}' )
# Use payload-based service routing if available, otherwise best-effort
if domain_payload:
- return self._control_device_with_payload( domain, hass_state_id, control_value, hass_state_value, domain_payload )
+ return self._control_device_with_payload( domain,
+ hass_state_id,
+ control_value,
+ hass_state_value,
+ domain_payload )
else:
- return self._control_device_best_effort( domain, hass_state_id, control_value, hass_state_value )
+ return self._control_device_best_effort( domain,
+ hass_state_id,
+ control_value,
+ hass_state_value )
- def _control_on_off_device( self, domain: str, hass_state_id: str, control_value: str, hass_state_value: str ) -> IntegrationControlResult:
+ def _control_on_off_device( self,
+ domain: str,
+ hass_state_id: str,
+ control_value: str,
+ hass_state_value: str ) -> IntegrationControlResult:
"""Handle on/off control for lights, switches, and similar devices"""
- logger.debug( f'HAss attempting service call for {domain}: {hass_state_id}={control_value}' )
+ logger.debug( f'HAss attempting service call for {domain}:'
+ f' {hass_state_id}={control_value}' )
# Determine service based on control value
if control_value.lower() in ['on', 'true', '1']:
@@ -113,7 +135,11 @@ class HassController( IntegrationController, HassMixin ):
error_list = error_list,
)
- def _control_device_best_effort( self, domain: str, hass_state_id: str, control_value: str, hass_state_value: str ) -> IntegrationControlResult:
+ def _control_device_best_effort( self,
+ domain : str,
+ hass_state_id : str,
+ control_value : str,
+ hass_state_value : str ) -> IntegrationControlResult:
"""
Best-effort device control when payload is missing.
Uses standard Home Assistant service patterns based on domain and control value.
@@ -143,7 +169,10 @@ class HassController( IntegrationController, HassMixin ):
except (ValueError, TypeError):
return False
- def _control_on_off_best_effort( self, domain: str, hass_state_id: str, control_value: str ) -> IntegrationControlResult:
+ def _control_on_off_best_effort( self,
+ domain : str,
+ hass_state_id : str,
+ control_value : str ) -> IntegrationControlResult:
"""Best-effort on/off/open/close control based on standard HA patterns"""
logger.debug( f'HAss best-effort on/off control: {domain} {hass_state_id}={control_value}' )
@@ -169,7 +198,8 @@ class HassController( IntegrationController, HassMixin ):
else:
service = 'turn_off' # Fallback
else:
- logger.warning( f'Unknown control value "{control_value}" for best-effort control of {hass_state_id}' )
+ logger.warning( f'Unknown control value "{control_value}"'
+ f' for best-effort control of {hass_state_id}' )
return IntegrationControlResult(
new_value = None,
error_list = [f'Unknown control value: {control_value}'],
@@ -182,15 +212,20 @@ class HassController( IntegrationController, HassMixin ):
hass_state_id = hass_state_id,
)
- logger.debug( f'HAss best-effort service call SUCCESS: {domain}.{service} for {hass_state_id}' )
+ logger.debug( f'HAss best-effort service call SUCCESS: {domain}.{service}'
+ f' for {hass_state_id}' )
return IntegrationControlResult(
new_value = control_value,
error_list = [],
)
- def _control_numeric_best_effort( self, domain: str, hass_state_id: str, control_value: str ) -> IntegrationControlResult:
+ def _control_numeric_best_effort( self,
+ domain : str,
+ hass_state_id : str,
+ control_value : str ) -> IntegrationControlResult:
"""Best-effort numeric control based on common HA patterns"""
- logger.debug( f'HAss best-effort numeric control: {domain} {hass_state_id}={control_value}' )
+ logger.debug( f'HAss best-effort numeric control: {domain}'
+ f' {hass_state_id}={control_value}' )
try:
numeric_value = float(control_value)
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 130301f1..b487dfa6 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -217,8 +217,8 @@ class HassConverter:
# Other domains (read-only)
# Note: CAMERA_DOMAIN entities should have has_video_stream=True but no VIDEO_STREAM EntityState
- (HassApi.SUN_DOMAIN, None, None): EntityStateType.MULTVALUED,
- (HassApi.WEATHER_DOMAIN, None, None): EntityStateType.MULTVALUED,
+ (HassApi.SUN_DOMAIN, None, None): EntityStateType.MULTIVALUED,
+ (HassApi.WEATHER_DOMAIN, None, None): EntityStateType.MULTIVALUED,
}
# Mapping 2: Control Service Mapping - only for controllable EntityStates
@@ -853,7 +853,7 @@ class HassConverter:
integration_key = integration_key,
name = name,
)
- elif entity_state_type == EntityStateType.MULTVALUED:
+ elif entity_state_type == EntityStateType.MULTIVALUED:
sensor = HiModelHelper.create_multivalued_sensor(
entity = entity,
integration_key = integration_key,
@@ -994,7 +994,7 @@ class HassConverter:
integration_key = integration_key,
name = name,
)
- elif entity_state_type == EntityStateType.MULTVALUED:
+ elif entity_state_type == EntityStateType.MULTIVALUED:
sensor = HiModelHelper.create_multivalued_sensor(
entity = entity,
integration_key = integration_key,
@@ -1123,7 +1123,7 @@ class HassConverter:
)
@classmethod
- def hass_state_to_sensor_value_str( self, hass_state : HassState ) -> str:
+ def hass_state_to_sensor_value_str( cls, hass_state : HassState ) -> str:
if hass_state.domain == HassApi.SUN_DOMAIN:
return hass_state.state_value
@@ -1131,6 +1131,38 @@ class HassConverter:
elif hass_state.domain == HassApi.WEATHER_DOMAIN:
return hass_state.state_value
+ elif hass_state.domain == HassApi.LIGHT_DOMAIN:
+ # Handle light domain - could be LIGHT_DIMMER or ON_OFF
+ if cls._has_brightness_capability(hass_state):
+ # This is a dimmer light - normalize to 0-100 numeric values
+ if hass_state.state_value.lower() == HassStateValue.OFF:
+ return "0"
+ elif hass_state.state_value.lower() == HassStateValue.ON:
+ # Extract brightness from attributes (HA uses 1-255, we use 0-100)
+ brightness = hass_state.attributes.get('brightness')
+ if brightness is not None:
+ try:
+ # Convert HA brightness (1-255) to percentage (0-100) with rounding
+ brightness_pct = round((float(brightness) / 255.0) * 100)
+ return str(brightness_pct)
+ except (ValueError, TypeError):
+ # Invalid brightness value, assume full brightness
+ return "100"
+ else:
+ # No brightness info available, assume full brightness
+ return "100"
+ else:
+ # Unknown state, return as-is
+ return hass_state.state_value
+ else:
+ # Regular on/off light - convert to EntityStateValue strings
+ if hass_state.state_value.lower() == HassStateValue.ON:
+ return str(EntityStateValue.ON)
+ elif hass_state.state_value.lower() == HassStateValue.OFF:
+ return str(EntityStateValue.OFF)
+ else:
+ return hass_state.state_value
+
elif hass_state.domain == HassApi.BINARY_SENSOR_DOMAIN:
if hass_state.state_value.lower() == HassStateValue.ON:
@@ -1175,7 +1207,7 @@ class HassConverter:
return hass_state.state_value
@classmethod
- def hass_entity_id_to_state_value_str( self,
+ def hass_entity_id_to_state_value_str( cls,
hass_entity_id : str,
hi_value : str) -> str:
if hi_value is None:
diff --git a/src/hi/services/hass/tests/test_dimmer_state_conversion.py b/src/hi/services/hass/tests/test_dimmer_state_conversion.py
new file mode 100644
index 00000000..eb8d274d
--- /dev/null
+++ b/src/hi/services/hass/tests/test_dimmer_state_conversion.py
@@ -0,0 +1,152 @@
+import logging
+from django.test import TestCase
+
+from hi.services.hass.hass_converter import HassConverter
+from hi.services.hass.hass_models import HassState
+
+logging.disable(logging.CRITICAL)
+
+
+class TestDimmerStateConversion(TestCase):
+ """Test the dimmer state conversion logic in hass_state_to_sensor_value_str"""
+
+ def test_dimmer_light_off_returns_zero(self):
+ """Test that dimmer light in 'off' state returns '0'"""
+ api_dict = {
+ 'entity_id': 'light.dimmer_switch',
+ 'state': 'off',
+ 'attributes': {
+ 'brightness': 100,
+ 'supported_features': 127,
+ 'friendly_name': 'Dimmer Switch'
+ }
+ }
+ hass_state = HassState(
+ api_dict=api_dict,
+ entity_id='light.dimmer_switch',
+ domain='light',
+ entity_name_sans_prefix='dimmer_switch',
+ entity_name_sans_suffix='dimmer_switch'
+ )
+
+ result = HassConverter.hass_state_to_sensor_value_str(hass_state)
+ self.assertEqual(result, "0")
+
+ def test_dimmer_light_on_with_brightness_converts_correctly(self):
+ """Test that dimmer light converts HA brightness (1-255) to percentage (0-100)"""
+ test_cases = [
+ (255, "100"), # Full brightness
+ (128, "50"), # Half brightness (rounded)
+ (127, "50"), # Half brightness (rounded down)
+ (25, "10"), # Low brightness (rounded)
+ (1, "0"), # Minimum HA brightness maps to 0%
+ ]
+
+ for ha_brightness, expected_pct in test_cases:
+ with self.subTest(brightness=ha_brightness):
+ api_dict = {
+ 'entity_id': 'light.dimmer_switch',
+ 'state': 'on',
+ 'attributes': {
+ 'brightness': ha_brightness,
+ 'supported_features': 127,
+ 'friendly_name': 'Dimmer Switch'
+ }
+ }
+ hass_state = HassState(
+ api_dict=api_dict,
+ entity_id='light.dimmer_switch',
+ domain='light',
+ entity_name_sans_prefix='dimmer_switch',
+ entity_name_sans_suffix='dimmer_switch'
+ )
+
+ result = HassConverter.hass_state_to_sensor_value_str(hass_state)
+ self.assertEqual(result, expected_pct)
+
+ def test_dimmer_light_on_without_brightness_defaults_to_full(self):
+ """Test that dimmer light 'on' with brightness attribute but None value defaults to 100"""
+ api_dict = {
+ 'entity_id': 'light.dimmer_switch',
+ 'state': 'on',
+ 'attributes': {
+ 'brightness': None, # Brightness attribute present but None
+ 'supported_features': 127,
+ 'friendly_name': 'Dimmer Switch'
+ }
+ }
+ hass_state = HassState(
+ api_dict=api_dict,
+ entity_id='light.dimmer_switch',
+ domain='light',
+ entity_name_sans_prefix='dimmer_switch',
+ entity_name_sans_suffix='dimmer_switch'
+ )
+
+ result = HassConverter.hass_state_to_sensor_value_str(hass_state)
+ self.assertEqual(result, "100")
+
+ def test_regular_light_on_off_returns_entity_state_values(self):
+ """Test that regular (non-dimmer) lights return EntityStateValue strings"""
+ # Test ON state (no brightness attribute = not a dimmer)
+ api_dict_on = {
+ 'entity_id': 'light.regular_switch',
+ 'state': 'on',
+ 'attributes': {
+ 'supported_features': 1, # No brightness-related attributes
+ 'friendly_name': 'Regular Switch'
+ }
+ }
+ hass_state_on = HassState(
+ api_dict=api_dict_on,
+ entity_id='light.regular_switch',
+ domain='light',
+ entity_name_sans_prefix='regular_switch',
+ entity_name_sans_suffix='regular_switch'
+ )
+
+ result_on = HassConverter.hass_state_to_sensor_value_str(hass_state_on)
+ self.assertEqual(result_on, "on") # EntityStateValue.ON (lowercase string representation)
+
+ # Test OFF state (no brightness attribute = not a dimmer)
+ api_dict_off = {
+ 'entity_id': 'light.regular_switch',
+ 'state': 'off',
+ 'attributes': {
+ 'supported_features': 1, # No brightness-related attributes
+ 'friendly_name': 'Regular Switch'
+ }
+ }
+ hass_state_off = HassState(
+ api_dict=api_dict_off,
+ entity_id='light.regular_switch',
+ domain='light',
+ entity_name_sans_prefix='regular_switch',
+ entity_name_sans_suffix='regular_switch'
+ )
+
+ result_off = HassConverter.hass_state_to_sensor_value_str(hass_state_off)
+ self.assertEqual(result_off, "off") # EntityStateValue.OFF (lowercase string representation)
+
+ def test_invalid_brightness_defaults_to_full(self):
+ """Test that invalid brightness values default to full brightness"""
+ api_dict = {
+ 'entity_id': 'light.dimmer_switch',
+ 'state': 'on',
+ 'attributes': {
+ 'brightness': 'invalid',
+ 'supported_features': 127,
+ 'friendly_name': 'Dimmer Switch'
+ }
+ }
+ hass_state = HassState(
+ api_dict=api_dict,
+ entity_id='light.dimmer_switch',
+ domain='light',
+ entity_name_sans_prefix='dimmer_switch',
+ entity_name_sans_suffix='dimmer_switch'
+ )
+
+ result = HassConverter.hass_state_to_sensor_value_str(hass_state)
+ self.assertEqual(result, "100")
+
diff --git a/src/hi/services/hass/tests/test_hass_converter_mapping.py b/src/hi/services/hass/tests/test_hass_converter_mapping.py
index e36c2807..a8423a8c 100644
--- a/src/hi/services/hass/tests/test_hass_converter_mapping.py
+++ b/src/hi/services/hass/tests/test_hass_converter_mapping.py
@@ -271,8 +271,8 @@ class TestHassConverterMapping(TestCase):
(HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.MOVEMENT),
(HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.CONNECTIVITY),
(HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.ON_OFF),
- (HassApi.SUN_DOMAIN, EntityStateType.MULTVALUED),
- (HassApi.WEATHER_DOMAIN, EntityStateType.MULTVALUED),
+ (HassApi.SUN_DOMAIN, EntityStateType.MULTIVALUED),
+ (HassApi.WEATHER_DOMAIN, EntityStateType.MULTIVALUED),
]
for domain, entity_type in non_controllable_cases:
diff --git a/src/hi/services/zoneminder/tests/test_zm_controller.py b/src/hi/services/zoneminder/tests/test_zm_controller.py
index acd41d37..64765c58 100644
--- a/src/hi/services/zoneminder/tests/test_zm_controller.py
+++ b/src/hi/services/zoneminder/tests/test_zm_controller.py
@@ -450,7 +450,7 @@ class TestZoneMinderControllerMonitorFunctionControl(TestCase):
with self.assertRaises(ValueError) as context:
self.controller.set_monitor_function('222', 'InvalidFunction')
- self.assertEqual(str(context.exception), 'Problen setting ZM monitor function.')
+ self.assertEqual(str(context.exception), 'Problem setting ZM monitor function.')
# Verify the monitor was called and error was detected
self.mock_monitor_222.set_parameter.assert_called_once_with({'function': 'InvalidFunction'})
diff --git a/src/hi/services/zoneminder/zm_controller.py b/src/hi/services/zoneminder/zm_controller.py
index eb251acf..a5843eef 100644
--- a/src/hi/services/zoneminder/zm_controller.py
+++ b/src/hi/services/zoneminder/zm_controller.py
@@ -61,7 +61,7 @@ class ZoneMinderController( IntegrationController, ZoneMinderMixin ):
logger.debug( f'ZM Set monitor: {monitor_id}={function_value}, response={response}' )
response_message = response.get('message')
if response_message and ( 'error' in response_message.lower() ):
- raise ValueError( 'Problen setting ZM monitor function.')
+ raise ValueError( 'Problem setting ZM monitor function.')
return IntegrationControlResult(
new_value = function_value,
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index 005c85ce..1dbea05f 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -70,14 +70,14 @@ LOGGING = {
'level': 'INFO',
'propagate': False,
},
- 'hi.apps.control': {
+ 'hi.apps.console': {
'handlers': ['console' ],
'level': 'INFO',
'propagate': False,
},
- 'hi.apps.console': {
+ 'hi.apps.control': {
'handlers': ['console' ],
- 'level': 'INFO',
+ 'level': 'DEBUG',
'propagate': False,
},
'hi.services.hass': {
@@ -90,6 +90,11 @@ LOGGING = {
'level': 'INFO',
'propagate': False,
},
+ 'hi.apps.location': {
+ 'handlers': ['console' ],
+ 'level': 'DEBUG',
+ 'propagate': False,
+ },
'hi.apps.monitor': {
'handlers': ['console' ],
'level': 'INFO',
@@ -112,7 +117,7 @@ LOGGING = {
},
'hi.apps.weather': {
'handlers': ['console' ],
- 'level': 'DEBUG',
+ 'level': 'INFO',
'propagate': False,
},
'hi.services.zoneminder': {
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index 90efa5f5..3b84529d 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -599,6 +599,9 @@ g[status="past"] {
filter: drop-shadow(0 0 5px var(--status-past-color));
}
+g[status="off"] {
+ filter: drop-shadow(0 0 5px var(--status-on-color));
+}
g[status="off"] path.hi-state-bg {
fill: var(--status-off-color);
}
@@ -616,6 +619,15 @@ div[status="on"] {
color: var(--on-status-on-color);
background-color: var(--status-on-color);
}
+g[status="dim"] {
+ filter: drop-shadow(0 0 5px var(--status-on-color));
+ opacity: 0.5;
+}
+div[status="dim"] {
+ color: var(--on-status-on-color);
+ background-color: var(--status-on-color);
+ opacity: 0.5;
+}
g[status="open"] {
filter: drop-shadow(0 0 5px var(--status-bad-color));
@@ -633,6 +645,7 @@ g[status="low"] {
filter: drop-shadow(0 0 5px var(--status-bad-color));
}
+
div[status] {
color: var(--black);
background-color: var(--white);
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index e5cc642e..e46015b7 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -76,17 +76,17 @@
//
// 2. JSON Response - supports multiple operations:
// {
-// "location": "/redirect/url", // Redirect browser
-// "refresh": true, // Refresh entire page
-// "html": "<div>...</div>", // Content for main target
-// "insert": {"id1": "...", ...}, // Replace inner HTML by ID
-// "replace": {"id1": "...", ...}, // Replace entire elements by ID
-// "append": {"id1": "...", ...}, // Append to elements by ID
-// "setAttributes": {"id1": {...}}, // Set element attributes
-// "modal": "<div>...</div>", // Create and show modal
-// "pushUrl": "/new/url", // Update browser URL without reload
-// "resetScrollbar": true, // Reset to top of page
-// "scrollTo": "element-id" // Scroll to specified element ID
+// "location": "/redirect/url", // Redirect browser
+// "refresh": true, // Refresh entire page
+// "html": "<div>...</div>", // Content for main target
+// "insert": {"id1": "...", ...}, // Replace inner HTML by ID
+// "replace": {"id1": "...", ...}, // Replace entire elements by ID
+// "append": {"id1": "...", ...}, // Append to elements by ID
+// "setAttributes": {"id-or-selector1": {...}}, // Set element attributes
+// "modal": "<div>...</div>", // Create and show modal
+// "pushUrl": "/new/url", // Update browser URL without reload
+// "resetScrollbar": true, // Reset to top of page
+// "scrollTo": "element-id" // Scroll to specified element ID
// }
// ====================
@@ -652,19 +652,11 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {
}
}
- // This entry should be a map from html ids to content that should
- // be appended. This add it as the last child of the target tag id.
+ // This entry should be a map from element selectors to attribute maps.
+ // Supports both plain IDs (backward compatibility) and CSS selectors.
//
if ( 'setAttributes' in json ) {
- for ( let htmlId in json['setAttributes'] ) {
- let targetObj = $("#"+htmlId);
- let attrMap = json['setAttributes'][htmlId];
- for ( let attrName in attrMap ) {
- let attrValue = attrMap[attrName];
- targetObj.attr( attrName, attrValue );
- handleNewContentAdded( targetObj );
- }
- }
+ handleSetAttributes( json['setAttributes'] );
}
// In case any content with preserved scroll bars was refreshed.
@@ -707,6 +699,44 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {
}
};
+//====================
+function handleSetAttributes( attributesMap ) {
+ for ( let selector in attributesMap ) {
+ let targetObj;
+
+ try {
+ // Check if selector already looks like a CSS selector
+ if ( selector.startsWith('#') || selector.startsWith('.') ||
+ selector.includes(' ') || selector.includes('[') || selector.includes(':') ) {
+ // Already a CSS selector, use directly
+ targetObj = $(selector);
+ } else {
+ // Try as ID first (backward compatibility)
+ targetObj = $("#" + selector);
+
+ // If no match found, try as CSS selector
+ if ( targetObj.length === 0 ) {
+ targetObj = $(selector);
+ }
+ }
+
+ if ( targetObj.length > 0 ) {
+ let attrMap = attributesMap[selector];
+ for ( let attrName in attrMap ) {
+ let attrValue = attrMap[attrName];
+ targetObj.attr( attrName, attrValue );
+ handleNewContentAdded( targetObj );
+ }
+ } else {
+ console.warn(`setAttributes: No elements found for selector '${selector}'`);
+ }
+ } catch (e) {
+ console.error(`setAttributes: Invalid selector '${selector}': ${e.message}`);
+ // Continue processing other selectors instead of failing completely
+ }
+ }
+}
+
//====================
function handleNewContentAdded( contentObj ) {
doAutofocusIfNeeded( contentObj );
diff --git a/src/hi/static/js/status.js b/src/hi/static/js/status.js
index 05b74a36..5ec65595 100644
--- a/src/hi/static/js/status.js
+++ b/src/hi/static/js/status.js
@@ -225,7 +225,7 @@
elements.each( function() {
if (this.hasAttribute(attrName)) {
let currentValue = $(this).attr(attrName);
- if ( attrValue && ( currentValue !== String(attrValue) )) {
+ if ( attrValue != null && ( currentValue !== String(attrValue) )) {
$(this).attr( attrName, attrValue );
}
} else {
diff --git a/src/hi/templates/modals/internal_error.html b/src/hi/templates/modals/internal_error.html
index 02a877e9..31496154 100644
--- a/src/hi/templates/modals/internal_error.html
+++ b/src/hi/templates/modals/internal_error.html
@@ -1,5 +1,9 @@
{% extends "modals/error_base.html" %}
{% block title_text %}
+{% if modal_title %}
+{{ modal_title }}
+{% else %}
Internal Error
+{% endif %}
{% endblock %}
diff --git a/src/hi/testing/view_test_base.py b/src/hi/testing/view_test_base.py
index f58707ea..82eab398 100644
--- a/src/hi/testing/view_test_base.py
+++ b/src/hi/testing/view_test_base.py
@@ -33,6 +33,12 @@ class ViewTestBase(BaseTestCase):
def setUp(self):
super().setUp()
+
+ # Add 'testserver' to ALLOWED_HOSTS for Django test client
+ from django.conf import settings
+ if 'testserver' not in settings.ALLOWED_HOSTS:
+ settings.ALLOWED_HOSTS = list(settings.ALLOWED_HOSTS) + ['testserver']
+
User = get_user_model()
self.user = User.objects.create_user(