From 300397b02129b1c084b24fee3994163a8c0788ee Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Tue, 14 Nov 2023 12:53:15 -0500 Subject: [PATCH] doorcontrol: Add property on Door model to get associated DoorController --- doorcontrol/models.py | 11 +++++++++++ doorcontrol/tasks/scrapehidevents.py | 10 +--------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/doorcontrol/models.py b/doorcontrol/models.py index f57e8ed..62207b6 100644 --- a/doorcontrol/models.py +++ b/doorcontrol/models.py @@ -1,15 +1,26 @@ from datetime import datetime +from django.conf import settings from django.db import models from django.db.models import ExpressionWrapper, F, Func, Q from django.db.models.functions import Mod from django.utils import timezone +from .hid.DoorController import DoorController + class Door(models.Model): name = models.CharField(max_length=64, unique=True) ip = models.GenericIPAddressField(protocol="IPv4") + @property + def controller(self) -> DoorController: + return DoorController( + self.ip, + settings.HID_DOOR_USERNAME, + settings.HID_DOOR_PASSWORD, + ) + def __str__(self): return self.name diff --git a/doorcontrol/tasks/scrapehidevents.py b/doorcontrol/tasks/scrapehidevents.py index ab4aa3a..69b325e 100644 --- a/doorcontrol/tasks/scrapehidevents.py +++ b/doorcontrol/tasks/scrapehidevents.py @@ -1,6 +1,5 @@ from datetime import datetime -from django.conf import settings from django.db import transaction from django.utils import timezone @@ -9,7 +8,6 @@ from django_q.models import Schedule from cmsmanage.django_q2_helper import ensure_scheduled from doorcontrol.models import Door, HIDEvent -from doorcontrol.hid.DoorController import DoorController @transaction.atomic() @@ -20,13 +18,7 @@ def getMessages(door: Door): else: last_ts = datetime(2010, 1, 1) - door_controller = DoorController( - door.ip, - settings.HID_DOOR_USERNAME, - settings.HID_DOOR_PASSWORD, - ) - - for events_page in door_controller.get_events(last_ts): + for events_page in door.controller.get_events(last_ts): print(f"Importing {len(events_page)} events for {door.name}") HIDEvent.objects.bulk_create( (HIDEvent.from_xml_attributes(door, event.attrib) for event in events_page),