sensors added to settings

This commit is contained in:
Joren de Graaf
2026-10-02 15:38:18 +02:00
parent 428caef29d
commit ab6cfc0bae
19 changed files with 360 additions and 19 deletions
+20
View File
@@ -1,6 +1,7 @@
import math
import secrets
from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
@@ -13,7 +14,9 @@ class Sensor(models.Model):
"""A physical recorder authorised to submit audio to the device API."""
name = models.CharField(max_length=100, unique=True, help_text=_("A recognisable device name, e.g. Garden ESP32."))
owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name="sensors")
is_active = models.BooleanField(default=True)
archived_at = models.DateTimeField(null=True, blank=True, editable=False)
token_prefix = models.CharField(max_length=15, blank=True, editable=False)
token_hash = models.CharField(max_length=256, blank=True, editable=False)
last_heartbeat = models.DateTimeField(null=True, blank=True, editable=False)
@@ -37,6 +40,23 @@ class Sensor(models.Model):
def token_matches(self, token):
return bool(self.token_hash) and check_password(token, self.token_hash)
def heartbeat_status(self):
if not self.last_heartbeat:
return "never", _("Never seen")
age = (timezone.now() - self.last_heartbeat).total_seconds()
if age <= 300:
return "online", _("Online")
if age <= 900:
return "delayed", _("Delayed")
return "offline", _("Offline")
def archive(self):
self.archived_at = timezone.now()
self.is_active = False
self.token_hash = ""
self.token_prefix = ""
self.save(update_fields=["archived_at", "is_active", "token_hash", "token_prefix"])
def record_heartbeat(self, submission=False):
now = timezone.now()
self.last_heartbeat = now