Home Information - Your home, your data, organized.
Python
Added client-server timestamp interactions.
Anthony Cassandra3a829aa15da5
diff --git a/src/hi/apps/api/views.py b/src/hi/apps/api/views.pyindex b8ac1431..57f4f5ba 100644--- a/src/hi/apps/api/views.py+++ b/src/hi/apps/api/views.py@@ -1,9 +1,12 @@+from datetime import datetimeimport jsonimport loggingfrom django.http import HttpResponsefrom django.views.generic import View+import hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.config.settings_manager import SettingsManagerfrom hi.apps.monitor.status_display_manager import StatusDisplayManagerfrom hi.apps.monitor.status_display_data import StatusDisplayData@@ -13,9 +16,26 @@ logger = logging.getLogger(__name__)class StatusView( View ):+ ServerStartTimestampAttr = 'startTimestamp'+ ServerTimestampAttr = 'timestamp'+ LastServerTimestampParam = 'lastTimestamp'CssClassUpdateMap = 'cssClassUpdateMap'- def get( self, *args, **kwargs ):+ def get( self, request, *args, **kwargs ):++ last_server_timestamp = request.GET.get( self.LastServerTimestampParam )+ last_server_datetime = None+ if last_server_timestamp:+ try:+ last_server_datetime = datetime.fromisoformat( last_server_timestamp.replace("Z", "+00:00") )+ except (TypeError, ValueError):+ logger.warning( f'Bad client timestamp param "{last_server_timestamp}"' )++ # Make sure to set this before querying monitors so that the client+ # does not get a time that is after some newly arriving data.+ #+ server_start_datetime = SettingsManager().get_server_start_datetime()+ server_datetime = datetimeproxy.now()entity_state_status_data_list = StatusDisplayManager().get_all_entity_state_status_data_list()status_display_data_list = [ StatusDisplayData(x) for x in entity_state_status_data_list ]@@ -28,6 +48,8 @@ class StatusView( View ):continuedata = {+ self.ServerStartTimestampAttr: server_start_datetime.isoformat(),+ self.ServerTimestampAttr: server_datetime.isoformat(),self.CssClassUpdateMap: css_class_update_map,}return HttpResponse(diff --git a/src/hi/apps/common/datetimeproxy.py b/src/hi/apps/common/datetimeproxy.pyindex cebe114c..d4f4d25c 100644--- a/src/hi/apps/common/datetimeproxy.py+++ b/src/hi/apps/common/datetimeproxy.py@@ -48,26 +48,9 @@ def now( tzname = None ):def min( tzname = None ):- # This assumes the Django system time is in UTC !!!- utcmax = timezone.now() - datetime.timedelta( weeks = 500 )- if tzname is None:- return utcmax-- try:- to_zone = pytz.timezone( tzname )- except pytz.exceptions.UnknownTimeZoneError:- logger.warning( "Unrecognized time zone '%s'", tzname )- to_zone = pytz.timezone( DEFAULT_TIME_ZONE_NAME )-- return utcmax.astimezone(to_zone)---def max( tzname = None ):-- # This assumes the Django system time is in UTC !!!- utcmax = timezone.now() + datetime.timedelta( weeks = 500 )+ utcmin = datetime.datetime( 1970, 1, 2, tzinfo = pytz.utc )if tzname is None:- return utcmax+ return utcmintry:to_zone = pytz.timezone( tzname )@@ -75,7 +58,7 @@ def max( tzname = None ):logger.warning( "Unrecognized time zone '%s'", tzname )to_zone = pytz.timezone( DEFAULT_TIME_ZONE_NAME )- return utcmax.astimezone(to_zone)+ return utcmin.astimezone(to_zone)def is_dst( date_time=None ):@@ -377,7 +360,7 @@ def year_to_datetime( date_str : str ):return datetime.datetime.strptime( date_str, "%Y" )-def iso_naive_to_datetime_utc( iso_str : str, tzname : str ):+def iso_naive_to_datetime_utc( iso_str : str, tzname : str = 'UTC' ):to_zone = pytz.timezone( tzname )naive_time = datetime.datetime.fromisoformat( iso_str )aware_time = to_zone.localize(naive_time)diff --git a/src/hi/apps/config/settings_manager.py b/src/hi/apps/config/settings_manager.pyindex dc9ed686..d9b582b0 100644--- a/src/hi/apps/config/settings_manager.py+++ b/src/hi/apps/config/settings_manager.py@@ -1,3 +1,4 @@+from datetime import datetimeimport loggingfrom threading import localfrom typing import List@@ -7,6 +8,7 @@ from django.db.models.signals import post_save, post_deletefrom django.dispatch import receiverfrom hi.apps.attribute.enums import AttributeType+import hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.common.singleton import Singletonfrom .enums import SubsystemType, SubsystemAttributeType@@ -18,6 +20,7 @@ logger = logging.getLogger(__name__)class SettingsManager( Singleton ):def __init_singleton__( self ):+ self._server_start_datetime = datetimeproxy.now()self._subsystem_list = list()self._attribute_value_map = dict()self.reload()@@ -34,6 +37,9 @@ class SettingsManager( Singleton ):continuecontinuereturn++ def get_server_start_datetime( self ) -> datetime:+ return self._server_start_datetimedef get_subsystems(self) -> List[ Subsystem ]:return self._subsystem_listdiff --git a/src/hi/static/js/polling.js b/src/hi/static/js/polling.jsindex 39f78a88..56f1b113 100644--- a/src/hi/static/js/polling.js+++ b/src/hi/static/js/polling.js@@ -22,10 +22,15 @@const ServerPollingWatchdogType = 'serverPolling';const ServerPollingIntervalMs = 5 * 1000;const ServerPollingUrl = '/api/status';+ const ServerStartTimestampAttr = 'startTimestamp';+ const ServerTimestampAttr = 'timestamp';+ const LastServerTimestampParam = 'lastTimestamp';const CssClassUpdateMap = 'cssClassUpdateMap';let gPollingTimer = null;let gCssClassElementCache = {};+ let gLastStartServerDate = null;+ let gLastServerDate = null;function startPolling() {Hi.watchdog.add( ServerPollingWatchdogType,@@ -38,10 +43,16 @@if ( Hi.DEBUG ) { console.log( "Polling server..." ); }clearPollingTimer();+ let url = ServerPollingUrl;+ if ( gLastServerDate ) {+ const lastTimestampString = gLastServerDate.toISOString();+ url += `?${LastServerTimestampParam}=${lastTimestampString}`;+ }+$.ajaxSuppressLoader = true;$.ajax({type: 'GET',- url: ServerPollingUrl,+ url: url,complete: function (jqXHR, textStatus) {$.ajaxSuppressLoader = false;@@ -63,6 +74,12 @@Hi.watchdog.ok( ServerPollingWatchdogType );clearPollingTimer();+ doServerStartTimeCheck( respObj );++ if ( ServerTimestampAttr in respObj ) {+ gLastServerDate = new Date( respObj[ServerTimestampAttr] );+ }+if ( CssClassUpdateMap in respObj ) {handleCssClassUpdates( respObj[CssClassUpdateMap] );}@@ -77,6 +94,21 @@}}+ function doServerStartTimeCheck( respObj ) {+ if ( ServerStartTimestampAttr in respObj ) {+ let startServerDate = new Date( respObj[ServerStartTimestampAttr] );+ if ( gLastStartServerDate ) {+ if ( startServerDate.getTime() != gLastStartServerDate.getTime() ) {+ if ( Hi.DEBUG ) { console.log( "Server restart detected. Reloading page." ); }+ gLastStartServerDate = startServerDate;+ location.reload(true);+ }+ } else {+ gLastStartServerDate = startServerDate;+ }+ }+ }+function handleCssClassUpdates( updateMap ) {for ( let cssClass in updateMap ) {