Skip to content

Home Information - Your home, your data, organized.

Python

Added SimProfile CRUD UI and operations.

Anthony Cassandra0e8a77d3e457
diff --git a/src/hi/settings/simulator.py b/src/hi/settings/simulator.py
index c7a96f8d..4a8fbf07 100644
--- a/src/hi/settings/simulator.py
+++ b/src/hi/settings/simulator.py
@@ -10,6 +10,7 @@ INSTALLED_APPS = [
'django.contrib.staticfiles',
'pipeline',
'django.contrib.humanize',
+
'hi.apps.common',
'hi.simulator',
'hi.simulator.services.hass',
@@ -25,6 +26,8 @@ MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
+
+ 'hi.simulator.middleware.SimViewMiddleware',
]
ROOT_URLCONF = 'hi.simulator.urls'
diff --git a/src/hi/simulator/forms.py b/src/hi/simulator/forms.py
new file mode 100644
index 00000000..766c5200
--- /dev/null
+++ b/src/hi/simulator/forms.py
@@ -0,0 +1,12 @@
+from django import forms
+
+from .models import SimProfile
+
+
+class SimProfileForm( forms.ModelForm ):
+
+ class Meta:
+ model = SimProfile
+ fields = (
+ 'name',
+ )
diff --git a/src/hi/simulator/middleware.py b/src/hi/simulator/middleware.py
new file mode 100644
index 00000000..581656cb
--- /dev/null
+++ b/src/hi/simulator/middleware.py
@@ -0,0 +1,20 @@
+import logging
+
+from .sim_view_parameters import SimViewParameters
+
+logger = logging.getLogger(__name__)
+
+
+class SimViewMiddleware:
+
+ def __init__(self, get_response):
+ self.get_response = get_response
+ return
+
+ def __call__(self, request):
+ self._set_sim_view_parameters( request )
+ return self.get_response( request )
+
+ def _set_sim_view_parameters( self, request ):
+ request.sim_view_parameters = SimViewParameters.from_session( request )
+ return
diff --git a/src/hi/simulator/migrations/0002_alter_simprofile_options_and_more.py b/src/hi/simulator/migrations/0002_alter_simprofile_options_and_more.py
new file mode 100644
index 00000000..4e8d8d4c
--- /dev/null
+++ b/src/hi/simulator/migrations/0002_alter_simprofile_options_and_more.py
@@ -0,0 +1,30 @@
+# Generated by Django 4.2.15 on 2024-12-21 17:45
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("simulator", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="simprofile",
+ options={
+ "ordering": ["-last_switched_to_datetime"],
+ "verbose_name": "Simulator Profile",
+ "verbose_name_plural": "Simulator Profiles",
+ },
+ ),
+ migrations.AddField(
+ model_name="simprofile",
+ name="last_switched_to_datetime",
+ field=models.DateTimeField(
+ default=django.utils.timezone.now, verbose_name="Last Switched To"
+ ),
+ preserve_default=False,
+ ),
+ ]
diff --git a/src/hi/simulator/migrations/0003_alter_simprofile_last_switched_to_datetime.py b/src/hi/simulator/migrations/0003_alter_simprofile_last_switched_to_datetime.py
new file mode 100644
index 00000000..be498d5d
--- /dev/null
+++ b/src/hi/simulator/migrations/0003_alter_simprofile_last_switched_to_datetime.py
@@ -0,0 +1,21 @@
+# Generated by Django 4.2.15 on 2024-12-21 19:26
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("simulator", "0002_alter_simprofile_options_and_more"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="simprofile",
+ name="last_switched_to_datetime",
+ field=models.DateTimeField(
+ default=django.utils.timezone.now, verbose_name="Last Switched To"
+ ),
+ ),
+ ]
diff --git a/src/hi/simulator/models.py b/src/hi/simulator/models.py
index d7c21773..6f578dd4 100644
--- a/src/hi/simulator/models.py
+++ b/src/hi/simulator/models.py
@@ -1,4 +1,5 @@
from django.db import models
+from django.utils.timezone import now
from hi.apps.entity.enums import EntityType
@@ -11,6 +12,10 @@ class SimProfile(models.Model):
null = False, blank = False,
unique = True,
)
+ last_switched_to_datetime = models.DateTimeField(
+ 'Last Switched To',
+ default = now,
+ )
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
@@ -20,6 +25,7 @@ class SimProfile(models.Model):
class Meta:
verbose_name = 'Simulator Profile'
verbose_name_plural = 'Simulator Profiles'
+ ordering = [ '-last_switched_to_datetime' ]
class DbSimEntity(models.Model):
diff --git a/src/hi/simulator/sim_view_parameters.py b/src/hi/simulator/sim_view_parameters.py
new file mode 100644
index 00000000..eca9410a
--- /dev/null
+++ b/src/hi/simulator/sim_view_parameters.py
@@ -0,0 +1,34 @@
+from dataclasses import dataclass
+
+from django.http import HttpRequest
+
+
+@dataclass
+class SimViewParameters:
+
+ simulator_id : str = None # Last active simulator
+
+ def __post_init__(self):
+ return
+
+ def to_session( self, request : HttpRequest ):
+ if not hasattr( request, 'session' ):
+ return
+ request.session['simulator_id'] = self.simulator_id
+ return
+
+ @staticmethod
+ def from_session( request : HttpRequest ):
+ if not request:
+ return SimViewParameters()
+ if not hasattr( request, 'session' ):
+ return SimViewParameters()
+ try:
+ simulator_id = int( request.session.get( 'simulator_id' ))
+ except ( TypeError, ValueError ):
+ simulator_id = None
+
+ return SimViewParameters(
+ simulator_id = simulator_id,
+ )
+
diff --git a/src/hi/simulator/simulator_manager.py b/src/hi/simulator/simulator_manager.py
index f7b14fcf..868cce17 100644
--- a/src/hi/simulator/simulator_manager.py
+++ b/src/hi/simulator/simulator_manager.py
@@ -5,6 +5,7 @@ from typing import Dict, Type
from django.apps import apps
+import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.module_utils import import_module_safe
from hi.apps.common.singleton import Singleton
@@ -25,10 +26,24 @@ class SimulatorManager( Singleton ):
self._data_lock = Lock()
return
+ def get_sim_profile_list(self):
+ return list( SimProfile.objects.all().order_by('name') )
+
@property
def current_sim_profile(self) -> SimProfile:
return self._current_sim_profile
-
+
+ def switch_sim_profile( self, sim_profile : SimProfile ):
+ if not sim_profile:
+ self._initialize_sim_profile()
+ else:
+ sim_profile.last_switched_to_datetime = datetimeproxy.now()
+ sim_profile.save()
+ self._current_sim_profile = sim_profile
+
+ self._initialize_simulators()
+ return
+
def get_simulator( self, simulator_id : str ) -> Simulator:
return self._id_to_simulator_map.get( simulator_id )
@@ -40,47 +55,29 @@ class SimulatorManager( Singleton ):
async def initialize(self) -> None:
self._data_lock.acquire()
try:
- await sync_to_async( self._set_current_sim_profile )()
await sync_to_async( self._load_simulator_data )()
+ await sync_to_async( self._initialize_sim_profile )()
+ await sync_to_async( self._initialize_simulators )()
+
finally:
self._data_lock.release()
return
- def _set_current_sim_profile(self):
- self._current_sim_profile = SimProfile.objects.all().first()
- if not self._current_sim_profile:
- self._current_sim_profile = SimProfile.objects.create(
- name = self.DEFAULT_PROFILE_NAME,
- )
- return
-
def _load_simulator_data(self) -> None:
logger.debug("Discovering defined simulators ...")
self._id_to_simulator_map = self._discover_defined_simulators()
self._defined_entity_classes = self._load_defined_entity_classes()
- self._initialize_simulators( )
return
- def _load_defined_entity_classes(self) -> Dict[ str, Dict[ str, Type[ SimEntity ]]]:
- """
- Query simulators to get the defined subclasses of SimEntity. Returns a
- map from simulator id, to class name, then to the (sub) class itself
- (which is used to create instances).
- """
-
- defined_entity_classes = dict()
- for simulator_id, simulator in self._id_to_simulator_map.items():
- sim_entity_class_list = simulator.get_sim_entity_class_list()
- logger.debug( f'Adding {len(sim_entity_class_list)} entity class to simulator {simulator_id}.' )
- if simulator_id not in defined_entity_classes:
- defined_entity_classes[simulator_id] = dict()
- for sim_entity_class in sim_entity_class_list:
- class_name = sim_entity_class.__name__
- defined_entity_classes[class_name] = sim_entity_class
- continue
- continue
- return defined_entity_classes
-
+ def _initialize_sim_profile(self):
+ self._current_sim_profile = SimProfile.objects.all().first() # Default ordering by usage time
+ if not self._current_sim_profile:
+ self._current_sim_profile = SimProfile.objects.create(
+ name = self.DEFAULT_PROFILE_NAME,
+ last_switched_to_datetime = datetimeproxy.now(),
+ )
+ return
+
def _initialize_simulators(self):
db_sim_entity_queryset = DbSimEntity.objects.prefetch_related( 'db_sim_states' ).filter(
@@ -142,3 +139,24 @@ class SimulatorManager( Singleton ):
continue
return simulator_id_to_simulator
+
+ def _load_defined_entity_classes(self) -> Dict[ str, Dict[ str, Type[ SimEntity ]]]:
+ """
+ Query simulators to get the defined subclasses of SimEntity. Returns a
+ map from simulator id, to class name, then to the (sub) class itself
+ (which is used to create instances).
+ """
+
+ defined_entity_classes = dict()
+ for simulator_id, simulator in self._id_to_simulator_map.items():
+ sim_entity_class_list = simulator.get_sim_entity_class_list()
+ logger.debug( f'Adding {len(sim_entity_class_list)} entity class to simulator {simulator_id}.' )
+ if simulator_id not in defined_entity_classes:
+ defined_entity_classes[simulator_id] = dict()
+ for sim_entity_class in sim_entity_class_list:
+ class_name = sim_entity_class.__name__
+ defined_entity_classes[class_name] = sim_entity_class
+ continue
+ continue
+ return defined_entity_classes
+
diff --git a/src/hi/simulator/templates/simulator/modals/sim_profile_create.html b/src/hi/simulator/templates/simulator/modals/sim_profile_create.html
new file mode 100644
index 00000000..5e8fce80
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/modals/sim_profile_create.html
@@ -0,0 +1,27 @@
+{% extends "modals/action_with_cancel.html" %}
+
+{% block preamble %}
+<form action="{% url 'simulator_profile_create' %}" method="post"
+ class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Create Simulator Profile
+{% endblock %}
+
+{% block body %}
+{% include "simulator/panes/sim_profile_form.html" %}
+{% endblock %}
+
+{% block action_right %}
+<button id="hi-simulator-profile-create-submit" type="submit" class="btn btn-lg btn-success"
+ name="action" value="create">
+ CREATE
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
+
diff --git a/src/hi/simulator/templates/simulator/modals/sim_profile_delete.html b/src/hi/simulator/templates/simulator/modals/sim_profile_delete.html
new file mode 100644
index 00000000..548d9112
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/modals/sim_profile_delete.html
@@ -0,0 +1,32 @@
+{% extends "modals/action_with_cancel.html" %}
+
+{% block preamble %}
+<form action="{% url 'simulator_profile_delete' profile_id=sim_profile.id %}" method="post"
+ class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Delete Simulation Profile?
+{% endblock %}
+
+{% block body %}
+ <p>
+ Deleting the simulation profile "{{ sim_profile.name }}" will remove all {{ sim_entity_count }} the defined simulator entities.
+ </p>
+ <p class="text-danger">
+ This action cannot be undone. Are you sure you want to delete the "{{ sim_profile.name }}" simulation profile?
+ </p>
+{% endblock %}
+
+{% block action_right %}
+<button id="hi-simulator-profile-delete-submit" type="submit" class="btn btn-lg btn-danger"
+ name="action" value="delete">
+ DELETE
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
+
diff --git a/src/hi/simulator/templates/simulator/pages/home.html b/src/hi/simulator/templates/simulator/pages/home.html
index c887c6ad..86ba3287 100644
--- a/src/hi/simulator/templates/simulator/pages/home.html
+++ b/src/hi/simulator/templates/simulator/pages/home.html
@@ -2,8 +2,13 @@
{% block content %}
<div class="container-fluid">
- <div class="h3">Service Simulators</div>
-
+ <div class="d-flex justify-content-between">
+ <div class="h3">Service Simulators</div>
+ <div>
+ {% include "simulator/panes/sim_profile_dropdown.html" %}
+ </div>
+ </div>
+
<ul id="hi-simulator-tabs" class="nav nav-tabs" role="tablist">
{% for simulator in simulator_list %}
<li class="nav-item">
diff --git a/src/hi/simulator/templates/simulator/panes/sim_profile_dropdown.html b/src/hi/simulator/templates/simulator/panes/sim_profile_dropdown.html
new file mode 100644
index 00000000..06110b29
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_profile_dropdown.html
@@ -0,0 +1,42 @@
+<div>
+ <div class="dropdown">
+ <button class="btn btn-secondary btn-control dropdown-toggle" type="button"
+ id="hi-sim_profile-menu" data-toggle="dropdown">
+ {% if current_sim_profile %}
+ Profile: {{ current_sim_profile.name }}
+ {% else %}
+ -- CHOOSE --
+ {% endif %}
+ <span class="caret"></span>
+ </button>
+ <div class="dropdown-menu dropdown-menu-right"
+ role="menu" aria-labelledby="hi-sim_profile-menu">
+ {% for sim_profile in sim_profile_list %}
+ {% if sim_profile != current_sim_profile %}
+
+ <a role="menuitem" class="dropdown-item plain"
+ href="{% url 'simulator_profile_switch' profile_id=sim_profile.id %} ">
+ {{ sim_profile.name }}
+ </a>
+ <div class="dropdown-divider"></div>
+
+ {% endif %}
+ {% empty %}
+ <div class="dropdown-item alert alert-secondary text-center">
+ <em>No simulator profiles.</em>
+ </div>
+ {% endfor %}
+ <a role="menuitem" class="dropdown-item plain"
+ href="{% url 'simulator_profile_create' %}"
+ data-async="modal">
+ NEW PROFILE
+ </a>
+ <div class="dropdown-divider"></div>
+ <a role="menuitem" class="dropdown-item plain text-danger"
+ href="{% url 'simulator_profile_delete' profile_id=current_sim_profile.id %}"
+ data-async="modal">
+ DELETE: {{ current_sim_profile.name }}
+ </a>
+ </div>
+ </div>
+</div>
diff --git a/src/hi/simulator/templates/simulator/panes/sim_profile_form.html b/src/hi/simulator/templates/simulator/panes/sim_profile_form.html
new file mode 100644
index 00000000..595bafaa
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/sim_profile_form.html
@@ -0,0 +1,17 @@
+{% for hidden in sim_profile_form.hidden_fields %}
+{{ hidden }}
+{% endfor %}
+
+{% if sim_profile_form.non_field_errors %}
+<div class="non-field-errors">
+ {% for err in sim_profile_form.non_field_errors %}
+ <p class="form-error text-danger">ERROR: {{ err }}</p>
+ {% endfor %}
+</div>
+{% endif %}
+
+<div>
+ {{ sim_profile_form.name.label }}
+ {{ sim_profile_form.name }}
+ {{ sim_profile_form.name.errors }}
+</div>
diff --git a/src/hi/simulator/urls.py b/src/hi/simulator/urls.py
index 61d6d3dc..11bb0485 100644
--- a/src/hi/simulator/urls.py
+++ b/src/hi/simulator/urls.py
@@ -6,15 +6,26 @@ from hi.apps.common.module_utils import import_module_safe
from . import views
urlpatterns = [
+
re_path( r'^$',
views.HomeView.as_view(),
- name = 'simulator_home',
- ),
-
+ name = 'simulator_home' ),
+
+ re_path( r'^profile/create$',
+ views.ProfileCreateView.as_view(),
+ name = 'simulator_profile_create' ),
+
+ re_path( r'^profile/delete/(?P<profile_id>\d+)$',
+ views.ProfileDeleteView.as_view(),
+ name = 'simulator_profile_delete' ),
+
+ re_path( r'^profile/switch/(?P<profile_id>\d+)$',
+ views.ProfileSwitchView.as_view(),
+ name = 'simulator_profile_switch' ),
+
re_path( r'^add-entity/(?P<simulator_id>[\w_]+)$',
views.AddEntityView.as_view(),
- name = 'simulator_add_entity',
- ),
+ name = 'simulator_add_entity' ),
]
diff --git a/src/hi/simulator/view_mixins.py b/src/hi/simulator/view_mixins.py
new file mode 100644
index 00000000..9a3208cf
--- /dev/null
+++ b/src/hi/simulator/view_mixins.py
@@ -0,0 +1,31 @@
+from typing import List
+
+from django.http import Http404, HttpRequest
+
+from .models import SimProfile
+from .simulator import Simulator
+
+
+class SimulatorViewMixin:
+
+ def get_current_simulator( self,
+ request : HttpRequest,
+ simulator_list : List[ Simulator ] ) -> Simulator:
+ if not simulator_list:
+ return None
+ current_simulator_id = request.sim_view_parameters.simulator_id
+ current_simulator = simulator_list[0]
+ for simulator in simulator_list:
+ if simulator.id == current_simulator_id:
+ current_simulator = simulator
+ break
+ continue
+ return current_simulator
+
+ def get_sim_profile( self, request, *args, **kwargs):
+ sim_profile_id = kwargs.get('profile_id')
+ try:
+ return SimProfile.objects.get( id = sim_profile_id )
+ except SimProfile.DoesNotExist:
+ raise Http404( 'Simulator profile does not exist.' )
+
diff --git a/src/hi/simulator/views.py b/src/hi/simulator/views.py
index 102caead..6d43f9bf 100644
--- a/src/hi/simulator/views.py
+++ b/src/hi/simulator/views.py
@@ -1,26 +1,98 @@
from dataclasses import fields, MISSING
from django.core.exceptions import BadRequest
-from django.http import Http404
+from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render
+from django.urls import reverse
from django.views.generic import View
+import hi.apps.common.antinode as antinode
+
+from . import forms
+from .models import DbSimEntity
from .simulator_manager import SimulatorManager
+from .view_mixins import SimulatorViewMixin
-class HomeView( View ):
+class HomeView( View, SimulatorViewMixin ):
def get(self, request, *args, **kwargs):
simulator_manager = SimulatorManager()
+ sim_profile_list = simulator_manager.get_sim_profile_list()
+ current_sim_profile = simulator_manager.current_sim_profile
simulator_list = simulator_manager.get_simulator_list()
- current_simulator = simulator_list[0]
+ current_simulator = self.get_current_simulator(
+ request = request,
+ simulator_list = simulator_list,
+ )
context = {
- 'current_simulator': current_simulator,
+ 'sim_profile_list': sim_profile_list,
+ 'current_sim_profile': current_sim_profile,
'simulator_list': simulator_list,
+ 'current_simulator': current_simulator,
}
return render( request, 'simulator/pages/home.html', context )
+class ProfileCreateView( View ):
+
+ MODAL_TEMPLATE_NAME = 'simulator/modals/sim_profile_create.html'
+
+ def get(self, request, *args, **kwargs):
+ context = {
+ 'sim_profile_form': forms.SimProfileForm()
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post(self, request, *args, **kwargs):
+
+ sim_profile_form = forms.SimProfileForm( request.POST )
+ if not sim_profile_form.is_valid():
+ context = {
+ 'sim_profile_form': forms.SimProfileForm()
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ sim_profile = sim_profile_form.save()
+ sim_profile = SimulatorManager().switch_sim_profile(
+ sim_profile = sim_profile,
+ )
+ return antinode.refresh_response()
+
+
+class ProfileSwitchView( View, SimulatorViewMixin ):
+
+ def get(self, request, *args, **kwargs):
+ sim_profile = self.get_sim_profile( request, *args, **kwargs)
+ SimulatorManager().switch_sim_profile(
+ sim_profile = sim_profile,
+ )
+ url = reverse( 'simulator_home' )
+ return HttpResponseRedirect( url )
+
+
+class ProfileDeleteView( View, SimulatorViewMixin ):
+
+ MODAL_TEMPLATE_NAME = 'simulator/modals/sim_profile_delete.html'
+
+ def get(self, request, *args, **kwargs):
+ sim_profile = self.get_sim_profile( request, *args, **kwargs)
+ sim_entity_count = DbSimEntity.objects.filter( sim_profile = sim_profile ).count()
+ context = {
+ 'sim_profile': sim_profile,
+ 'sim_entity_count': sim_entity_count,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post(self, request, *args, **kwargs):
+ sim_profile = self.get_sim_profile( request, *args, **kwargs)
+ needs_switch = bool( sim_profile == SimulatorManager().current_sim_profile )
+ sim_profile.delete()
+ if needs_switch:
+ sim_profile = SimulatorManager().switch_sim_profile( sim_profile = None )
+ return antinode.refresh_response()
+
+
class AddEntityView( View ):
def get(self, request, *args, **kwargs):
@@ -53,7 +125,7 @@ class AddEntityView( View ):
def post(self, request, *args, **kwargs):
simulator_id = kwargs.get('simulator_id')
- entity_id = kwargs.get('entity_id')
+
simulator = SimulatorManager().get_simulator( simulator_id = simulator_id )
simulator.add_entity( entity_id = entity_id )