Skip to content

Home Information - Your home, your data, organized.

Python

First basic status polling and entity styling no working. WIP

Anthony Cassandrac1e5c3ff1a4d
diff --git a/src/hi/apps/api/urls.py b/src/hi/apps/api/urls.py
index 0156c5f1..537195fb 100644
--- a/src/hi/apps/api/urls.py
+++ b/src/hi/apps/api/urls.py
@@ -5,5 +5,8 @@ from . import views
urlpatterns = [
-
+ re_path( r'^status$',
+ views.StatusView.as_view(),
+ name='api_status'),
+
]
diff --git a/src/hi/apps/api/views.py b/src/hi/apps/api/views.py
index c7a3481c..9fcc8a45 100644
--- a/src/hi/apps/api/views.py
+++ b/src/hi/apps/api/views.py
@@ -1,6 +1,37 @@
+import json
import logging
+from django.http import HttpResponse
from django.views.generic import View
+from hi.apps.monitor.status_display_helper import StatusDisplayStatusViewHelper
+
+
logger = logging.getLogger(__name__)
+
+class StatusView( View ):
+
+ CssClassUpdateMap = 'cssClassUpdateMap'
+
+ def get( self, *args, **kwargs ):
+ status_display_data_list = StatusDisplayStatusViewHelper().get_status_display_data()
+
+ css_class_update_map = dict()
+ for status_display_data in status_display_data_list:
+ if status_display_data.should_skip:
+ continue
+ css_class_update_map[status_display_data.css_class] = status_display_data.attribute_dict
+ continue
+
+ data = {
+ self.CssClassUpdateMap: css_class_update_map,
+ }
+ return HttpResponse(
+ json.dumps(data),
+ content_type='application/json',
+ status = 200,
+ )
+
+
+
diff --git a/src/hi/apps/collection/edit/async_views.py b/src/hi/apps/collection/edit/async_views.py
index e9fe2994..543a9bce 100644
--- a/src/hi/apps/collection/edit/async_views.py
+++ b/src/hi/apps/collection/edit/async_views.py
@@ -104,6 +104,7 @@ class CollectionPositionEditView( View, CollectionViewMixin ):
svg_icon_item = SvgItemFactory().create_svg_icon_item(
item = collection_position.collection,
position = collection_position,
+ css_class = '',
)
set_attributes_map = {
svg_icon_item.html_id: {
diff --git a/src/hi/apps/common/svg_models.py b/src/hi/apps/common/svg_models.py
index f5b33d7e..f5c88e69 100644
--- a/src/hi/apps/common/svg_models.py
+++ b/src/hi/apps/common/svg_models.py
@@ -95,13 +95,13 @@ class SvgIconItem:
"""
html_id : str
+ css_class : str
template_name : str
bounding_box : SvgViewBox
position_x : float
position_y : float
rotate : float
scale : float
- status_value : str
@property
def transform_str(self):
@@ -138,13 +138,14 @@ class SvgPathItem:
"""
html_id : str
+ css_class : str
svg_path : str
stroke_color : str
stroke_width : float
fill_color : str
fill_opacity : float
-
+
class SvgDecimalField( models.DecimalField ):
"""
Custom model field for SVG-related decimal values to fix precision and
diff --git a/src/hi/apps/entity/edit/async_views.py b/src/hi/apps/entity/edit/async_views.py
index 2e2eab5e..0744ad0a 100644
--- a/src/hi/apps/entity/edit/async_views.py
+++ b/src/hi/apps/entity/edit/async_views.py
@@ -124,6 +124,7 @@ class EntityPositionEditView( View, EntityViewMixin ):
svg_icon_item = SvgItemFactory().create_svg_icon_item(
item = entity_position.entity,
position = entity_position,
+ css_class = '',
)
set_attributes_map = {
svg_icon_item.html_id: {
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 0f9869b9..23d8a90b 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -152,7 +152,13 @@ class EntityState( models.Model ):
class Meta:
verbose_name = 'Entity State'
verbose_name_plural = 'Entity States'
-
+ constraints = [
+ models.UniqueConstraint(
+ fields = [ 'entity_id', 'entity_state_type_str' ],
+ name = 'entity_state_entity_entity_type',
+ ),
+ ]
+
def __str__(self):
return f'State[{self.id}]: {self.name} [{self.entity_state_type_str}]'
@@ -167,6 +173,10 @@ class EntityState( models.Model ):
def entity_state_type( self, entity_state_type : EntityStateType ):
self.entity_state_type_str = str(entity_state_type)
return
+
+ @property
+ def css_class(self):
+ return f'hi-entity-state-{self.id}'
class EntityStateDelegation(models.Model):
diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.py
index 3ee1dc0a..c171a42e 100644
--- a/src/hi/apps/location/location_manager.py
+++ b/src/hi/apps/location/location_manager.py
@@ -8,9 +8,9 @@ from django.http import HttpRequest
from hi.apps.common.singleton import Singleton
from hi.apps.common.svg_models import SvgViewBox
+from hi.apps.monitor.status_display_helper import StatusDisplayLocationHelper
from .enums import LocationViewType
-from .status_display_helper import StatusDisplayLocationHelper
from .location_view_data import LocationViewData
from .models import (
Location,
@@ -209,11 +209,11 @@ class LocationManager(Singleton):
if include_status_display_data:
status_display_helper = StatusDisplayLocationHelper( location_view = location_view )
- status_display_data_map = status_display_helper.get_status_display_data_map(
- displayed_entities = displayed_entities,
+ status_entity_state_map = status_display_helper.get_status_entity_state_map(
+ entities = displayed_entities,
)
else:
- status_display_data_map = dict()
+ status_entity_state_map = dict()
return LocationViewData(
location_view = location_view,
@@ -223,7 +223,7 @@ class LocationManager(Singleton):
collection_paths = collection_paths,
unpositioned_collections = unpositioned_collections,
orphan_entities = orphan_entities,
- status_display_data_map = status_display_data_map,
+ status_entity_state_map = status_entity_state_map,
)
def set_location_view_order( self, location_view_id_list : List[int] ):
diff --git a/src/hi/apps/location/location_view_data.py b/src/hi/apps/location/location_view_data.py
index d84945db..9cd1bc37 100644
--- a/src/hi/apps/location/location_view_data.py
+++ b/src/hi/apps/location/location_view_data.py
@@ -3,11 +3,10 @@ from typing import Dict, Generator, List, Set
from hi.apps.collection.models import Collection, CollectionPath, CollectionPosition
from hi.apps.common.svg_models import SvgIconItem, SvgPathItem
-from hi.apps.entity.models import Entity, EntityPosition, EntityPath
+from hi.apps.entity.models import Entity, EntityPosition, EntityPath, EntityState
from hi.apps.location.svg_item_factory import SvgItemFactory
from .models import LocationView
-from .transient_models import StatusDisplayData
@dataclass
@@ -23,7 +22,7 @@ class LocationViewData:
collection_paths : List[ CollectionPath ]
unpositioned_collections : List[ Collection ]
orphan_entities : Set[ Entity ]
- status_display_data_map : Dict[ Entity, StatusDisplayData ]
+ status_entity_state_map : Dict[ Entity, EntityState ]
def __post_init__(self):
self._svg_item_factory = SvgItemFactory()
@@ -32,11 +31,14 @@ class LocationViewData:
def svg_icon_items(self) -> Generator[ SvgIconItem, None, None ]:
for entity_position in self.entity_positions:
- status_display_data = self.status_display_data_map.get( entity_position.entity )
+ entity_state = self.status_entity_state_map.get( entity_position.entity )
+ css_class = ''
+ if entity_state:
+ css_class = entity_state.css_class
svg_icon_item = self._svg_item_factory.create_svg_icon_item(
item = entity_position.entity,
position = entity_position,
- status_display_data = status_display_data,
+ css_class = css_class,
)
yield svg_icon_item
continue
@@ -44,6 +46,7 @@ class LocationViewData:
svg_icon_item = self._svg_item_factory.create_svg_icon_item(
item = collection_position.collection,
position = collection_position,
+ css_class = '',
)
yield svg_icon_item
continue
@@ -52,11 +55,14 @@ class LocationViewData:
def svg_path_items(self) -> Generator[ SvgPathItem, None, None ]:
for entity_path in self.entity_paths:
- status_display_data = self.status_display_data_map.get( entity_path.entity )
+ entity_state = self.status_entity_state_map.get( entity_path.entity )
+ css_class = ''
+ if entity_state:
+ css_class = entity_state.css_class
svg_path_item = self._svg_item_factory.create_svg_path_item(
item = entity_path.entity,
path = entity_path,
- status_display_data = status_display_data,
+ css_class = css_class,
)
yield svg_path_item
continue
@@ -64,6 +70,7 @@ class LocationViewData:
svg_path_item = self._svg_item_factory.create_svg_path_item(
item = collection_path.collection,
path = collection_path,
+ css_class = '',
)
yield svg_path_item
continue
diff --git a/src/hi/apps/location/status_display_helper.py b/src/hi/apps/location/status_display_helper.py
deleted file mode 100644
index 81b129ad..00000000
--- a/src/hi/apps/location/status_display_helper.py
+++ /dev/null
@@ -1,100 +0,0 @@
-from typing import Dict, List, Set
-
-from hi.apps.entity.enums import EntityStateType
-from hi.apps.entity.models import Entity, EntityState
-from hi.apps.sense.sensor_response_manager import SensorResponseManager
-
-from .enums import LocationViewType
-from .models import LocationView
-from .transient_models import StatusDisplayData
-
-
-class StatusDisplayLocationHelper:
-
- def __init__( self, location_view : LocationView ):
- self._location_view_type = location_view.location_view_type
- self._entity_state_type_priority_list = self._location_view_type.entity_state_type_priority_list
- self._latest_sensor_response_list_map = SensorResponseManager().get_all_latest_sensor_responses()
- return
-
- def get_status_display_data_map(
- self,
- displayed_entities : Set[ Entity ] ) -> Dict[ Entity, StatusDisplayData ]:
- if self._location_view_type == LocationViewType.SUPPRESS:
- return dict()
-
- entity_to_status_display_data = dict()
- for entity in displayed_entities:
- status_display_data = self.get_status_display_data( entity = entity )
- if not status_display_data:
- continue
- entity_to_status_display_data[entity] = status_display_data
- continue
-
- return entity_to_status_display_data
-
- def get_status_display_data( self, entity : Entity ) -> StatusDisplayData:
-
- entity_state_list = list( entity.states.all() )
-
- # Delegate entities include all their principal entity states as well.
- entity_state_delegations = entity.entity_state_delegations.select_related('entity_state').all()
- entity_state_list.extend([ x.entity_state for x in entity_state_delegations ])
- if not entity_state_list:
- return None
-
- entity_state_type_for_status = self._get_entity_state_type_for_status(
- entity_state_list = entity_state_list,
- )
-
- # N.B. An entity is not limited to a single EntityState per
- # EntityStateType, nor is a single EnttyStateType limited to a
- # single sensor. In the (rare) cases there are multiples of these,
- # we will always use the most recent sensor response.
-
- candidate_sensors_for_status = set()
- for entity_state in entity_state_list:
- if entity_state.entity_state_type == entity_state_type_for_status:
- candidate_sensors_for_status.update( entity_state.sensors.all() )
- continue
-
- latest_sensor_response_list_list = list()
- sensor_map = dict()
- for sensor in candidate_sensors_for_status:
- latest_sensor_response_list = self._latest_sensor_response_list_map.get( sensor.integration_key )
- if latest_sensor_response_list:
- latest_sensor_response_list_list.append( latest_sensor_response_list )
- sensor_map[sensor.integration_key] = sensor
- continue
-
- if not latest_sensor_response_list_list:
- return None
-
- latest_sensor_response_list_list.sort( key = lambda item: item[0].timestamp, reverse = True )
- sensor_response_list_for_status = latest_sensor_response_list_list[0]
- sensor_for_status = sensor_map.get( sensor_response_list_for_status[0].integration_key )
-
- return StatusDisplayData(
- entity = entity,
- sensor = sensor_for_status,
- sensor_response_list = sensor_response_list_for_status,
- )
-
- def _get_entity_state_type_for_status( self, entity_state_list : List[ EntityState ] ) -> EntityStateType:
- entity_state_type_list = [ x.entity_state_type for x in entity_state_list ]
-
- for priority_entity_state_type in self._entity_state_type_priority_list:
- if priority_entity_state_type in entity_state_type_list:
- return priority_entity_state_type
- continue
-
- # If no prioritizes state type matches, then fallback to an
- # arbitrary, but deterministic choice by using all defined values.
- #
- for default_entity_state_type in EntityStateType:
- if default_entity_state_type in entity_state_type_list:
- return default_entity_state_type
- continue
-
- # This code should not really be reachable. Should always match one in fallback case.
- return None
diff --git a/src/hi/apps/location/svg_item_factory.py b/src/hi/apps/location/svg_item_factory.py
index 9f40c873..c8fef292 100644
--- a/src/hi/apps/location/svg_item_factory.py
+++ b/src/hi/apps/location/svg_item_factory.py
@@ -1,10 +1,8 @@
-import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.singleton import Singleton
from hi.apps.common.svg_models import SvgIconItem, SvgPathItem, SvgViewBox
from hi.apps.collection.models import Collection
-from hi.apps.entity.enums import EntityStateType, EntityType
+from hi.apps.entity.enums import EntityType
from hi.apps.entity.models import Entity
-from hi.apps.sense.enums import SensorValue
from .enums import SvgItemType
from .models import (
@@ -13,7 +11,6 @@ from .models import (
LocationItemPathModel,
LocationView,
)
-from .transient_models import StatusDisplayData
class SvgItemFactory( Singleton ):
@@ -24,77 +21,34 @@ class SvgItemFactory( Singleton ):
return
def create_svg_icon_item( self,
- item : LocationItemModelMixin,
- position : LocationItemPositionModel,
- status_display_data : StatusDisplayData = None ) -> SvgIconItem:
+ item : LocationItemModelMixin,
+ position : LocationItemPositionModel,
+ css_class : str ) -> SvgIconItem:
- status_value = 'placeholder'
-
return SvgIconItem(
html_id = item.html_id,
+ css_class = css_class,
position_x = float( position.svg_x ),
position_y = float( position.svg_y ),
rotate = float( position.svg_rotate ),
scale = float( position.svg_scale ),
template_name = 'entity/svg/type.other.svg',
bounding_box = SvgViewBox( x = 0, y = 0, width = 32, height = 32 ),
- status_value = status_value,
)
def create_svg_path_item( self,
- item : LocationItemModelMixin,
- path : LocationItemPathModel,
- status_display_data : StatusDisplayData = None ) -> SvgPathItem:
-
-
-
+ item : LocationItemModelMixin,
+ path : LocationItemPathModel,
+ css_class : str ) -> SvgPathItem:
- if status_display_data:
-
- print( f'\n\n{status_display_data.sensor.entity_state.entity_state_type}' )
- print( f'\n\n{status_display_data.sensor_response_list}' )
- print( f' First = {status_display_data.sensor_response_list[0].value}' )
- if len(status_display_data.sensor_response_list) > 1:
- print( f' Second = {status_display_data.sensor_response_list[1].value}' )
-
- if status_display_data.sensor.entity_state.entity_state_type == EntityStateType.MOVEMENT:
- if status_display_data.sensor_response_list[0].value == str(SensorValue.MOVEMENT_ACTIVE):
- fill_color = 'red'
- fill_opacity = 0.5
- elif (( len(status_display_data.sensor_response_list) > 1 )
- and ( status_display_data.sensor_response_list[1].value == str(SensorValue.MOVEMENT_ACTIVE) )):
- movement_timedelta = datetimeproxy.now() - status_display_data.sensor_response_list[1].timestamp
- if movement_timedelta.seconds < 30:
- fill_color = 'orange'
- fill_opacity = 0.5
- elif movement_timedelta.seconds < 60:
- fill_color = 'yellow'
- fill_opacity = 0.5
- else:
- fill_color = 'white'
- fill_opacity = 0.5
- else:
- fill_color = 'white'
- fill_opacity = 0.0
- else:
- fill_color = 'blue'
- fill_opacity = 0.5
- else:
- fill_color = 'green'
- fill_opacity = 0.5
-
-
-
-
-
-
return SvgPathItem(
html_id = item.html_id,
+ css_class = css_class,
svg_path = path.svg_path,
stroke_color = '#40f040',
stroke_width = 5.0,
- fill_color = fill_color,
- fill_opacity = fill_opacity,
+ fill_color = 'white',
+ fill_opacity = 0.0,
)
def get_svg_item_type( self, obj ) -> SvgItemType:
diff --git a/src/hi/apps/location/templates/location/panes/svg_icon_item.html b/src/hi/apps/location/templates/location/panes/svg_icon_item.html
index 5175b3e5..d909e7ea 100644
--- a/src/hi/apps/location/templates/location/panes/svg_icon_item.html
+++ b/src/hi/apps/location/templates/location/panes/svg_icon_item.html
@@ -1,4 +1,4 @@
-<g id="{{ svg_icon_item.html_id }}" class="selectable draggable"
+<g id="{{ svg_icon_item.html_id }}" class="selectable draggable {{ svg_icon_item.css_class }}"
status="{{ svg_icon_item.status_value }}"
data-type="svg-icon" transform="{{ svg_icon_item.transform_str }}">
{% include svg_icon_item.template_name %}
diff --git a/src/hi/apps/location/templates/location/panes/svg_path_item.html b/src/hi/apps/location/templates/location/panes/svg_path_item.html
index d2302dd3..dad6a5f3 100644
--- a/src/hi/apps/location/templates/location/panes/svg_path_item.html
+++ b/src/hi/apps/location/templates/location/panes/svg_path_item.html
@@ -1,6 +1,6 @@
-<g id="{{ svg_path_item.html_id }}" class="selectable" data-type="svg-path"
- integration-key="{{ svg_icon_item.integration_key }}" >
- <path fill="{{ svg_path_item.fill_color }}"
+<g id="{{ svg_path_item.html_id }}" class="selectable" data-type="svg-path">
+ <path class="{{ svg_path_item.css_class }}"
+ fill="{{ svg_path_item.fill_color }}"
fill-opacity="{{ svg_path_item.fill_opacity }}"
stroke="{{ svg_path_item.stroke_color }}"
stroke-width="{{ svg_path_item.stroke_width }}"
diff --git a/src/hi/apps/location/transient_models.py b/src/hi/apps/location/transient_models.py
index 5ae9656b..7fb48de9 100644
--- a/src/hi/apps/location/transient_models.py
+++ b/src/hi/apps/location/transient_models.py
@@ -1,27 +1,15 @@
from dataclasses import dataclass
-from typing import List
-from hi.apps.entity.models import Entity
from hi.apps.location.edit.forms import (
LocationAttributeFormSet,
LocationAttributeUploadForm,
LocationEditForm,
LocationViewEditForm,
)
-from hi.apps.sense.models import Sensor
-from hi.apps.sense.transient_models import SensorResponse
from .models import Location, LocationView
-@dataclass
-class StatusDisplayData:
- entity : Entity
- sensor : Sensor
- sensor_response_list : List[ SensorResponse ]
-
-
-
@dataclass
class LocationEditData:
""" All the data needed to render the Location edit pane. """
diff --git a/src/hi/apps/monitor/status_display_data.py b/src/hi/apps/monitor/status_display_data.py
new file mode 100644
index 00000000..3c6d5cc5
--- /dev/null
+++ b/src/hi/apps/monitor/status_display_data.py
@@ -0,0 +1,127 @@
+import hi.apps.common.datetimeproxy as datetimeproxy
+from dataclasses import dataclass
+from typing import List
+
+from hi.apps.entity.enums import EntityStateType
+from hi.apps.entity.models import EntityState
+from hi.apps.sense.enums import SensorValue
+from hi.apps.sense.transient_models import SensorResponse
+
+
+@dataclass
+class SvgStatusStyle:
+
+ status_value : str
+ stroke_color : str
+ stroke_width : float
+ fill_color : str
+ fill_opacity : float
+
+ def to_dict(self):
+ return {
+ 'status': self.status_value,
+ 'stroke': self.stroke_color,
+ 'stroke-width': self.stroke_width,
+ 'fill': self.fill_color,
+ 'fill-opacity': self.fill_opacity,
+ }
+
+
+class StatusStyle:
+
+ MovementActive = SvgStatusStyle(
+ status_value = 'active',
+ stroke_color = 'red',
+ stroke_width = None,
+ fill_color = 'red',
+ fill_opacity = 0.5,
+ )
+
+ MovementRecent = SvgStatusStyle(
+ status_value = 'recent',
+ stroke_color = 'orange',
+ stroke_width = None,
+ fill_color = 'orange',
+ fill_opacity = 0.5,
+ )
+
+ MovementPast = SvgStatusStyle(
+ status_value = 'past',
+ stroke_color = 'yellow',
+ stroke_width = None,
+ fill_color = 'yellow',
+ fill_opacity = 0.5,
+ )
+
+ MovementIdle = SvgStatusStyle(
+ status_value = 'idle',
+ stroke_color = '#888888',
+ stroke_width = None,
+ fill_color = 'white',
+ fill_opacity = 0.0,
+ )
+
+
+@dataclass
+class StatusDisplayData:
+ entity_state : EntityState
+ sensor_response_list : List[ SensorResponse ]
+
+ def __post_init__(self):
+ self._svg_status_style = self.get_svg_status_style()
+ return
+
+ @property
+ def should_skip(self):
+ return bool( self._svg_status_style is None )
+
+ @property
+ def css_class(self):
+ return self.entity_state.css_class
+
+ @property
+ def attribute_dict(self):
+ if self._svg_status_style:
+ return self._svg_status_style.to_dict()
+ return dict()
+
+ @property
+ def latest_sensor_value(self):
+ if self.sensor_response_list:
+ return self.sensor_response_list[0].value
+ return None
+
+ @property
+ def penultimate_sensor_value(self):
+ if len(self.sensor_response_list) > 1:
+ return self.sensor_response_list[1].value
+ return None
+
+ @property
+ def penultimate_sensor_timestamp(self):
+ if len(self.sensor_response_list) > 1:
+ return self.sensor_response_list[1].timestamp
+ return None
+
+ def get_svg_status_style(self):
+
+ if self.entity_state.entity_state_type == EntityStateType.MOVEMENT:
+ return self.get_movement_status_style()
+
+ return None
+
+ def get_movement_status_style( self ):
+
+ if self.latest_sensor_value == str(SensorValue.MOVEMENT_ACTIVE):
+ return StatusStyle.MovementActive
+
+ if self.penultimate_sensor_value == str(SensorValue.MOVEMENT_ACTIVE):
+ movement_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ if movement_timedelta.seconds < 30:
+ return StatusStyle.MovementRecent
+
+ elif movement_timedelta.seconds < 60:
+ return StatusStyle.MovementPast
+
+ return StatusStyle.MovementIdle
+
diff --git a/src/hi/apps/monitor/status_display_helper.py b/src/hi/apps/monitor/status_display_helper.py
new file mode 100644
index 00000000..0919f493
--- /dev/null
+++ b/src/hi/apps/monitor/status_display_helper.py
@@ -0,0 +1,105 @@
+from typing import Dict, List, Set
+
+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.monitor.status_display_data import StatusDisplayData
+from hi.apps.sense.sensor_response_manager import SensorResponseManager
+
+
+class StatusDisplayLocationHelper:
+
+ def __init__( self, location_view : LocationView ):
+ self._location_view_type = location_view.location_view_type
+ self._entity_state_type_priority_list = self._location_view_type.entity_state_type_priority_list
+ return
+
+ def get_status_entity_state_map( self, entities : Set[ Entity ] ) -> Dict[ Entity, EntityState ]:
+ if self._location_view_type == LocationViewType.SUPPRESS:
+ return dict()
+
+ entity_to_entity_state_data = dict()
+ for entity in entities:
+ entity_state = self.get_status_entity_state( entity = entity )
+ if entity_state:
+ entity_to_entity_state_data[entity] = entity_state
+ continue
+
+ return entity_to_entity_state_data
+
+ def get_status_entity_state( self, entity : Entity ) -> EntityState:
+
+ entity_state_type_map = dict()
+
+ # Delegate entities include will include all their principal entity
+ # states, though any direct state will take precendence
+
+ delegations_queryset = entity.entity_state_delegations.select_related('entity_state').all()
+ for entity_state_delegation in delegations_queryset:
+ entity_state = entity_state_delegation.entity_state
+ entity_state_type_map[entity_state.entity_state_type] = entity_state
+ continue
+
+ states_queryset = entity.states.all()
+ for entity_state in states_queryset:
+ entity_state_type_map[entity_state.entity_state_type] = entity_state
+ continue
+
+ if not entity_state_type_map:
+ return None
+
+ entity_state_type_for_status = self._get_entity_state_type_for_status(
+ entity_states = entity_state_type_map.values(),
+ )
+
+ return entity_state_type_map.get( entity_state_type_for_status )
+
+ def _get_entity_state_type_for_status( self, entity_states : List[ EntityState ] ) -> EntityStateType:
+ entity_state_type_list = [ x.entity_state_type for x in entity_states ]
+
+ for priority_entity_state_type in self._entity_state_type_priority_list:
+ if priority_entity_state_type in entity_state_type_list:
+ return priority_entity_state_type
+ continue
+
+ # If no prioritizes state type matches, then fallback to an
+ # arbitrary, but deterministic choice by using all defined values.
+ #
+ for default_entity_state_type in EntityStateType:
+ if default_entity_state_type in entity_state_type_list:
+ return default_entity_state_type
+ continue
+
+ # This code should not really be reachable. Should always match one in fallback case.
+ return None
+
+
+class StatusDisplayStatusViewHelper:
+
+ def get_status_display_data( self ) -> List[ StatusDisplayData ]:
+
+ sensor_response_list_map = SensorResponseManager().get_all_latest_sensor_responses()
+
+ # Since a given EntityState can have zero or more sensors, for each
+ # EntityState, we need to collate all the sensor values to find the
+ # latest status.
+
+ entity_state_sensor_response_list_map = dict()
+ for sensor, sensor_response_list in sensor_response_list_map.items():
+ if sensor.entity_state not in entity_state_sensor_response_list_map:
+ entity_state_sensor_response_list_map[sensor.entity_state] = list()
+ entity_state_sensor_response_list_map[sensor.entity_state].extend( sensor_response_list )
+ continue
+
+ status_display_data_list = list()
+ for entity_state, sensor_response_list in entity_state_sensor_response_list_map.items():
+ sensor_response_list.sort( key = lambda item: item.timestamp, reverse = True )
+ status_display_data = StatusDisplayData(
+ entity_state = entity_state,
+ sensor_response_list = sensor_response_list,
+ )
+ status_display_data_list.append( status_display_data )
+ continue
+
+ return status_display_data_list
diff --git a/src/hi/apps/sense/models.py b/src/hi/apps/sense/models.py
index 8c70cc2a..b50bfc9e 100644
--- a/src/hi/apps/sense/models.py
+++ b/src/hi/apps/sense/models.py
@@ -48,6 +48,10 @@ class Sensor( IntegrationKeyModel ):
self.sensor_type_str = str(sensor_type)
return
+ @property
+ def css_class(self):
+ return f'hi-sensor-{self.id}'
+
class SensorHistory(models.Model):
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index 2b386d7d..1cb0b4e5 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -1,3 +1,4 @@
+from cachetools import TTLCache
import logging
from typing import Dict, List
@@ -41,6 +42,7 @@ class SensorResponseManager( Singleton ):
def __init_singleton__( self ):
self._redis_client = get_redis_client()
self._sensor_history_manager = SensorHistoryManager()
+ self._sensor_cache = TTLCache( maxsize = 1000, ttl = 3600 )
return
def add_latest_sensor_responses( self, sensor_response_list : List[ SensorResponse ] ):
@@ -112,8 +114,9 @@ class SensorResponseManager( Singleton ):
if not cached_list:
continue
sensor_response_list = [ SensorResponse.from_string( x ) for x in cached_list ]
- integration_key = sensor_response_list[0].integration_key
- sensor_response_list_map[integration_key] = sensor_response_list
+ sensor = self._get_sensor( integration_key = sensor_response_list[0].integration_key )
+ if sensor:
+ sensor_response_list_map[sensor] = sensor_response_list
continue
return sensor_response_list_map
@@ -149,3 +152,16 @@ class SensorResponseManager( Singleton ):
def to_sensor_response_list_cache_key( self, integration_key : IntegrationKey ) -> str:
return f'hi.sr.latest.{integration_key}'
+ def _get_sensor( self, integration_key : IntegrationKey ):
+ if integration_key not in self._sensor_cache:
+ try:
+ sensor = Sensor.objects.select_related('entity_state').get(
+ integration_id = integration_key.integration_id,
+ integration_name = integration_key.integration_name,
+ )
+ self._sensor_cache[integration_key] = sensor
+ except Sensor.DoesNotExist:
+ return None
+
+ return self._sensor_cache[integration_key]
+
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index 421a8d92..1eaf379c 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -282,9 +282,10 @@ PIPELINE = {
},
'js_after_content_custom': {
'source_filenames': (
+ 'js/main.js',
'js/svg-utils.js',
+ 'js/watchdog.js',
'js/polling.js',
- 'js/main.js',
'js/edit.js',
'js/edit-dragdrop.js',
'js/svg-icon.js',
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index fe94800a..e05b1c07 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -193,3 +193,19 @@ svg[action-state="scale"] {
svg .highlighted {
filter: drop-shadow(0 0 10px red);
}
+
+g[status="active"] {
+ outline: 2px solid red;
+ filter: drop-shadow(0 0 5px red);
+}
+
+g[status="recent"] {
+ outline: 2px solid orange;
+ filter: drop-shadow(0 0 5px orange);
+}
+
+
+g[status="past"] {
+ outline: 2px solid yellow;
+ filter: drop-shadow(0 0 5px yellow);
+}
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index 2b83865e..ca5a62bc 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -829,12 +829,17 @@ jQuery(function($) {
});
-$(document)
- .ajaxStart(function () {
- $('#antinode-loader').show();
- })
- .ajaxStop(function () {
- $('#antinode-loader').hide();
- });
+// Extend jQuery to allow some requests to suppress the loading image.
+$.ajaxSuppressLoader = false;
+$(document)
+ .ajaxStart(function () {
+ if ( ! $.ajaxSuppressLoader ) {
+ $('#antinode-loader').show();
+ }
+ })
+ .ajaxStop(function () {
+ $('#antinode-loader').hide();
+ });
+
})();
diff --git a/src/hi/static/js/polling.js b/src/hi/static/js/polling.js
index 1166df1e..758c5f5a 100644
--- a/src/hi/static/js/polling.js
+++ b/src/hi/static/js/polling.js
@@ -2,10 +2,106 @@
window.Hi = window.Hi || {};
const HiPolling = {
- pollStates: function() {
- return true;
- }
+ init: function() {
+ startPolling();
+ },
};
window.Hi.polling = HiPolling;
+
+ window.addEventListener('load', function() {
+ HiPolling.init();
+ });
+
+ /*
+ POLLING
+
+ - Periodic polling of server to get status and alerts.
+ */
+
+ const ServerPollingWatchdogType = 'serverPolling';
+ const ServerPollingIntervalMs = 5 * 1000;
+ const ServerPollingUrl = '/api/status';
+ const CssClassUpdateMap = 'cssClassUpdateMap';
+
+ let gPollingTimer = null;
+ let gCssClassElementCache = {};
+
+ function startPolling() {
+ Hi.watchdog.add( ServerPollingWatchdogType,
+ fetchServerResponse,
+ ServerPollingIntervalMs );
+ fetchServerResponse();
+ }
+
+ function fetchServerResponse() {
+ if ( Hi.DEBUG ) { console.log( "Polling server..." ); }
+ clearPollingTimer();
+
+ $.ajaxSuppressLoader = true;
+ $.ajax({
+ type: 'GET',
+ url: ServerPollingUrl,
+
+ complete: function (jqXHR, textStatus) {
+ $.ajaxSuppressLoader = false;
+ },
+ success: function( data, status, xhr ) {
+ handleServerResponse( data, status, xhr );
+ return false;
+ },
+ error: function (xhr, ajaxOptions, thrownError) {
+ console.error( `Server polling error [${xhr.status}] : ${thrownError}` );
+ return false;
+ }
+ });
+ }
+
+ function handleServerResponse( respObj, textStatus, jqXHR ) {
+ try {
+ if ( Hi.DEBUG ) { console.log( "Server response: "+JSON.stringify( respObj)); }
+
+ Hi.watchdog.ok( ServerPollingWatchdogType );
+ clearPollingTimer();
+
+ for ( let cssClass in respObj[CssClassUpdateMap] ) {
+ let elements;
+ if ( cssClass in gCssClassElementCache ) {
+ elements = gCssClassElementCache[cssClass];
+ } else {
+ elements = $(`.${cssClass}`);
+ gCssClassElementCache[cssClass] = elements;
+ }
+ let attrMap = respObj[CssClassUpdateMap][cssClass];
+ for ( let attrName in attrMap ) {
+ let attrValue = attrMap[attrName];
+ elements.each( function() {
+ if (this.hasAttribute(attrName)) {
+ let currentValue = $(this).attr(attrName);
+ if ( attrValue && ( currentValue !== String(attrValue) )) {
+ $(this).attr( attrName, attrValue );
+ }
+ }
+ });
+ }
+ }
+ }
+ catch (e) {
+ console.error( "Exception parsing server response: " + e
+ + " (line="+e.lineNumber+")" );
+ }
+ finally {
+ gPollingTimer = setTimeout( fetchServerResponse,
+ ServerPollingIntervalMs );
+ }
+ }
+
+ function clearPollingTimer() {
+ if ( gPollingTimer ) {
+ clearTimeout( gPollingTimer );
+ gPollingTimer = null;
+ }
+ }
+
+
})();
diff --git a/src/hi/static/js/watchdog.js b/src/hi/static/js/watchdog.js
new file mode 100644
index 00000000..e0d489dd
--- /dev/null
+++ b/src/hi/static/js/watchdog.js
@@ -0,0 +1,57 @@
+(function() {
+
+ window.Hi = window.Hi || {};
+
+ const MODULE_NAME = 'svg-location';
+
+ const HiWatchdog = {
+ add: function( type, initFunction, normalRefreshMs ) {
+ watchdogAdd( type, initFunction, normalRefreshMs );
+ },
+ ok: function( type ) {
+ watchdogOk( type );
+ }
+ };
+
+ window.Hi.watchdog = HiWatchdog;
+
+ /*
+ WATCHDOG
+
+ - Provides backup to ensure periodic background queries keep running.
+ */
+
+ var WatchdogTimers = {};
+ var watchdogInactive = {};
+ var watchdogFunctions = {};
+
+ function watchdogAdd( type, initFunction, normalRefreshMs ) {
+ watchdogInactive[type] = false;
+ watchdogFunctions[type] = initFunction;
+ WatchdogTimers[type] = setInterval( function() { watchdogCheck( type ); },
+ 2 * normalRefreshMs );
+ }
+
+ function watchdogCheck( type ) {
+ if ( ! ( type in watchdogInactive )) {
+ console.error( `No watchdog timer added for "${type}". Cannot check.`);
+ return;
+ }
+
+ if ( Hi.DEBUG ) { console.debug( `Watchdog check: ${type}` ); }
+ if ( watchdogInactive[type] ) {
+ if ( Hi.DEBUG ) { console.debug( `Watchdog detected "${type}" stopped. Restarting.` ); }
+ watchdogFunctions[type]();
+ watchdogInactive[type] = false;
+
+ } else {
+ watchdogInactive[type] = true;
+ }
+ }
+
+ //--------------------
+ function watchdogOk( type ) {
+ watchdogInactive[type] = false;
+ }
+
+})();