Skip to content

Home Information - Your home, your data, organized.

Python

Have simulator controls for setting state implemented.

Anthony Cassandraf6ec66fdbf1d
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index f2782db7..d452102c 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -117,10 +117,10 @@ class EntityStateType(LabeledEnum):
def controller_template_name(self):
"""
- Template used to render a sensor's value for this state. Create the
+ Template used to render a controllers for this state. Create the
template at the given location to define a state-specific rendering, else
it will fallback to the default template of
- "entity/panes/sensor_value_default.html"
+ "entity/panes/controller_value_default.html"
"""
return f'control/panes/controller_{self.name.lower()}.html'
diff --git a/src/hi/simulator/admin.py b/src/hi/simulator/admin.py
index 36cce8ed..12c5153f 100644
--- a/src/hi/simulator/admin.py
+++ b/src/hi/simulator/admin.py
@@ -12,7 +12,7 @@ class DbSimEntityAdmin(admin.ModelAdmin):
'sim_profile',
'simulator_id',
'entity_fields_class_id',
- 'entity_type_str',
+ 'sim_entity_type_str',
'sim_entity_fields_json',
'updated_datetime',
'created_datetime',
diff --git a/src/hi/simulator/base_models.py b/src/hi/simulator/base_models.py
index 269fad6d..530f88a4 100644
--- a/src/hi/simulator/base_models.py
+++ b/src/hi/simulator/base_models.py
@@ -1,8 +1,8 @@
from dataclasses import dataclass, fields, MISSING
from datetime import datetime
-from typing import Any, Dict, List, Type
+from typing import Any, Dict, List, Tuple, Type
-from hi.apps.entity.enums import EntityStateType, EntityType
+from .enums import SimEntityType, SimStateType
@dataclass( frozen = True )
@@ -18,7 +18,9 @@ class SimEntityFields:
@classmethod
def class_id(cls) -> str:
- return f'{cls.__module__}.{cls.__qualname__}'
+ dotted_path = f'{cls.__module__}.{cls.__qualname__}'
+ parts = dotted_path.split('.')
+ return '.'.join( reversed( parts ))
def to_json_dict(self) -> Dict[ str, Any ]:
"""
@@ -81,14 +83,42 @@ class SimState:
SimState definitions and instances are not persisted in the database.
"""
- sim_entity_fields : SimEntityFields # Will be provided by SimulatorManager when creating instances.
- entity_state_type : EntityStateType # Subclasses should provide a default value for this.
- value_range : str = None # Subclasses can override to provide value range hints
- value : Any = None # Subclasses can override to provide a default value
+
+ # These fields are provided by SimulatorManager when creating instances.
+ simulator_id : str
+ sim_entity_id : int
+ sim_state_idx : int
+ sim_entity_fields : SimEntityFields
+
+ # Subclasses must provide a default value for these.
+ sim_state_type : SimStateType
+
+ # Subclasses may provide a default value for this.
+ value : Any = None
@property
def name(self):
return self.sim_entity_fields.name
+
+ def set_value_from_string( self, value_str : str ):
+ """ Subclasses should override this is the value is not a string and needs conversion. """
+ self.value = value_str
+ return
+
+ @property
+ def min_value(self) -> Any:
+ """ Subclasses can override this to define the minimum valid value """
+ return None
+
+ @property
+ def max_value(self) -> Any:
+ """ Subclasses can override this to define the maximum valid value """
+ return None
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ]]:
+ """ Subclasses using SimStateType.DISCRETE should override this to provide the valid values. """
+ return list()
@dataclass
@@ -101,7 +131,7 @@ class SimEntityDefinition:
"""
class_label : str
- entity_type : EntityType
+ sim_entity_type : SimEntityType
sim_entity_fields_class : Type[ SimEntityFields ]
sim_state_class_list : List[ Type[ SimState ]]
diff --git a/src/hi/simulator/enums.py b/src/hi/simulator/enums.py
new file mode 100644
index 00000000..41e54df5
--- /dev/null
+++ b/src/hi/simulator/enums.py
@@ -0,0 +1,107 @@
+from hi.apps.common.enums import LabeledEnum
+
+
+class SimStateType(LabeledEnum):
+
+ # General types
+ DISCRETE = ( 'Discrete' , 'Single value, fixed set of possible values' )
+ CONTINUOUS = ( 'Continuous' , 'For single value with a float type value' )
+
+ # Specific types
+ AIR_PRESSURE = ( 'Air Pressure' , '' )
+ BANDWIDTH_USAGE = ( 'Bandwidth Usage' , '' )
+ CONNECTIVITY = ( 'Connectivity' , '' )
+ DATETIME = ( 'Date/Time' , '' )
+ ELECTRIC_USAGE = ( 'Electric Usage' , '' )
+ HIGH_LOW = ( 'High/Low' , '' )
+ HUMIDITY = ( 'Humidity' , '' )
+ LIGHT_LEVEL = ( 'Light Level' , '' )
+ MOISTURE = ( 'Moisture' , '' )
+ MOVEMENT = ( 'Movement' , '' )
+ ON_OFF = ( 'On/Off' , '' )
+ OPEN_CLOSE = ( 'Open/Close' , '' )
+ PRESENCE = ( 'Presence' , '' )
+ SOUND_LEVEL = ( 'Sound Level' , '' )
+ TEMPERATURE = ( 'Temperature' , '' )
+ VIDEO_STREAM = ( 'Video Stream' , '' )
+ WATER_FLOW = ( 'Water Flow' , '' )
+ WIND_SPEED = ( 'Wind Speed' , '' )
+
+ @classmethod
+ def default(cls):
+ return cls.DISCRETE
+
+ def template_name(self):
+ """
+ Template used to render the simulator control for this state. Create the
+ template at the given location to define a state-specific rendering, else
+ it will fallback to the default template of
+ "simulator/panes/sim_control_default.html"
+ """
+ return f'simulator/panes/sim_control_{self.name.lower()}.html'
+
+
+class SimEntityType(LabeledEnum):
+
+ AIR_CONDITIONER = ( 'Air Conditioner', '' )
+ APPLIANCE = ( 'Appliance', '' )
+ AREA = ( 'Area', '' )
+ AUDIO_AMPLIFIER = ( 'Audio Amplifier', '' )
+ AUDIO_PLAYER = ( 'Audio Player', '' )
+ AUTOMOBILE = ( 'Automobile', '' )
+ BAROMETER = ( 'Barometer', '' )
+ CAMERA = ( 'Camera', '' )
+ COMPUTER = ( 'Computer', '' )
+ CONSUMABLE = ( 'Consumable', '' )
+ CONTROL_WIRE = ( 'Control Wire', '' )
+ DISPLAY = ( 'Display', '' )
+ DOOR = ( 'Door', '' )
+ DOOR_LOCK = ( 'Door Lock', '' ) # Controls doors
+ ELECTRICAL_OUTLET = ( 'Electrical Outlet', '' )
+ ELECTRICY_METER = ( 'Electric Meter', '' )
+ ELECTRIC_PANEL = ( 'Electric Panel', '' )
+ ELECTRIC_WIRE = ( 'Electric Wire', '' )
+ FURNITURE = ( 'Furniture', '' )
+ HEALTHCHECK = ( 'Healthcheck', '' )
+ HEATER = ( 'Heater', '' ) # Controls area
+ HVAC_AIR_HANDLER = ( 'HVAC Air Handler', '' ) # Controls area
+ HVAC_CONDENSER = ( 'HVAC Condenser', '' ) # Controls area
+ HVAC_MIN_SPLIT = ( 'HVAC Mini-split', '' ) # Controls area
+ HUMIDIFIER = ( 'Humidifier', '' ) # Controls area
+ HYGROMETER = ( 'Hygrometer', '' )
+ LIGHT = ( 'Light', '' )
+ LIGHT_SENSOR = ( 'Light Sensor', '' )
+ MOTION_SENSOR = ( 'Motion Sensor', '' )
+ NETWORK_SWITCH = ( 'Network Switch', '' )
+ OPEN_CLOSE_SENSOR = ( 'Open/Close Sensor', '' )
+ OTHER = ( 'Other', '' ) # Will use generic visual element
+ PRESENCE_SENSOR = ( 'Presence Sensor', '' )
+ SEWER_LINE = ( 'Sewer Wire', '' )
+ SHOWER = ( 'Shower', '' )
+ SINK = ( 'Sink', '' )
+ SERVICE = ( 'Service' , '' )
+ SPEAKER = ( 'Speaker', '' )
+ SPINKLER_CONTROLLER = ( 'Spinkler Controller', '' )
+ SPINKLER_VALVE = ( 'Spinkler Valve', '' ) # Controls sprinkler heads
+ SPRINKLER_HEAD = ( 'Sprinkler Head', '' )
+ SPRINKLER_WIRE = ( 'Sprinkler Wire', '' )
+ TELECOM_BOX = ( 'Telecom Box', '' )
+ TELECOM_WIRE = ( 'Telecom Wire', '' )
+ THERMOMETER = ( 'Thermometer', '' )
+ THERMOSTAT = ( 'Thermostat', '' )
+ TIME_SOURCE = ( 'Time Source', '' )
+ TOILET = ( 'Toilet', '' )
+ TOOL = ( 'Tool', '' )
+ VIDEO_PLAYER = ( 'Video Player', '' )
+ WALL_SWITCH = ( 'Wall Switch', '' )
+ WASTE_PIPE = ( 'Waste Pipe', '' )
+ WATER_HEATER = ( 'Water Heater', '' )
+ WATER_LINE = ( 'Water Line', '' )
+ WATER_METER = ( 'Water Meter', '' )
+ WATER_SHUTOFF_VALVE = ( 'Water Shutoff Valve', '' )
+ WEATHER_STATION = ( 'Weather Station', '' )
+ WINDOW = ( 'Window', '' )
+
+ @classmethod
+ def default(cls):
+ return cls.OTHER
diff --git a/src/hi/simulator/migrations/0013_rename_entity_type_str_dbsimentity_sim_entity_type_str.py b/src/hi/simulator/migrations/0013_rename_entity_type_str_dbsimentity_sim_entity_type_str.py
new file mode 100644
index 00000000..ed796b13
--- /dev/null
+++ b/src/hi/simulator/migrations/0013_rename_entity_type_str_dbsimentity_sim_entity_type_str.py
@@ -0,0 +1,18 @@
+# Generated by Django 4.2.15 on 2024-12-29 16:08
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("simulator", "0012_alter_dbsimentity_entity_fields_class_id"),
+ ]
+
+ operations = [
+ migrations.RenameField(
+ model_name="dbsimentity",
+ old_name="entity_type_str",
+ new_name="sim_entity_type_str",
+ ),
+ ]
diff --git a/src/hi/simulator/migrations/0014_alter_dbsimentity_sim_entity_fields_json.py b/src/hi/simulator/migrations/0014_alter_dbsimentity_sim_entity_fields_json.py
new file mode 100644
index 00000000..6a43aaa1
--- /dev/null
+++ b/src/hi/simulator/migrations/0014_alter_dbsimentity_sim_entity_fields_json.py
@@ -0,0 +1,18 @@
+# Generated by Django 4.2.15 on 2024-12-29 16:09
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("simulator", "0013_rename_entity_type_str_dbsimentity_sim_entity_type_str"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="dbsimentity",
+ name="sim_entity_fields_json",
+ field=models.JSONField(default=dict, verbose_name="Entity Fields"),
+ ),
+ ]
diff --git a/src/hi/simulator/models.py b/src/hi/simulator/models.py
index 2bc9fcc8..7fbb6b16 100644
--- a/src/hi/simulator/models.py
+++ b/src/hi/simulator/models.py
@@ -1,7 +1,7 @@
from django.db import models
from django.utils.timezone import now
-from hi.apps.entity.enums import EntityType
+from .enums import SimEntityType
class SimProfile(models.Model):
@@ -49,13 +49,13 @@ class DbSimEntity(models.Model):
max_length = 255,
null = False, blank = False,
)
- entity_type_str = models.CharField(
+ sim_entity_type_str = models.CharField(
'Entity Type',
max_length = 32,
null = False, blank = False,
)
sim_entity_fields_json = models.JSONField(
- 'Sim Entity Fields',
+ 'Entity Fields',
default = dict,
null = False, blank = False,
)
@@ -74,10 +74,10 @@ class DbSimEntity(models.Model):
verbose_name_plural = 'Simulator Entities'
@property
- def entity_type(self) -> EntityType:
- return EntityType.from_name_safe( self.entity_type_str )
+ def sim_entity_type(self) -> SimEntityType:
+ return SimEntityType.from_name_safe( self.sim_entity_type_str )
- @entity_type.setter
- def entity_type( self, entity_type : EntityType ):
- self.entity_type_str = str(entity_type)
+ @sim_entity_type.setter
+ def sim_entity_type( self, sim_entity_type : SimEntityType ):
+ self.sim_entity_type_str = str(sim_entity_type)
return
diff --git a/src/hi/simulator/services/hass/api/views.py b/src/hi/simulator/services/hass/api/views.py
index 75443067..917a8b11 100644
--- a/src/hi/simulator/services/hass/api/views.py
+++ b/src/hi/simulator/services/hass/api/views.py
@@ -1,7 +1,7 @@
from django.http import JsonResponse
from django.views.generic import View
-from hi.simulator.services.hass.transient_models import HassInsteonLightSwitch
+from hi.simulator.services.hass.sim_models import HassInsteonLightSwitch
class StatesView( View ):
diff --git a/src/hi/simulator/services/hass/transient_models.py b/src/hi/simulator/services/hass/sim_models.py
similarity index 82%
rename from src/hi/simulator/services/hass/transient_models.py
rename to src/hi/simulator/services/hass/sim_models.py
index d096dc73..2b9dc5db 100644
--- a/src/hi/simulator/services/hass/transient_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -2,12 +2,12 @@ import base64
from dataclasses import dataclass
import os
import time
-from typing import Dict
+from typing import Dict, List, Tuple
import hi.apps.common.datetimeproxy as datetimeproxy
-from hi.apps.entity.enums import EntityStateType, EntityType
from hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinition
+from hi.simulator.enums import SimEntityType, SimStateType
@dataclass
@@ -73,7 +73,7 @@ class HassInsteonSimEntityFields( SimEntityFields ):
@dataclass
-class HassInsteonState( SimState ):
+class HassInsteonState( HassState ):
""" Base class for all HAss Insteon device states """
sim_entity_fields : HassInsteonSimEntityFields
@@ -92,7 +92,11 @@ class HassInsteonLightSwitchFields( HassInsteonSimEntityFields ):
class HassInsteonLightSwitchLightState( HassInsteonState ):
sim_entity_fields : HassInsteonLightSwitchFields
- entity_state_type : EntityStateType = EntityStateType.ON_OFF
+ sim_state_type : SimStateType = SimStateType.ON_OFF
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Switch'
@property
def entity_id(self):
@@ -117,8 +121,12 @@ class HassInsteonLightSwitchLightState( HassInsteonState ):
class HassInsteonLightSwitchColorState( HassInsteonState ):
sim_entity_fields : HassInsteonLightSwitchFields
- entity_state_type : EntityStateType = EntityStateType.ON_OFF
-
+ sim_state_type : SimStateType = SimStateType.ON_OFF
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Color'
+
@property
def entity_id(self):
return 'light.switchlinc_relay_%s' % self.insteon_address.replace( '.', '_' )
@@ -149,8 +157,12 @@ class HassInsteonMotionDetectorFields( HassInsteonSimEntityFields ):
class HassInsteonMotionDetectorMotionState( HassInsteonState ):
sim_entity_fields : HassInsteonMotionDetectorFields
- entity_state_type : EntityStateType = EntityStateType.MOVEMENT
+ sim_state_type : SimStateType = SimStateType.MOVEMENT
+ @property
+ def name(self):
+ return f'{self.entity_name} Motion'
+
@property
def entity_id(self):
return 'binary_sensor.motion_sensor_%s_motion' % self.insteon_address.replace( '.', '_' )
@@ -159,7 +171,7 @@ class HassInsteonMotionDetectorMotionState( HassInsteonState ):
def attributes(self) -> Dict[ str, str ]:
return {
"device_class": "motion",
- 'friendly_name': f'{self.entity_name} Motion',
+ 'friendly_name': self.name,
"insteon_address": self.insteon_address,
"insteon_group": 1,
}
@@ -174,8 +186,12 @@ class HassInsteonMotionDetectorMotionState( HassInsteonState ):
class HassInsteonMotionDetectorLightState( HassInsteonState ):
sim_entity_fields : HassInsteonMotionDetectorFields
- entity_state_type : EntityStateType = EntityStateType.ON_OFF
+ sim_state_type : SimStateType = SimStateType.ON_OFF
+ @property
+ def name(self):
+ return f'{self.entity_name} Light'
+
@property
def entity_id(self):
return 'binary_sensor.motion_sensor_%s_light' % self.insteon_address.replace( '.', '_' )
@@ -184,7 +200,7 @@ class HassInsteonMotionDetectorLightState( HassInsteonState ):
def attributes(self) -> Dict[ str, str ]:
return {
"device_class": "light",
- 'friendly_name': f'{self.entity_name} Light',
+ 'friendly_name': self.name,
"insteon_address": self.insteon_address,
"insteon_group": 1,
}
@@ -199,7 +215,19 @@ class HassInsteonMotionDetectorLightState( HassInsteonState ):
class HassInsteonMotionDetectorBatteryState( HassInsteonState ):
sim_entity_fields : HassInsteonMotionDetectorFields
- entity_state_type : EntityStateType = EntityStateType.DISCRETE
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ value : str = 'High'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Battery'
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ]]:
+ return [
+ ( 'Low' , 'Low' ),
+ ( 'High' , 'High' ),
+ ]
@property
def entity_id(self):
@@ -209,7 +237,7 @@ class HassInsteonMotionDetectorBatteryState( HassInsteonState ):
def attributes(self) -> Dict[ str, str ]:
return {
"device_class": "battery",
- 'friendly_name': f'{self.entity_name} Battery',
+ 'friendly_name': self.name,
"insteon_address": self.insteon_address,
"insteon_group": 1,
}
@@ -229,7 +257,7 @@ class HassInsteonOpenCloseSensorFields( HassInsteonSimEntityFields ):
class HassInsteonOpenCloseSensorState( HassInsteonState ):
sim_entity_fields : HassInsteonOpenCloseSensorFields
- entity_state_type : EntityStateType = EntityStateType.OPEN_CLOSE
+ sim_state_type : SimStateType = SimStateType.OPEN_CLOSE
@property
def entity_id(self):
@@ -254,7 +282,7 @@ class HassInsteonOpenCloseSensorState( HassInsteonState ):
HASS_SIM_ENTITY_DEFINITION_LIST = [
SimEntityDefinition(
class_label = 'Insteon Light Switch',
- entity_type = EntityType.LIGHT,
+ sim_entity_type = SimEntityType.LIGHT,
sim_entity_fields_class = HassInsteonLightSwitchFields,
sim_state_class_list = [
HassInsteonLightSwitchLightState,
@@ -263,7 +291,7 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [
),
SimEntityDefinition(
class_label = 'Insteon Motion Detector',
- entity_type = EntityType.MOTION_SENSOR,
+ sim_entity_type = SimEntityType.MOTION_SENSOR,
sim_entity_fields_class = HassInsteonMotionDetectorFields,
sim_state_class_list = [
HassInsteonMotionDetectorMotionState,
@@ -273,7 +301,7 @@ HASS_SIM_ENTITY_DEFINITION_LIST = [
),
SimEntityDefinition(
class_label = 'Insteon Open/Close Sensor',
- entity_type = EntityType.OPEN_CLOSE_SENSOR,
+ sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,
sim_entity_fields_class = HassInsteonOpenCloseSensorFields,
sim_state_class_list = [
HassInsteonOpenCloseSensorState,
diff --git a/src/hi/simulator/services/hass/simulator.py b/src/hi/simulator/services/hass/simulator.py
index 7d0a76c8..5a8a99ad 100644
--- a/src/hi/simulator/services/hass/simulator.py
+++ b/src/hi/simulator/services/hass/simulator.py
@@ -3,7 +3,7 @@ from typing import List
from hi.simulator.simulator import Simulator
from hi.simulator.base_models import SimEntityDefinition
-from .transient_models import HASS_SIM_ENTITY_DEFINITION_LIST
+from .sim_models import HASS_SIM_ENTITY_DEFINITION_LIST
class HassSimulator( Simulator ):
@@ -19,8 +19,3 @@ class HassSimulator( Simulator ):
@property
def sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:
return HASS_SIM_ENTITY_DEFINITION_LIST
-
- def set_sim_state( self, device_id : int, value : str ):
- raise NotImplementedError('Subclasses must override this method.')
-
-
diff --git a/src/hi/simulator/services/zoneminder/api/views.py b/src/hi/simulator/services/zoneminder/api/views.py
index fe9ebf99..c8322382 100644
--- a/src/hi/simulator/services/zoneminder/api/views.py
+++ b/src/hi/simulator/services/zoneminder/api/views.py
@@ -7,7 +7,7 @@ from django.views.generic import View
import hi.apps.common.datetimeproxy as datetimeproxy
-from hi.simulator.services.zoneminder.transient_models import (
+from hi.simulator.services.zoneminder.sim_models import (
ZmEvent,
ZmMonitor,
ZmPagination,
diff --git a/src/hi/simulator/services/zoneminder/transient_models.py b/src/hi/simulator/services/zoneminder/sim_models.py
similarity index 90%
rename from src/hi/simulator/services/zoneminder/transient_models.py
rename to src/hi/simulator/services/zoneminder/sim_models.py
index b339f5bb..c3f02b06 100644
--- a/src/hi/simulator/services/zoneminder/transient_models.py
+++ b/src/hi/simulator/services/zoneminder/sim_models.py
@@ -1,11 +1,11 @@
from dataclasses import dataclass
from datetime import datetime
-from typing import List
+from typing import List, Tuple
import hi.apps.common.datetimeproxy as datetimeproxy
-from hi.apps.entity.enums import EntityType, EntityStateType
from hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinition
+from hi.simulator.enums import SimEntityType, SimStateType
@dataclass( frozen = True )
@@ -17,13 +17,21 @@ class ZmServerSimEntityFields( SimEntityFields ):
class ZmServerRunState( SimState ):
sim_entity_fields : ZmServerSimEntityFields
- entity_state_type : EntityStateType = EntityStateType.DISCRETE
- value : str = 'Home'
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ value : str = 'Day'
@property
def name(self):
return 'ZoneMinder Run State'
+ @property
+ def choices(self) -> List[ Tuple[ str, str ]]:
+ return [
+ ( 'default' , 'default' ),
+ ( 'Day' , 'Day' ),
+ ( 'Night' , 'Night' ),
+ ]
+
@dataclass( frozen = True )
class ZmMonitorSimEntityFields( SimEntityFields ):
@@ -155,8 +163,19 @@ class ZmMonitorSimEntityFields( SimEntityFields ):
class ZmMonitorFunctionState( SimState ):
sim_entity_fields : ZmMonitorSimEntityFields
- entity_state_type : EntityStateType = EntityStateType.DISCRETE
- value : str = 'Modect'
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ value : str = 'Modect'
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ]]:
+ return [
+ ( 'None' , 'None' ),
+ ( 'Monitor' , 'Monitor' ),
+ ( 'Modect' , 'Modect' ),
+ ( 'Record' , 'Record' ),
+ ( 'Mocord' , 'Mocord' ),
+ ( 'Nodect' , 'Nodect' ),
+ ]
@property
def name(self):
@@ -167,7 +186,7 @@ class ZmMonitorFunctionState( SimState ):
class ZmMonitorMotionState( SimState ):
sim_entity_fields : ZmMonitorSimEntityFields
- entity_state_type : EntityStateType = EntityStateType.MOVEMENT
+ sim_state_type : SimStateType = SimStateType.MOVEMENT
@property
def name(self):
@@ -205,6 +224,7 @@ class ZmState:
'IsActive': is_active_str,
},
}
+
@dataclass
@@ -300,7 +320,7 @@ class ZmPagination:
ZONEMINDER_SIM_ENTITY_DEFINITION_LIST = [
SimEntityDefinition(
class_label = 'Camera (monitor)',
- entity_type = EntityType.MOTION_SENSOR,
+ sim_entity_type = SimEntityType.MOTION_SENSOR,
sim_entity_fields_class = ZmMonitorSimEntityFields,
sim_state_class_list = [
ZmMonitorFunctionState,
@@ -309,7 +329,7 @@ ZONEMINDER_SIM_ENTITY_DEFINITION_LIST = [
),
SimEntityDefinition(
class_label = 'ZoneMinder Service',
- entity_type = EntityType.SERVICE,
+ sim_entity_type = SimEntityType.SERVICE,
sim_entity_fields_class = ZmServerSimEntityFields,
sim_state_class_list = [
ZmServerRunState,
diff --git a/src/hi/simulator/services/zoneminder/simulator.py b/src/hi/simulator/services/zoneminder/simulator.py
index 60f53d0e..1e7f7c90 100644
--- a/src/hi/simulator/services/zoneminder/simulator.py
+++ b/src/hi/simulator/services/zoneminder/simulator.py
@@ -3,7 +3,7 @@ from typing import List
from hi.simulator.base_models import SimEntityDefinition
from hi.simulator.simulator import Simulator
-from .transient_models import ZONEMINDER_SIM_ENTITY_DEFINITION_LIST
+from .sim_models import ZONEMINDER_SIM_ENTITY_DEFINITION_LIST
class ZoneMinderSimulator( Simulator ):
@@ -19,7 +19,4 @@ class ZoneMinderSimulator( Simulator ):
@property
def sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:
return ZONEMINDER_SIM_ENTITY_DEFINITION_LIST
-
- def set_sim_state( self, device_id : int, value : str ):
- raise NotImplementedError('Subclasses must override this method.')
diff --git a/src/hi/simulator/sim_entity.py b/src/hi/simulator/sim_entity.py
index f5e0c5d8..2a2f77de 100644
--- a/src/hi/simulator/sim_entity.py
+++ b/src/hi/simulator/sim_entity.py
@@ -22,10 +22,14 @@ class SimEntity:
self._sim_entity_fields = SimEntityFieldsSubclass.from_json_dict(
self.db_sim_entity.sim_entity_fields_json,
)
-
self._sim_state_list = list()
- for SimStateSubclass in self.sim_entity_definition.sim_state_class_list:
- sim_state = SimStateSubclass( sim_entity_fields = self._sim_entity_fields )
+ for sim_state_idx, SimStateSubclass in enumerate( self.sim_entity_definition.sim_state_class_list ):
+ sim_state = SimStateSubclass(
+ simulator_id = self.db_sim_entity.simulator_id,
+ sim_entity_id = self.db_sim_entity.id,
+ sim_state_idx = sim_state_idx,
+ sim_entity_fields = self._sim_entity_fields,
+ )
self._sim_state_list.append( sim_state )
continue
return
@@ -47,9 +51,17 @@ class SimEntity:
def sim_state_list(self) -> List[ SimState ]:
return self._sim_state_list
+ def set_sim_state( self,
+ sim_state_idx : int,
+ value_str : str ) -> SimState:
+ sim_state = self._sim_state_list[sim_state_idx]
+ sim_state.set_value_from_string( value_str = value_str )
+ return sim_state
+
def copy_state_values( self, other_sim_entity : 'SimEntity' ):
for self_sim_state, other_sim_state in zip( self.sim_state_list,
other_sim_entity.sim_state_list ):
+ assert self_sim_state.sim_state_idx == other_sim_state.sim_state_idx
self_sim_state.value = other_sim_state.value
continue
return
diff --git a/src/hi/simulator/simulator.py b/src/hi/simulator/simulator.py
index b21e706c..64b46263 100644
--- a/src/hi/simulator/simulator.py
+++ b/src/hi/simulator/simulator.py
@@ -2,7 +2,7 @@ from typing import Dict, List
from hi.apps.common.singleton import Singleton
-from .base_models import SimEntityDefinition
+from .base_models import SimEntityDefinition, SimEntityFields, SimState
from .sim_entity import SimEntity
@@ -17,7 +17,7 @@ class Simulator( Singleton ):
"""
def __init_singleton__( self ):
- self._initialize()
+ self.initialize()
return
@property
@@ -53,10 +53,19 @@ class Simulator( Singleton ):
self._sim_entity_map : Dict[ id, SimEntity ] = dict()
return
+ def validate_sim_entity_fields( self, sim_entity_fields : SimEntityFields ):
+ """
+ Subclasses should override this if there are additional validation
+ checks needed before adding a SimEntity. This is called
+ before persisting the data so can raise SimEntityValidationError if
+ there are any validation issue.
+ """
+ return
+
def validate_sim_entity( self, sim_entity : SimEntity ):
"""
Subclasses should override this if there are additional validation
- checks needed before adding or updating a SimEntity. This is called
+ checks needed before updating a SimEntity. This is called
before persisting the data so can raise SimEntityValidationError if
there are any validation issue.
"""
@@ -72,3 +81,17 @@ class Simulator( Singleton ):
def remove_sim_entity_by_id( self, sim_entity_id : int ):
del self._sim_entity_map[sim_entity_id]
return
+
+ def set_sim_state( self,
+ sim_entity_id : int,
+ sim_state_idx : int,
+ value_str : str ) -> SimState:
+ sim_entity = self._sim_entity_map[sim_entity_id]
+ return sim_entity.set_sim_state(
+ sim_state_idx = sim_state_idx,
+ value_str = value_str,
+ )
+
+
+
+
diff --git a/src/hi/simulator/simulator_manager.py b/src/hi/simulator/simulator_manager.py
index ee9c49ca..021d1094 100644
--- a/src/hi/simulator/simulator_manager.py
+++ b/src/hi/simulator/simulator_manager.py
@@ -77,16 +77,16 @@ class SimulatorManager( Singleton ):
sim_profile = self.current_sim_profile,
simulator_id = simulator.id,
entity_fields_class_id = sim_entity_definition.class_id,
- entity_type = sim_entity_definition.entity_type,
+ sim_entity_type = sim_entity_definition.sim_entity_type,
sim_entity_fields_json = sim_entity_fields.to_json_dict(),
)
+ simulator.validate_sim_entity_fields( sim_entity_fields = sim_entity_fields )
+ db_sim_entity.save()
sim_entity = SimEntity(
db_sim_entity = db_sim_entity,
sim_entity_definition = sim_entity_definition,
)
- simulator.validate_sim_entity( sim_entity = sim_entity )
- db_sim_entity.save()
simulator.add_sim_entity( sim_entity = sim_entity )
finally:
@@ -123,7 +123,7 @@ class SimulatorManager( Singleton ):
simulator.remove_sim_entity_by_id( sim_entity_id = db_sim_entity.id )
db_sim_entity.delete()
return
-
+
async def initialize(self) -> None:
self._data_lock.acquire()
try:
diff --git a/src/hi/simulator/templates/simulator/pages/base.html b/src/hi/simulator/templates/simulator/pages/base.html
index bcc16b74..7368e9f9 100644
--- a/src/hi/simulator/templates/simulator/pages/base.html
+++ b/src/hi/simulator/templates/simulator/pages/base.html
@@ -14,19 +14,18 @@
<link rel="icon" type="image/png" href="{% static 'img/hi-icon-128x128.png' %}" sizes="128x128">
<link rel="icon" type="image/png" href="{% static 'img/hi-icon-196x196.png' %}" sizes="196x196">
<link href="{% static 'bootstrap/css/bootstrap.css' %}" rel="stylesheet" type="text/css" media="all" />
- <link href="{% static 'css/main.css" rel="stylesheet' %}" type="text/css" media="all" />
+ <link href="{% static 'css/simulator.css' %}" rel="stylesheet" type="text/css" media="all" />
</head>
<body>
<script type="text/javascript" src="{% static 'js/jquery-3.7.0.min.js' %}" charset="utf-8"></script>
<script type="text/javascript" src="{% static 'js/cookie.js' %}" charset="utf-8"></script>
+ <script type="text/javascript" src="{% static 'js/popper.min.js' %}" charset="utf-8"></script>
+ <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.js' %}" charset="utf-8"></script>
<script type="text/javascript" src="{% static 'js/antinode.js' %}" charset="utf-8"></script>
<script type="text/javascript" src="{% static 'js/autosize.min.js' %}" charset="utf-8"></script>
- <script type="text/javascript" src="{% static 'js/main.js' %}" charset="utf-8"></script>
+ <script type="text/javascript" src="{% static 'js/simulator.js' %}" charset="utf-8"></script>
{% block content %}{% endblock %}
-
- <script type="text/javascript" src="{% static 'js/popper.min.js' %}" charset="utf-8"></script>
- <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.js' %}" charset="utf-8"></script>
</body>
</html>
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_default.html b/src/hi/simulator/templates/simulator/panes/sim_control_default.html
new file mode 100644
index 00000000..7161a763
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_control_default.html
@@ -0,0 +1,2 @@
+CONTROL : {{ sim_state.sim_state_type }}
+VALUE : {{ sim_state.value }}
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_discrete.html b/src/hi/simulator/templates/simulator/panes/sim_control_discrete.html
new file mode 100644
index 00000000..c34d8a64
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_control_discrete.html
@@ -0,0 +1,9 @@
+<select name="value"
+ onchange-async="true"
+ value="{{ sim_state.value }}" autocomplete="off">
+ {% for value, label in sim_state.choices %}
+ <option value="{{ value }}" {% if sim_state.value == value %}selected="true"{% endif %}>
+ {{ label }} / {{sim_state.value }} / {{ value }}
+ </option>
+ {% endfor %}
+</select>
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_movement.html b/src/hi/simulator/templates/simulator/panes/sim_control_movement.html
new file mode 100644
index 00000000..3975a1fa
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_control_movement.html
@@ -0,0 +1,8 @@
+IDLE
+<label class="switch">
+ <input type="checkbox" name="value"
+ {% if sim_state.value %}checked="true"{% endif %}
+ onchange-async="true" >
+ <span class="slider"></span>
+</label>
+MOVEMENT
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_on_off.html b/src/hi/simulator/templates/simulator/panes/sim_control_on_off.html
new file mode 100644
index 00000000..56222801
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_control_on_off.html
@@ -0,0 +1,8 @@
+OFF
+<label class="switch">
+ <input type="checkbox" name="value"
+ {% if sim_state.value %}checked="true"{% endif %}
+ onchange-async="true" >
+ <span class="slider"></span>
+</label>
+ON
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_open_close.html b/src/hi/simulator/templates/simulator/panes/sim_control_open_close.html
new file mode 100644
index 00000000..2256388e
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_control_open_close.html
@@ -0,0 +1,8 @@
+CLOSED
+<label class="switch">
+ <input type="checkbox" name="value"
+ {% if sim_state.value %}checked="true"{% endif %}
+ onchange-async="true" >
+ <span class="slider"></span>
+</label>
+OPEN
diff --git a/src/hi/simulator/templates/simulator/panes/sim_entity.html b/src/hi/simulator/templates/simulator/panes/sim_entity.html
index 0c5154a6..4cef0f8c 100644
--- a/src/hi/simulator/templates/simulator/panes/sim_entity.html
+++ b/src/hi/simulator/templates/simulator/panes/sim_entity.html
@@ -4,15 +4,7 @@
</div>
<div class="col-7">
{% for sim_state in sim_entity.sim_state_list %}
- <div class="row">
- <div class="col-4">
- {{ sim_state.name }}
- </div>
- <div class="col-8">
- CONTROL : {{ sim_state.entity_state_type }}
- VALUE : {{ sim_state.value }}
- </div>
- </div>
+ {% include "simulator/panes/sim_state.html" with sim_state=sim_state %}
{% empty %}
<div class="alert alert-warning">No simulation states defined.</div>
{% endfor %}
diff --git a/src/hi/simulator/templates/simulator/panes/sim_state.html b/src/hi/simulator/templates/simulator/panes/sim_state.html
new file mode 100644
index 00000000..e21883d7
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_state.html
@@ -0,0 +1,15 @@
+{% load common_template_helpers %}
+<div id="hi-sim-state-{{ sim_state.simulator_id }}-{{ sim_state.sim_entity_id }}-{{ sim_state.sim_state_idx }}" class="row">
+ <div class="col-4">
+ {{ sim_state.name }}
+ </div>
+ <div class="col-8">
+ <form action="{% url 'simulator_entity_state_set' simulator_id=sim_state.simulator_id sim_entity_id=sim_state.sim_entity_id sim_state_idx=sim_state.sim_state_idx %}"
+ method="POST" class="form"
+ data-async="#hi-sim-state-{{ sim_state.simulator_id }}-{{ sim_state.sim_entity_id }}-{{ sim_state.sim_state_idx }}"
+ data-mode="replace">
+ {% csrf_token %}
+ {% include_with_fallback sim_state.sim_state_type.template_name "simulator/panes/sim_control_default.html" %}
+ </form>
+ </div>
+</div>
diff --git a/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html b/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html
index 17b88d79..17231bc8 100644
--- a/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html
+++ b/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html
@@ -3,12 +3,12 @@
{% for simulator_data in simulator_data_list %}
{% with simulator_data.simulator as simulator %}
<li class="nav-item">
- <a id="hi-simulator-tab-{{ simulator_data.simulator.id }}" role="tab"
+ <a id="hi-simulator-tab-{{ simulator.id }}" role="tab"
class="nav-link {% if simulator.id == current_simulator.id %}active{% endif %}"
data-toggle="tab"
- href="#hi-simulator-content-{{ simulator.id }}"
+ href="#simulator-{{ simulator.id }}"
role="tab"
- aria-controls="hi-simulator-content-{{ simulator.id }}"
+ aria-controls="simulator-{{ simulator.id }}"
aria-selected="{% if simulator.id == current_simulator.id %}true{% else %}false{% endif %}">
{{ simulator.label }}</a>
</li>
@@ -16,10 +16,10 @@
{% endfor %}
</ul>
- <div id="hi-simulator-tab-content" class="tab-content">
+ <div id="hi-simulator-content" class="tab-content">
{% for simulator_data in simulator_data_list %}
{% with simulator_data.simulator as simulator %}
- <div id="hi-simulator-content-{{ simulator.id }}"
+ <div id="simulator-{{ simulator.id }}"
class="tab-pane fade {% if simulator.id == current_simulator.id %}show active{% endif %}"
role="tabpanel"
aria-labelledby="hi-simulator-tab-{{ simulator.id }}">
@@ -58,3 +58,21 @@
{% endfor %}
</div>
</div>
+
+<script>
+ $(document).ready(function () {
+ $('a[data-toggle="tab"]').on('shown.bs.tab', function (event) {
+ const tabId = $(event.target).attr('href');
+ history.replaceState(null, null, tabId);
+ console.log('Tab activated:', tabId);
+ });
+
+ const hash = window.location.hash;
+ if ( hash ) {
+ const targetTab = document.querySelector(`.nav-link[href="${hash}"]`);
+ if ( targetTab ) {
+ new bootstrap.Tab( targetTab ).show();
+ }
+ }
+ });
+</script>
diff --git a/src/hi/simulator/urls.py b/src/hi/simulator/urls.py
index 9175b968..b4869b4b 100644
--- a/src/hi/simulator/urls.py
+++ b/src/hi/simulator/urls.py
@@ -40,6 +40,10 @@ urlpatterns = [
re_path( r'^entity/delete/(?P<sim_entity_id>\d+)$',
views.SimEntityDeleteView.as_view(),
name = 'simulator_entity_delete' ),
+
+ re_path( r'^entity/state/set/(?P<simulator_id>[\w_\-\.\:]+)/(?P<sim_entity_id>\d+)/(?P<sim_state_idx>\d+)$',
+ views.SimStateSetView.as_view(),
+ name = 'simulator_entity_state_set' ),
]
diff --git a/src/hi/simulator/views.py b/src/hi/simulator/views.py
index ee8796a5..893cd2f0 100644
--- a/src/hi/simulator/views.py
+++ b/src/hi/simulator/views.py
@@ -264,3 +264,24 @@ class SimEntityDeleteView( View, SimulatorViewMixin ):
db_sim_entity = db_sim_entity,
)
return antinode.refresh_response()
+
+
+class SimStateSetView( View, SimulatorViewMixin ):
+
+ TEMPLATE_NAME = 'simulator/panes/sim_state.html'
+
+ def post( self, request, *args, **kwargs ):
+ simulator = self.get_simulator( request, *args, **kwargs)
+ sim_entity_id = int( kwargs.get( 'sim_entity_id' ))
+ sim_state_idx = int( kwargs.get( 'sim_state_idx' ))
+ value_str = request.POST.get('value')
+ sim_state = simulator.set_sim_state(
+ sim_entity_id = sim_entity_id,
+ sim_state_idx = sim_state_idx,
+ value_str = value_str,
+ )
+ context = {
+ 'sim_state': sim_state,
+ }
+ return render( request, self.TEMPLATE_NAME, context )
+
diff --git a/src/hi/static/css/simulator.css b/src/hi/static/css/simulator.css
new file mode 100644
index 00000000..8001bd5a
--- /dev/null
+++ b/src/hi/static/css/simulator.css
@@ -0,0 +1,203 @@
+/* Home Information
+ Copyright 2024 by POMDP, Inc.
+ All Rights Reserved.
+*/
+:root {
+ --white-fg-color: #fdfdfd;
+ --white-bg-color: #fdfdfd;
+ --black: #020204;
+ --primary-color: #177072;
+ --on-primary-color: #ffffff;
+ --primary-highlight-color: #26BFD1;
+ --secondary-color: #F45F36;
+ --on-secondary-color: #ffffff;
+ --secondary-highlight-color: #F8AD98;
+ --tertiary-color: #020204;
+ --on-tertiary-color: #ffffff;
+ --secondary-highlight-color: #7e7e81;
+ --success-color: #177219;
+ --on-success-color: #ffffff;
+ --warning-color: #ECA500;
+ --on-warning-color: #ffffff;
+ --error-color: #721817;
+ --on-error-color: #ffffff;
+ --muted-color: #7e7e81;
+ --on-muted-color: #ffffff;
+ --line-color: #cccccc;
+
+ --top-buttons-height: 2.5rem;
+ --bottom-buttons-height: 2.5rem;
+}
+
+html, body {
+ font-size: 1rem;
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ background-color: var(--white-bg-color);
+}
+
+a { color: var(--primary-color); }
+a:hover,
+a:focus,
+a:active {
+ opacity: 0.65;
+ color: var(--primary-color);
+}
+a.plain {
+ text-decoration: none;
+ cursor: pointer;
+ border-bottom: 0;
+}
+a.underline,
+a.underline:visited {
+ text-decoration: none;
+ padding-bottom: 0.075rem;
+ border-bottom: 2px solid var(--primary-color);
+}
+
+.text-primary {
+ color: var(--primary-color) !important;
+}
+.text-on-primary {
+ color: var(--on-primary-color) !important;
+}
+.text-white {
+ color: var(--white-fg-color) !important;
+}
+.text-black {
+ color: var(--black);
+}
+
+.bg-primary, .btn-primary {
+ color: var(--on-primary-color) !important;
+ background-color: var(--primary-color) !important;
+ border-color: var(--primary-highlight-color) !important;
+}
+.bg-primary a {
+ color: color: var(--on-primary-color);
+}
+.bg-primary a:hover,
+.bg-primary a:focus,
+.bg-primary a:active,
+.bg-info a:hover,
+.bg-info a:focus,
+.bg-info a:active {
+ opacity: 0.65;
+ color: color: var(--on-primary-color);
+}
+
+.bg-secondary, .btn-secondary {
+ color: var(--on-secondary-color) !important;
+ background-color: var(--secondary-color) !important;
+ border-color: var(--secondary-highlight-color) !important;
+}
+.bg-secondary a {
+ color: color: var(--on-secondary-color);
+}
+.bg-secondary a:hover,
+.bg-secondary a:focus,
+.bg-secondary a:active,
+.bg-info a:hover,
+.bg-info a:focus,
+.bg-info a:active {
+ opacity: 0.65;
+ color: color: var(--on-secondary-color);
+}
+
+.bg-tertiary, .btn-tertiary {
+ color: var(--on-tertiary-color) !important;
+ background-color: var(--tertiary-color) !important;
+ border-color: var(--tertiary-highlight-color) !important;
+}
+.bg-tertiary a {
+ color: color: var(--on-tertiary-color);
+}
+.bg-tertiary a:hover,
+.bg-tertiary a:focus,
+.bg-tertiary a:active,
+.bg-info a:hover,
+.bg-info a:focus,
+.bg-info a:active {
+ opacity: 0.65;
+ color: color: var(--on-tertiary-color);
+}
+
+.bg-muted, .btn-muted {
+ color: var(--on-muted-color) !important;
+ background-color: var(--muted-color) !important;
+}
+
+.hi-top-content {
+ height: var(--top-buttons-height);
+ border-bottom: 1px solid var(--line-color);
+}
+.hi-bottom-content {
+ height: var(--bottom-buttons-height);
+ border-top: 1px solid var(--line-color);
+}
+.hi-screen {
+ max-height: 100vh;
+}
+.scrollable-column {
+ overflow-y: auto;
+ max-height: 100vh;
+ padding-top: var(--top-buttons-height);
+ padding-bottom: var(--bottom-buttons-height);
+}
+.fixed-column {
+ overflow-y: auto;
+ flex-shrink: 0;
+ height: 100vh;
+ max-height: 100vh;
+ padding-top: var(--top-buttons-height);
+ padding-bottom: var(--bottom-buttons-height);
+ border-left: 1px solid var(--line-color);
+}
+
+.btn-control {
+ width: 100%;
+ white-space: nowrap;
+ font-size: 0.75rem;
+ font-weight: bold;
+}
+
+.switch {
+ position: relative;
+ display: inline-block;
+ width: 50px;
+ height: 24px;
+}
+.switch input {
+ opacity: 0;
+ width: 0;
+ height: 0;
+}
+.slider {
+ position: absolute;
+ cursor: pointer;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background-color: #ccc;
+ transition: 0.4s;
+ border-radius: 24px;
+}
+.slider:before {
+ position: absolute;
+ content: "";
+ height: 18px;
+ width: 18px;
+ left: 3px;
+ bottom: 3px;
+ background-color: white;
+ transition: 0.4s;
+ border-radius: 50%;
+}
+.switch input:checked + .slider {
+ background-color: var(--success-color);
+}
+.switch input:checked + .slider:before {
+ transform: translateX(26px);
+}
diff --git a/src/hi/static/js/simulator.js b/src/hi/static/js/simulator.js
new file mode 100644
index 00000000..a6479b95
--- /dev/null
+++ b/src/hi/static/js/simulator.js
@@ -0,0 +1,46 @@
+(function() {
+
+ const HiSimulator = {
+
+ DEBUG: true,
+
+ setCookie: function( name, value, days = 365, sameSite = 'Lax' ) {
+ return _setCookie( name, value, days, sameSite );
+ },
+ getCookie: function( name ) {
+ return _getCookie( name );
+ },
+ submitForm: function( formElement ) {
+ return _submitForm( formElement );
+ },
+ };
+
+ window.HiSimulator = HiSimulator;
+
+ function _setCookie( name, value, days, sameSite ) {
+ const expires = new Date();
+ expires.setTime( expires.getTime() + days * 24 * 60 * 60 * 1000 );
+ const secureFlag = sameSite === 'None' ? '; Secure' : '';
+ document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires.toUTCString()}; path=/; SameSite=${sameSite}${secureFlag}`;
+ return true;
+ }
+
+ function _getCookie( name ) {
+ const nameEQ = `${encodeURIComponent(name)}=`;
+ const cookies = document.cookie.split(';'); // SPlit into key-pairs
+ for ( let i = 0; i < cookies.length; i++ ) {
+ let cookie = cookies[i].trim();
+ if (cookie.startsWith( nameEQ )) {
+ return decodeURIComponent( cookie.substring( nameEQ.length ));
+ }
+ }
+ return null;
+ }
+
+ function _submitForm( formElement ) {
+ let form = $(formElement).closest('form');
+ if ( Hi.DEBUG ) { console.debug( 'Submitting form:', formElement, form ); }
+ $(form).submit();
+ }
+
+})();