Home Information - Your home, your data, organized.
Python
Added sensor history with pagination.
Anthony Cassandrad2085d9a3e21
diff --git a/src/hi/apps/common/pagination.py b/src/hi/apps/common/pagination.pyindex 27d68f12..837164d7 100644--- a/src/hi/apps/common/pagination.py+++ b/src/hi/apps/common/pagination.py@@ -22,20 +22,33 @@ class Pagination:next_page_number : bool = Nonehas_pages_before : bool = Falsehas_pages_after : bool = False+ base_url : str = ''+ async_urls : bool = False--def compute_pagination_from_queryset( request : HttpRequest, query_set : QuerySet, page_size : int = 10 ):++def compute_pagination_from_queryset( request : HttpRequest,+ queryset : QuerySet,+ base_url : str = '',+ page_size : int = 10,+ async_urls : bool = False ):try:page_number = int(request.GET.get( 'page', '1' ))except ( ValueError, TypeError ):page_number = 1- item_count = query_set.count()+ item_count = queryset.count()return compute_pagination( page_number = page_number,page_size = page_size,- item_count = item_count )+ item_count = item_count,+ base_url = base_url,+ async_urls = async_urls )-def compute_pagination( page_number : int, page_size : int, item_count : int, paging_window : int = 2 ):+def compute_pagination( page_number : int,+ page_size : int,+ item_count : int,+ base_url : str = '',+ paging_window : int = 2,+ async_urls : bool = False ):pagination = Pagination(page_number = page_number,@@ -43,6 +56,8 @@ def compute_pagination( page_number : int, page_size : int, item_count : int, paitem_count = item_count,page_number_list = [ 1 ],end_offset = item_count - 1,+ base_url = base_url,+ async_urls = async_urls,)if pagination.page_size < 1:diff --git a/src/hi/apps/common/templates/common/panes/pagination.html b/src/hi/apps/common/templates/common/panes/pagination.htmlnew file mode 100644index 00000000..bbdecb50--- /dev/null+++ b/src/hi/apps/common/templates/common/panes/pagination.html@@ -0,0 +1,56 @@+{% load humanize %}+{% load common_template_helpers %}+{% if pagination.required or show_total_items %}+<div class="my-4">+ {% if pagination and show_total_items %}+ <h4 class="mx-auto text-center">{{ pagination.item_count | intcomma }} Results</h4>+ {% endif %}+ {% if pagination.required %}+ <nav aria-label="Race answers">+ {% with params=request.GET.urlencode %}+ <ul class="pagination pagination-lg justify-content-center">+ {% if pagination.has_previous_page %}+ <li class="page-item"><a class="page-link" href="{{ pagination.base_url }}?page={{ pagination.previous_page_number }}" {% if pagination.async_urls %}data-async="true"{%endif %} >+ <span class="d-none d-sm-block" >< Previous</span>+ <span class="d-xs d-sm-none" ><</span>+ </a></li>+ {% else %}+ <li class="page-item disabled"><span class="page-link text-muted">+ <span class="d-none d-sm-block" >< Previous</span>+ <span class="d-xs d-sm-none" ><</span>+ </span></li>+ {% endif %}++ {% if pagination.has_pages_before %}+ <li class="page-item"><a class="page-link" href="{{ pagination.base_url }}?page=1" {% if pagination.async_urls %}data-async="true"{%endif %} >«</a></li>+ {% endif %}++ {% for page_number in pagination.page_number_list %}+ {% if page_number == pagination.page_number %}+ <li class="page-item active"><span class="page-link">{{ page_number }}</span></li>+ {% else %}+ <li class="page-item"><a class="page-link" href="{{ pagination.base_url }}{% pagination_url page_number params %}" {% if pagination.async_urls %}data-async="true"{%endif %} >{{ page_number }}</a></li>+ {% endif %}+ {% endfor %}++ {% if pagination.has_pages_after %}+ <li class="page-item"><a class="page-link" href="{{ pagination.base_url }}?page={{ pagination.page_count }}" {% if pagination.async_urls %}data-async="true"{%endif %} >»</a></li>+ {% endif %}++ {% if pagination.has_next_page %}+ <li class="page-item"><a class="page-link" href="{{ pagination.base_url }}?page={{ pagination.next_page_number }}" {% if pagination.async_urls %}data-async="true"{%endif %} >+ <span class="d-none d-sm-block" >Next ></span>+ <span class="d-xs d-sm-none" >></span>+ </a></li>+ {% else %}+ <li class="page-item disabled"><span class="page-link text-muted">+ <span class="d-none d-sm-block" >Next ></span>+ <span class="d-xs d-sm-none" >></span>+ </span></li>+ {% endif %}+ </ul>+ {% endwith %}+ </nav>+ {% endif %}+</div>+{% endif %}diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.pyindex 08978198..f626dd9c 100644--- a/src/hi/apps/entity/entity_manager.py+++ b/src/hi/apps/entity/entity_manager.py@@ -7,7 +7,7 @@ from hi.apps.common.singleton import Singletonfrom hi.apps.entity.edit.forms import EntityPositionFormfrom hi.apps.location.models import Location, LocationViewfrom hi.apps.location.svg_item_factory import SvgItemFactory-from hi.apps.sense.sensor_response_manager import SensorResponseManager+from hi.apps.sense.sensor_history_manager import SensorHistoryManagerfrom .delegation_manager import DelegationManagerfrom .enums import (@@ -31,6 +31,8 @@ from .transient_models import (class EntityManager(Singleton):+ ENTITY_INFO_SENSOR_HISTORY_ITEM_MAX = 5+def __init_singleton__(self):return@@ -38,8 +40,9 @@ class EntityManager(Singleton):entity : Entity,is_editing : bool ) -> EntityDetailsData:entity_edit_data = EntityEditData( entity = entity )- sensor_response_list_map = SensorResponseManager().get_entity_latest_sensor_responses(+ sensor_history_list_map = SensorHistoryManager().get_latest_entity_sensor_history(entity = entity,+ max_items = self.ENTITY_INFO_SENSOR_HISTORY_ITEM_MAX,)entity_state_list = list(@@ -49,7 +52,7 @@ class EntityManager(Singleton):return EntityInfoData(entity_edit_data = entity_edit_data,- sensor_response_list_map = sensor_response_list_map,+ sensor_history_list_map = sensor_history_list_map,entity_state_list = entity_state_list,principal_entity_list = principal_entity_list,)diff --git a/src/hi/apps/entity/templates/entity/modals/entity_info.html b/src/hi/apps/entity/templates/entity/modals/entity_info.htmlindex 234c1885..d3c452c8 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_info.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_info.html@@ -8,13 +8,9 @@<h5>Sensor Responses</h5><ul>- {% for sensor, sensor_response_list in sensor_response_list_map.items %}+ {% for sensor, sensor_history_list in sensor_history_list_map.items %}<li>Sensor: {{ sensor.name }}- <ul>- {% for sensor_response in sensor_response_list %}- <li>Response: {{ sensor_response.value }} [{{ sensor_response.timestamp }}]</li>- {% endfor %}- </ul>+ {% include "sense/panes/sensor_history_list.html" with sensor_history_list=sensor_history_list show_all_link=True %}</li>{% empty %}<div><em>No sensors</em></div>diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.pyindex 1a729d8a..271651af 100644--- a/src/hi/apps/entity/transient_models.py+++ b/src/hi/apps/entity/transient_models.py@@ -7,8 +7,7 @@ from hi.apps.entity.edit.forms import (EntityPositionForm,EntityAttributeUploadForm,)-from hi.apps.sense.models import Sensor-from hi.apps.sense.transient_models import SensorResponse+from hi.apps.sense.models import Sensor, SensorHistoryfrom .enums import EntityTypefrom .models import Entity, EntityState@@ -71,7 +70,7 @@ class EntityInfoData:""" All the data needed to render the Entity info modal. """entity_edit_data : EntityEditData- sensor_response_list_map : Dict[ Sensor, List[ SensorResponse ] ]+ sensor_history_list_map : Dict[ Sensor, List[ SensorHistory ] ]entity_state_list : List[ EntityState ]principal_entity_list : List[ Entity ]@@ -82,7 +81,7 @@ class EntityInfoData:def to_template_context(self):context = {'entity': self.entity,- 'sensor_response_list_map': self.sensor_response_list_map,+ 'sensor_history_list_map': self.sensor_history_list_map,'entity_state_list': self.entity_state_list,'principal_entity_list': self.principal_entity_list,}diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.pyindex c171a42e..29c98e1e 100644--- a/src/hi/apps/location/location_manager.py+++ b/src/hi/apps/location/location_manager.py@@ -209,11 +209,11 @@ class LocationManager(Singleton):if include_status_display_data:status_display_helper = StatusDisplayLocationHelper( location_view = location_view )- status_entity_state_map = status_display_helper.get_status_entity_state_map(+ status_entity_states_map = status_display_helper.get_status_entity_states_map(entities = displayed_entities,)else:- status_entity_state_map = dict()+ status_entity_states_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_entity_state_map = status_entity_state_map,+ status_entity_states_map = status_entity_states_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.pyindex 9cd1bc37..89d733f2 100644--- a/src/hi/apps/location/location_view_data.py+++ b/src/hi/apps/location/location_view_data.py@@ -22,7 +22,7 @@ class LocationViewData:collection_paths : List[ CollectionPath ]unpositioned_collections : List[ Collection ]orphan_entities : Set[ Entity ]- status_entity_state_map : Dict[ Entity, EntityState ]+ status_entity_states_map : Dict[ Entity, List[ EntityState ]]def __post_init__(self):self._svg_item_factory = SvgItemFactory()@@ -31,10 +31,11 @@ class LocationViewData:def svg_icon_items(self) -> Generator[ SvgIconItem, None, None ]:for entity_position in self.entity_positions:- entity_state = self.status_entity_state_map.get( entity_position.entity )- css_class = ''- if entity_state:- css_class = entity_state.css_class+ entity_states = self.status_entity_states_map.get( entity_position.entity )+ if entity_states:+ css_class = ' '.join([ x.css_class for x in entity_states ])+ else:+ css_class = ''svg_icon_item = self._svg_item_factory.create_svg_icon_item(item = entity_position.entity,position = entity_position,@@ -55,10 +56,11 @@ class LocationViewData:def svg_path_items(self) -> Generator[ SvgPathItem, None, None ]:for entity_path in self.entity_paths:- entity_state = self.status_entity_state_map.get( entity_path.entity )- css_class = ''- if entity_state:- css_class = entity_state.css_class+ entity_states = self.status_entity_states_map.get( entity_path.entity )+ if entity_states:+ css_class = ' '.join([ x.css_class for x in entity_states ])+ else:+ css_class = ''svg_path_item = self._svg_item_factory.create_svg_path_item(item = entity_path.entity,path = entity_path,diff --git a/src/hi/apps/monitor/status_display_helper.py b/src/hi/apps/monitor/status_display_helper.pyindex bba7926c..828e4702 100644--- a/src/hi/apps/monitor/status_display_helper.py+++ b/src/hi/apps/monitor/status_display_helper.py@@ -15,20 +15,20 @@ class StatusDisplayLocationHelper:self._entity_state_type_priority_list = self._location_view_type.entity_state_type_priority_listreturn- def get_status_entity_state_map( self, entities : Set[ Entity ] ) -> Dict[ Entity, EntityState ]:+ def get_status_entity_states_map( self, entities : Set[ Entity ] ) -> Dict[ Entity, EntityState ]:if self._location_view_type == LocationViewType.SUPPRESS:return dict()- entity_to_entity_state_data = dict()+ entity_to_entity_states_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+ entity_states = self.get_status_entity_states( entity = entity )+ if entity_states:+ entity_to_entity_states_data[entity] = entity_statescontinue- return entity_to_entity_state_data+ return entity_to_entity_states_data- def get_status_entity_state( self, entity : Entity ) -> EntityState:+ def get_status_entity_states( self, entity : Entity ) -> List[ EntityState ]:# Delegate entities include will include all their principal entity# states, though any direct state will take precendence@@ -52,13 +52,7 @@ class StatusDisplayLocationHelper:)entity_state_list = entity_state_list_map.get( entity_state_type_for_status )- # TODO: It is possible to have multiple EntityState instances with- # the same EntityStateType, but it is rare in the cases where we- # care about showing dynamic status display changes. If/when it- # matters, we would need to add some reconcilliation logic here for- # picking the entity state to use.- #- return entity_state_list[0]+ return entity_state_listdef _get_entity_state_type_for_status(self,diff --git a/src/hi/apps/sense/sensor_history_manager.py b/src/hi/apps/sense/sensor_history_manager.pyindex b32cb212..ea7e898d 100644--- a/src/hi/apps/sense/sensor_history_manager.py+++ b/src/hi/apps/sense/sensor_history_manager.py@@ -1,10 +1,11 @@from asgiref.sync import sync_to_asyncimport logging-from typing import List+from typing import Dict, Listfrom hi.apps.common.singleton import Singleton+from hi.apps.entity.models import Entity-from .models import SensorHistory+from .models import Sensor, SensorHistoryfrom .transient_models import SensorResponselogger = logging.getLogger(__name__)@@ -22,14 +23,7 @@ class SensorHistoryManager( Singleton ):sensor_history_list = list()for sensor_response in sensor_response_list:if sensor_response.sensor and sensor_response.sensor.persist_history:- sensor_history_list.append(- SensorHistory(- sensor = sensor_response.sensor,- value = sensor_response.value[0:255],- response_datetime = sensor_response.timestamp,- details = sensor_response.details,- )- )+ sensor_history_list.append( sensor_response.to_sensor_history )continueawait self._bulk_create_sensor_history_async( sensor_history_list )@@ -38,3 +32,24 @@ class SensorHistoryManager( Singleton ):async def _bulk_create_sensor_history_async( self, sensor_history_list : List[ SensorHistory ] ):await sync_to_async( SensorHistory.objects.bulk_create)( sensor_history_list )return++ def get_latest_entity_sensor_history( self,+ entity : Entity,+ max_items : int = 5 ) -> Dict[ Sensor, List[ SensorHistory ] ]:++ entity_state_list = list( entity.states.all() )+ 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 ])++ sensor_list = list()+ for entity_state in entity_state_list:+ sensor_list.extend( entity_state.sensors.all() )+ continue++ sensor_history_list_map = dict()+ for sensor in sensor_list:+ sensor_history_list = SensorHistory.objects.filter( sensor = sensor )[0:max_items]+ sensor_history_list_map[sensor] = sensor_history_list+ continue++ return sensor_history_list_mapdiff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.pyindex 1cf88cb5..645ceaa2 100644--- a/src/hi/apps/sense/sensor_response_manager.py+++ b/src/hi/apps/sense/sensor_response_manager.py@@ -5,7 +5,6 @@ from typing import Dict, Listfrom hi.apps.common.redis_client import get_redis_clientfrom hi.apps.common.singleton import Singleton-from hi.apps.entity.models import Entityfrom hi.integrations.core.integration_key import IntegrationKeyfrom .models import Sensor@@ -43,7 +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 )+ self._sensor_cache = TTLCache( maxsize = 1000, ttl = 300 )returnasync def add_latest_sensor_responses( self, sensor_response_list : List[ SensorResponse ] ):@@ -123,34 +122,6 @@ class SensorResponseManager( Singleton ):return sensor_response_list_map- def get_entity_latest_sensor_responses( self, entity : Entity ) -> Dict[ Sensor, List[ SensorResponse ] ]:- """ Maps all sensors to the latest response, but possibly 'None' if not latest response """-- entity_state_list = list( entity.states.all() )- 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 ])-- sensor_list = list()- for entity_state in entity_state_list:- sensor_list.extend( entity_state.sensors.all() )- continue-- list_cache_keys = [ self.to_sensor_response_list_cache_key( x.integration_key ) for x in sensor_list ]-- pipeline = self._redis_client.pipeline()- for list_cache_key in list_cache_keys:- pipeline.lrange( list_cache_key, 0, -1 )- continue- cached_list_list = pipeline.execute()-- sensor_response_list_map = dict()- for sensor, cached_list in zip( sensor_list, cached_list_list ):- sensor_response_list = [ SensorResponse.from_string( x ) for x in cached_list ]- sensor_response_list_map[sensor] = sensor_response_list- continue-- return sensor_response_list_map-def to_sensor_response_list_cache_key( self, integration_key : IntegrationKey ) -> str:return f'hi.sr.latest.{integration_key}'diff --git a/src/hi/apps/sense/templates/sense/modals/sensor_history.html b/src/hi/apps/sense/templates/sense/modals/sensor_history.htmlnew file mode 100644index 00000000..d30b3ad6--- /dev/null+++ b/src/hi/apps/sense/templates/sense/modals/sensor_history.html@@ -0,0 +1,13 @@+{% extends "modals/action_done.html" %}++{% block title_text %}+{{ sensor.name }}+{% endblock %}++{% block body %}+<h5>Sensor History</h5>+{% include "sense/panes/sensor_history_list.html" with sensor_history_list=sensor_history_list %}++{% include "common/panes/pagination.html" with pagination=pagination %}++{% endblock %}diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_history_list.html b/src/hi/apps/sense/templates/sense/panes/sensor_history_list.htmlnew file mode 100644index 00000000..928152c8--- /dev/null+++ b/src/hi/apps/sense/templates/sense/panes/sensor_history_list.html@@ -0,0 +1,17 @@+<ul>+ {% for sensor_history in sensor_history_list %}+ <li>+ Response: {{ sensor_history.value }} [{{ sensor_history.response_datetime }}]+ {% if sensor_history.details %}+ <a href="{% url 'sense_sensor_history_details' id=sensor_history.id %}"+ data-async="true">Details</a>+ {% endif %}+ </li>+ {% empty %}+ <div><em>No sensor history</em></div>+ {% endfor %}+ {% if show_all_link and sensor_history_list %}+ <a href="{% url 'sense_sensor_history' sensor_id=sensor.id %}"+ data-async="true">All History</a>+ {% endif %}+</ul>diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.pyindex 72caa18e..04b83939 100644--- a/src/hi/apps/sense/transient_models.py+++ b/src/hi/apps/sense/transient_models.py@@ -4,7 +4,7 @@ import jsonfrom hi.integrations.core.integration_key import IntegrationKey-from .models import Sensor+from .models import Sensor, SensorHistory@dataclass@@ -27,6 +27,15 @@ class SensorResponse:'details': self.details,}+ def to_sensor_history(self):+ return SensorHistory(+ sensor = self.sensor,+ value = self.value[0:255],+ response_datetime = self.timestamp,+ details = self.details,+ )++@classmethoddef from_string( self, sensor_reading_str : str ) -> 'SensorResponse':sensor_reading_dict = json.loads( sensor_reading_str )@@ -36,3 +45,5 @@ class SensorResponse:timestamp = datetime.fromisoformat( sensor_reading_dict.get('timestamp') ),details = sensor_reading_dict.get('details'),)++diff --git a/src/hi/apps/sense/urls.py b/src/hi/apps/sense/urls.pynew file mode 100644index 00000000..29463f33--- /dev/null+++ b/src/hi/apps/sense/urls.py@@ -0,0 +1,16 @@+from django.urls import re_path++from . import views+++urlpatterns = [++ re_path( r'^sensor/history/(?P<sensor_id>\d+)$',+ views.SensorHistoryView.as_view(),+ name='sense_sensor_history'),++ re_path( r'^sensor/history/details/(?P<id>\d+)$',+ views.SensorHistoryDetailsView.as_view(),+ name='sense_sensor_history_details'),++]diff --git a/src/hi/apps/sense/view_mixin.py b/src/hi/apps/sense/view_mixin.pynew file mode 100644index 00000000..0018275b--- /dev/null+++ b/src/hi/apps/sense/view_mixin.py@@ -0,0 +1,18 @@+from django.core.exceptions import BadRequest+from django.http import Http404++from hi.apps.sense.models import Sensor+++class SenseViewMixin:++ def get_sensor( self, request, *args, **kwargs ) -> Sensor:+ """ Assumes there is a required sensor_id in kwargs """+ try:+ sensor_id = int( kwargs.get( 'sensor_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid sensor id.' )+ try:+ return Sensor.objects.get( id = sensor_id )+ except Sensor.DoesNotExist:+ raise Http404( request )diff --git a/src/hi/apps/sense/views.py b/src/hi/apps/sense/views.pynew file mode 100644index 00000000..f163116c--- /dev/null+++ b/src/hi/apps/sense/views.py@@ -0,0 +1,46 @@+import logging++from django.urls import reverse+from django.views.generic import View++from hi.hi_async_view import HiModalView+from hi.apps.common.pagination import compute_pagination_from_queryset++from .models import SensorHistory+from .view_mixin import SenseViewMixin++logger = logging.getLogger(__name__)+++class SensorHistoryView( HiModalView, SenseViewMixin ):++ SENSOR_HISTORY_PAGE_SIZE = 25++ def get_template_name( self ) -> str:+ return 'sense/modals/sensor_history.html'++ def get( self, request, *args, **kwargs ):++ sensor = self.get_sensor( request, *args, **kwargs )+ base_url = reverse( 'sense_sensor_history', kwargs = { 'sensor_id': sensor.id } )++ queryset = SensorHistory.objects.filter( sensor = sensor )+ pagination = compute_pagination_from_queryset( request = request,+ queryset = queryset,+ base_url = base_url,+ page_size = self.SENSOR_HISTORY_PAGE_SIZE,+ async_urls = True )+ sensor_history_list = queryset[pagination.start_offset:pagination.end_offset + 1]++ context = {+ 'sensor': sensor,+ 'sensor_history_list': sensor_history_list,+ 'pagination': pagination,+ }+ return self.modal_response( request, context )+++class SensorHistoryDetailsView( View, SenseViewMixin ):++ def get(self, request, *args, **kwargs):+ passdiff --git a/src/hi/urls.py b/src/hi/urls.pyindex 011f987b..9083a52d 100644--- a/src/hi/urls.py+++ b/src/hi/urls.py@@ -34,6 +34,7 @@ urlpatterns = [re_path( r'^location/', include('hi.apps.location.urls' )),re_path( r'^entity/', include('hi.apps.entity.urls' )),re_path( r'^collection/', include('hi.apps.collection.urls' )),+ re_path( r'^sense/', include('hi.apps.sense.urls' )),# Custom error pagesre_path( r'^400.html$', views.bad_request_response, name='bad_request' ),