added scheduling

This commit is contained in:
Joren de Graaf
2026-10-10 16:03:14 +02:00
parent e967fc391e
commit 7220dd564f
53 changed files with 769 additions and 67 deletions
+11
View File
@@ -0,0 +1,11 @@
# Burst Events
A report with at least three `occurrences` is a Burst Event. `event_kind`, `is_burst`, `bangs_per_15_minutes`, and `burst_intensity` are derived properties on both PendingEvent and Event; they are never stored separately. One or two occurrences are ordinary reports.
`captured_at` is the reported occurrence time for a manual report. PendingEvent `created_at` is its actual submission time; approval copies that value into Event `submitted_at`, while Event `approved_at` remains the approval time. Older Events have an unknown `submitted_at` because their original submission time cannot be reconstructed. `occurrence_time_approximate` records uncertainty about the reported time. No individual bang times are inferred from an aggregate report.
`observation_duration_minutes` holds a window only when the reporter explicitly accepts an estimate, or when a future source provides a measured window. `observation_duration_kind` distinguishes `estimated` from `measured`; a blank kind or duration means intensity is unavailable. The quick form suggests 15 minutes and asks the reporter to accept that estimate. Existing records migrate with an unknown duration, preserving their counts without inventing an intensity.
The normalised rate is `occurrences × 15 / observation_duration_minutes`. Provisional presentation bands live in `fireworks_detect/bursts.py`: light below 5, moderate from 5 to below 10, intense from 10 per 15 minutes. This describes **frequency, not loudness**. The map event JSON exposes the count, event kind, duration, duration kind, rate, intensity, and approximate-time flag for future timeline work. No timeline is rendered in this pass.
Quick reports remain Pending until moderated. The browser can enhance the form, while the POST endpoint also accepts an ordinary server-rendered form submission with no microphone, classifier, or JavaScript. A reporter can correct the count and estimated duration before moderation through a session-scoped receipt form; each correction creates a ManualReportRevision. Corrections do not change the original occurrence or submission time.
+25 -17
View File
@@ -1,24 +1,32 @@
# Waveshare firmware validation — concept archive
# Waveshare V2 firmware integration status
Reviewed `BoomCast_Waveshare_Arduino_v0.1.0-concept.zip` as supplied. The README targets the non-touch ESP32-S3-ePaper-1.54 **V2**, but the physical board revision has not been inspected. Waveshare states that V1 and V2 example programs are not interchangeable. Confirm the V2 marking on the PCB before flashing. The official V2 has 8 MiB PSRAM, 8 MiB flash, ES8311 codec, microphone, and microSD slot. The firmware's SDMMC pins 39/40/41 match Waveshare's published pinout for this board.
The owner has confirmed a non-touch Waveshare ESP32-S3-ePaper-1.54 V2 board. The firmware now lives at `../arduino/BoomCast_Waveshare_Arduino/`; that folder is currently **outside** the Django Git worktree (`django/`). Its sketch, build guide, source, pinned preparation script, local-config example, ignore rules, and hardware/API/checklist documents are there.
## Source review
The official Waveshare support was inspected at commit `aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956`. The Arduino audio `board_cfg.h` and explicitly V2 ESP-IDF audio example agree on ES8311 I2S pins. The official Arduino SD example uses CLK/D0/CMD 39/40/41. The firmware uses those pins. Waveshare documents V2 as 8 MB flash and 8 MB PSRAM and says V1/V2 examples are not interchangeable.
- **Microphone and capture:** `boomcast_audio.cpp` uses Waveshare's `audio_bsp` wrapper and a 16 kHz stereo read, selecting the louder slot per frame for mono. That slot selection is a heuristic; verify actual channel mapping and recorded playback on the board. A 2.5-second PSRAM ring and 2.5-second post-trigger buffer make an intended 5-second capture. The detector uses RMS/peak thresholds and cooldown. The first capture after boot can contain less pre-roll. Return values from `audio_playback_read` are not checked, so failed or short reads could enter recordings.
- **WAV and storage:** `boomcast_queue.cpp` writes RIFF PCM mono 16-bit headers and a 16 kHz sample rate. Header arithmetic matches the intended sample count. The queue is on FAT microSD, but files are written directly to their final `.wav` names without a temporary file and atomic rename. Power loss or a full card can leave a truncated item that appears queued; `fwrite`, `fflush`, and `fclose` results are not checked.
- **Network and uploads:** `boomcast_network.cpp` reconnects Wi-Fi and starts NTP. `boomcast_uploader.cpp` sends a conventional multipart body with CRLF boundaries and a `file` part. It sends a Bearer header if a token is set. The current fields are `event_id`, `trigger_type`, optional `detected_at`, and `file`; this **does not satisfy** the new `/api/pending/` contract's `sensor_id`, `captured_at`, `duration_seconds`, or `firmware_version`. It still targets `/fireworks/classify/`.
- **TLS and credentials:** `TLS_ALLOW_INSECURE` defaults to true, and the HTTPS client has no CA certificate configured when it is false. `SENSOR_TOKEN` is in committed-style `boomcast_config.h`; move it into an ignored local header or provisioned NVS and configure a trusted CA before deployment. The setup AP also uses a fixed prototype password.
- **Retries and duplicate safety:** the SD item remains after non-2xx or transport failure, and filename-derived `event_id` is stable across retries. The main loop only calls the uploader after an explicit local UI sync request; it does not automatically drain the queue after reconnection. The uploader treats any 2xx response as success without parsing the submission ID or status, and deletes the file immediately. Add bounded retry scheduling with backoff, parse the JSON receipt, and delete only after a matching accepted or duplicate receipt.
- **Display and memory:** the ePaper shows capture and queue count, plus a transient upload message on the owner screen. It lacks distinct persistent queued, uploading, success, and failure indicators on the display. The upload path allocates the whole WAV plus multipart framing in PSRAM for each request; there is no measured heap or fragmentation data. Measure free and largest contiguous PSRAM before/after repeated uploads and Wi-Fi outages.
## Implemented in source
## Required firmware changes before an end-to-end trial
- Audio reads now check the codec return code, clear input buffers first, discard failed blocks, abort a capture after a read error, select one fixed microphone slot, and count read/recording errors. Capture duration uses the available pre-roll plus the requested post-roll; UTC capture-start and trigger timestamps are retained when time is valid.
- SD commits use checked WAV and sidecar writes, flush/fsync/close, WAV length/header validation, final renames, interrupted-commit recovery, a queue commit marker, oldest-first selection across the directory, an event-count cap, and a free-space reserve. Incomplete files are excluded from upload.
- Uploads stream file contents through `WiFiClientSecure` with a trusted CA, require HTTPS, send the actual `/api/pending/` fields, parse JSON receipts, verify the echoed event ID and submission ID, and retain files after ambiguous responses. Automatic retries use bounded exponential backoff and jitter. Source-embedded token placeholders were replaced with an ignored local header and optional NVS token; shared setup and management passwords were replaced with per-device NVS passwords.
- ePaper owner status reflects listening, recording, queue/offline, uploading, successful submission, retry failure, and audio error counters.
- Django now returns `event_id` in first and duplicate receipts and accepts an explicit `time_state=unknown` when the device clock was not synchronized. The same Pending Review and classifier pipeline remains in use.
1. Confirm the physical V2 revision and use its matching official support files. Do not copy Atom Echo GPIO assignments.
2. Point at `/api/pending/` and send `sensor_id`, stable `event_id`, UTC `captured_at`, measured `duration_seconds`, `firmware_version`, and `file`. Do not send a timestamp until NTP or the RTC is valid; preserve a reliable capture time with the queued file.
3. Configure CA-backed HTTPS and store the sensor token outside committed source. Reject HTTP on deployed builds.
4. Write queue items atomically, detect SD write errors, auto-retry with backoff, validate the JSON receipt, and retain files on ambiguous responses.
5. Show distinct recording, queued, uploading, success, and failure states; log I2S read failures and memory metrics.
## Verification performed
## Verification status
- Official Waveshare pin/support comparison at the pinned commit.
- The pinned `prepare_from_waveshare.sh` completed successfully against a checkout at that commit.
- Arduino CLI 1.5.1 compiled the sketch for ESP32-S3 with ESP32 core 3.3.0, 8 MB flash, OPI PSRAM, and the 8 MB partition scheme. The only emitted warnings were in copied Waveshare support and Espressif touch APIs.
- The `fireworks_detect` Django suite passed: 39 tests. Firmware-shaped unknown-time and receipt fields have focused backend tests.
- Firmware `.gitignore` patterns were checked for local credentials, copied support, and build artifacts.
Automated Django tests cover authenticated submission, storage, classification response handling, duplicate retry, invalid token/sensor/audio, conflict, and classifier outage. A temporary local Django instance was inspected with Playwright at desktop and 390 px mobile width; its Pending Review sensor detail rendered and showed no console errors. **No physical Waveshare board was flashed or tested.** Microphone fidelity, trigger timing, HTTPS certificate validation, firmware build, offline queue recovery, and on-device RAM stability remain hardware test items. Use a real recording and a controlled Wi-Fi outage for final acceptance.
## Still open
- **Firmware compile passed; no flash was performed.** Arduino CLI 1.5.1 compiled the sketch with ESP32 core 3.3.0, Waveshare support at the pinned commit, LVGL 8.4.0, ArduinoJson 7.4.3, 8 MB flash, and OPI PSRAM. The build reports 1,350,599 bytes of program storage (40%) and 99,368 bytes of global dynamic memory (30%). Device runtime RAM use is unmeasured.
- **No physical V2 test was performed.** The fixed microphone slot, actual audio fidelity, short successful codec reads, ePaper refresh, SD power-cut behavior, TLS handshake, and offline recovery need the real board.
- Waveshare's codec API reports read success/failure but not a byte count; a successful short read cannot be detected through the current wrapper.
- FAT does not provide an atomic transaction spanning WAV and sidecar. Valid interrupted commits are recovered; incomplete/orphan files remain on SD for manual inspection rather than being uploaded or overwritten.
- The uploader currently runs synchronously in the main loop. During a slow HTTPS attempt, the local web UI and display update may pause. Verify this on hardware and move upload to a worker task if it affects usability or watchdog health.
- Arduino source is not tracked by the current Django Git repository. Decide on a project-wide repository or a dedicated firmware repository before relying on source control for deployment.
See `../arduino/BoomCast_Waveshare_Arduino/docs/validation-checklist.md` for the pending physical acceptance checks. Do not treat this source review or the Django tests as hardware validation.
+4 -2
View File
@@ -2,8 +2,10 @@
`POST /api/pending/` accepts `multipart/form-data` from an active, registered sensor. Send `Authorization: Bearer <sensor token>`. The token determines the sensor and owner; send the sensor's database ID in `sensor_id` as an assertion, never as authority.
Required parts: `file` (16-bit PCM mono WAV), `sensor_id`, `event_id` (1–100 ASCII letters, digits, `_` or `-`), `captured_at` (UTC ISO 8601 timestamp with offset or Unix seconds), `duration_seconds` (positive number matching the WAV within 0.1 seconds), and `firmware_version` (1–64 printable characters). Optional: `trigger_type` (short label), `signal_rms`, `signal_peak` (finite nonnegative numbers), and `latitude`/`longitude` (untrusted device claims, retained only as metadata). No client location is promoted to the trusted event location.
Required parts: `file` (16-bit PCM mono WAV), `sensor_id`, `event_id` (1–100 ASCII letters, digits, `_` or `-`), `captured_at` (UTC ISO 8601 timestamp with offset or Unix seconds, or omit it with `time_state=unknown` when the device clock was not synchronized), `duration_seconds` (positive number matching the WAV within 0.1 seconds), and `firmware_version` (1–64 printable characters). Optional: `trigger_type` (short label), `signal_rms`, `signal_peak` (finite nonnegative numbers), and `latitude`/`longitude` (untrusted device claims, retained only as metadata). No client location is promoted to the trusted event location.
WAV data must be PCM, mono, 16-bit, at 16 kHz, at most 25 MiB, and 0.1–30 seconds long. A successful first submission returns HTTP 201 with `submission_id`, `status: pending`, and classifier results. A repeat of the same `(sensor, event_id)` returns HTTP 200 with the same `submission_id` and `duplicate: true`; a different body with the same ID returns HTTP 409. Errors have `code` and `detail` fields. HTTP 429 means retry after the `Retry-After` interval. HTTP 502 means classification failed and the device should retain the queued clip.
WAV data must be PCM, mono, 16-bit, at 16 kHz, at most 25 MiB, and 0.1–30 seconds long. A successful first submission returns HTTP 201 with `event_id`, `submission_id`, `status: pending`, and classifier results. A repeat of the same `(sensor, event_id)` returns HTTP 200 with the same `event_id`, `submission_id`, and `duplicate: true`; a different body with the same ID returns HTTP 409. Errors have `code` and `detail` fields. HTTP 429 means retry after the `Retry-After` interval. HTTP 502 means classification failed and the device should retain the queued clip.
The existing `/fireworks/classify/` route remains available for older clients. New firmware should use this contract. Pending audio stays behind the staff-only playback route and follows the existing accept/reject workflow and storage lifetime.
`captured_at` means the start of the actual recorded WAV. Optional `capture_started_at`, `triggered_at`, and `queued_at` are UTC ISO 8601 timestamps; `time_state=unknown` leaves the database capture time null. A missing timestamp without that explicit state is invalid.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+20 -5
View File
@@ -10,7 +10,7 @@ from django.urls import path, reverse
from django.utils.html import format_html
from django.utils.translation import gettext as _, gettext_lazy, ngettext
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor
from .models import BrowserProcessingSettings, ClassificationRule, Event, ManualReportRevision, PendingEvent, Sensor
from . import views as classifier_views
@@ -49,11 +49,11 @@ class BrowserProcessingSettingsAdmin(admin.ModelAdmin):
class ClassificationAdmin(admin.ModelAdmin):
list_display = ("original_filename", "source_type", "sensor", "occurrences", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
list_display = ("original_filename", "source_type", "sensor", "occurrences", "event_kind", "observation_duration_minutes", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
list_filter = ("source_type", "visually_confirmed", "created_at")
search_fields = ("original_filename",)
readonly_fields = ("audio_file", "sensor", "h3_cell", "direction_display", "direction_accuracy_degrees", "original_filename", "created_at", "pretty_classifier_response")
fields = ("audio_file", "sensor", "source_type", "occurrences", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
fields = ("audio_file", "sensor", "source_type", "occurrences", "observation_duration_minutes", "observation_duration_kind", "occurrence_time_approximate", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
change_form_template = "admin/fireworks_detect/classification_audio_change_form.html"
@admin.display(description=gettext_lazy("Direction"))
@@ -149,13 +149,28 @@ class PendingEventAdmin(ClassificationAdmin):
@admin.register(Event)
class EventAdmin(ClassificationAdmin):
readonly_fields = ClassificationAdmin.readonly_fields + ("approved_at",)
fields = ClassificationAdmin.fields + ("approved_at",)
readonly_fields = ClassificationAdmin.readonly_fields + ("submitted_at", "approved_at")
fields = ClassificationAdmin.fields + ("submitted_at", "approved_at")
def has_add_permission(self, request):
return False
@admin.register(ManualReportRevision)
class ManualReportRevisionAdmin(admin.ModelAdmin):
list_display = ("original_pending_id", "previous_occurrences", "new_occurrences", "previous_duration_minutes", "new_duration_minutes", "changed_at")
readonly_fields = list_display
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(Sensor)
class SensorAdmin(admin.ModelAdmin):
list_display = ("name", "owner", "is_active", "heartbeat_light", "last_heartbeat", "last_submission", "token_prefix", "archived_at")
+25
View File
@@ -0,0 +1,25 @@
"""Derived burst presentation rules; rates describe frequency, not loudness."""
from decimal import Decimal
BURST_MIN_BANGS = 3
DEFAULT_ESTIMATED_DURATION_MINUTES = 15
MODERATE_RATE_PER_15_MINUTES = Decimal("5")
INTENSE_RATE_PER_15_MINUTES = Decimal("10")
def burst_rate(bang_count, duration_minutes):
if bang_count < BURST_MIN_BANGS or not duration_minutes or duration_minutes <= 0:
return None
return Decimal(bang_count) * 15 / Decimal(duration_minutes)
def burst_intensity(bang_count, duration_minutes):
rate = burst_rate(bang_count, duration_minutes)
if rate is None:
return None
if rate >= INTENSE_RATE_PER_15_MINUTES:
return "intense"
if rate >= MODERATE_RATE_PER_15_MINUTES:
return "moderate"
return "light"
@@ -0,0 +1,57 @@
# Generated by Django 6.1.1 on 2026-10-09 23:43
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0011_event_captured_at_event_device_metadata_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='observation_duration_kind',
field=models.CharField(blank=True, choices=[('estimated', 'Estimated'), ('measured', 'Measured')], max_length=10),
),
migrations.AddField(
model_name='event',
name='observation_duration_minutes',
field=models.PositiveSmallIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='occurrence_time_approximate',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='pendingevent',
name='observation_duration_kind',
field=models.CharField(blank=True, choices=[('estimated', 'Estimated'), ('measured', 'Measured')], max_length=10),
),
migrations.AddField(
model_name='pendingevent',
name='observation_duration_minutes',
field=models.PositiveSmallIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='occurrence_time_approximate',
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name='ManualReportRevision',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('original_pending_id', models.PositiveBigIntegerField()),
('previous_occurrences', models.PositiveIntegerField()),
('new_occurrences', models.PositiveIntegerField()),
('previous_duration_minutes', models.PositiveSmallIntegerField(blank=True, null=True)),
('new_duration_minutes', models.PositiveSmallIntegerField(blank=True, null=True)),
('changed_at', models.DateTimeField(auto_now_add=True)),
('pending_event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='fireworks_detect.pendingevent')),
],
),
]
@@ -0,0 +1,18 @@
# Generated by Django 6.1.1 on 2026-10-09 23:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0012_event_observation_duration_kind_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='submitted_at',
field=models.DateTimeField(blank=True, null=True),
),
]
+55
View File
@@ -117,12 +117,19 @@ class ClassifiedAudio(models.Model):
SENSOR = "sensor", _("Sensor")
MANUAL = "manual", _("Manual report")
class DurationKind(models.TextChoices):
ESTIMATED = "estimated", _("Estimated")
MEASURED = "measured", _("Measured")
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d", blank=True)
sensor = models.ForeignKey(Sensor, null=True, blank=True, on_delete=models.SET_NULL, related_name="%(class)s_records")
original_filename = models.CharField(max_length=255)
classifier_response = models.JSONField()
source_type = models.CharField(max_length=10, choices=SourceType.choices, default=SourceType.SENSOR)
occurrences = models.PositiveIntegerField(default=1)
observation_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
observation_duration_kind = models.CharField(max_length=10, choices=DurationKind.choices, blank=True)
occurrence_time_approximate = models.BooleanField(default=False)
location = models.CharField(max_length=255, blank=True)
latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
@@ -154,6 +161,10 @@ class ClassifiedAudio(models.Model):
not math.isfinite(self.direction_accuracy_degrees) or self.direction_accuracy_degrees < 0
):
errors["direction_accuracy_degrees"] = _("Compass accuracy must be a finite, non-negative value.")
if self.observation_duration_minutes is not None and not 1 <= self.observation_duration_minutes <= 1440:
errors["observation_duration_minutes"] = _("Observation duration must be between 1 and 1,440 minutes.")
if bool(self.observation_duration_minutes) != bool(self.observation_duration_kind):
errors["observation_duration_kind"] = _("A duration needs an estimated or measured source.")
if errors:
raise ValidationError(errors)
@@ -172,6 +183,33 @@ class ClassifiedAudio(models.Model):
return "—"
return f"{self.direction_degrees:g}° ({self.direction_cardinal})"
@property
def is_burst(self):
from .bursts import BURST_MIN_BANGS
return self.occurrences >= BURST_MIN_BANGS
@property
def event_kind(self):
return "burst" if self.is_burst else "ordinary"
@property
def bangs_per_15_minutes(self):
from .bursts import burst_rate
if not self.observation_duration_kind:
return None
return burst_rate(self.occurrences, self.observation_duration_minutes)
@property
def burst_intensity(self):
from .bursts import burst_intensity
if not self.observation_duration_kind:
return None
return burst_intensity(self.occurrences, self.observation_duration_minutes)
@property
def burst_intensity_display(self):
return {"light": _("Light"), "moderate": _("Moderate"), "intense": _("Intense")}.get(self.burst_intensity)
@property
def predictions(self):
@@ -229,6 +267,7 @@ class PendingEvent(ClassifiedAudio):
@transaction.atomic
def approve(self):
event = Event.objects.create(
submitted_at=self.created_at,
audio_file=self.audio_file.name,
sensor=self.sensor,
captured_at=self.captured_at,
@@ -238,6 +277,9 @@ class PendingEvent(ClassifiedAudio):
classifier_response=self.classifier_response,
source_type=self.source_type,
occurrences=self.occurrences,
observation_duration_minutes=self.observation_duration_minutes,
observation_duration_kind=self.observation_duration_kind,
occurrence_time_approximate=self.occurrence_time_approximate,
location=self.location,
latitude=self.latitude,
longitude=self.longitude,
@@ -261,12 +303,25 @@ class Event(ClassifiedAudio):
"""A reviewed classification that is safe to appear in the event feed."""
approved_at = models.DateTimeField(auto_now_add=True)
submitted_at = models.DateTimeField(null=True, blank=True)
class Meta(ClassifiedAudio.Meta):
verbose_name = _("Event")
verbose_name_plural = _("Events")
class ManualReportRevision(models.Model):
"""Record edits to a session-owned manual Pending report."""
pending_event = models.ForeignKey(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL)
original_pending_id = models.PositiveBigIntegerField()
previous_occurrences = models.PositiveIntegerField()
new_occurrences = models.PositiveIntegerField()
previous_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
new_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
changed_at = models.DateTimeField(auto_now_add=True)
class SensorSubmission(models.Model):
"""Durable idempotency receipt, retained after moderation."""
@@ -1,9 +1,13 @@
{% load i18n %}
{% if event.source_type == "manual" %}
<h2>{% trans "Manual fireworks report" %}</h2>
<h2>{% if event.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Manual fireworks report" %}{% endif %}</h2>
<p class="meta">{% blocktrans with date=event.approved_at|date:"j M Y, H:i" %}Approved {{ date }} · Reported manually{% endblocktrans %}</p>
<h3>{% trans "Report details" %}</h3>
<div class="prediction prediction--firework"><strong>{% trans "Occurrences" %}</strong><span>{{ event.occurrences }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Occurred" %}</strong><span>{% if event.occurrence_time_approximate %}{% trans "Approximately" %} {% endif %}{{ event.captured_at|date:"j M Y, H:i"|default:"Unknown" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Submitted" %}</strong><span>{% if event.submitted_at %}{{ event.submitted_at|date:"j M Y, H:i" }}{% else %}{% trans "Unknown" %}{% endif %}</span></div>
{% if event.is_burst %}<div class="prediction prediction--firework"><strong>{% trans "Duration" %}</strong><span>{% if event.observation_duration_minutes %}{{ event.observation_duration_minutes }} {% if event.observation_duration_kind == "estimated" %}{% trans "minutes (estimated)" %}{% else %}{% trans "minutes (measured)" %}{% endif %}{% else %}{% trans "Unknown" %}{% endif %}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Intensity" %}</strong><span>{% if event.burst_intensity %}{{ event.burst_intensity_display }} · {{ event.bangs_per_15_minutes|floatformat:1 }} {% trans "bangs per 15 minutes" %}{% else %}{% trans "Not rated" %}{% endif %}</span></div>{% endif %}
<div class="prediction prediction--firework"><strong>{% trans "Location" %}</strong><span>{{ event.location|default:"Not recorded" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Captured location" %}</strong><span>{{ event_h3_cell|default:"Not recorded" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Direction" %}</strong><span>{{ event.direction_display }}</span></div>
@@ -5,7 +5,7 @@
<span class="event__content">
{% if event.source_type == "manual" %}
<span class="event__source">{% trans "Manual report" %}</span>
<strong>{% trans "Manual fireworks report" %}</strong><br>
<strong>{% if event.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Manual fireworks report" %}{% endif %}</strong><br>
<small>{% blocktrans count count=event.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}{% if event.location %} · {{ event.location }}{% endif %}</small>
{% else %}
<span class="event__source">{% trans "Sensor classification" %}</span>
@@ -20,6 +20,12 @@
<input id="manual-longitude" name="longitude" type="hidden">
<input id="manual-direction-degrees" name="direction_degrees" type="hidden">
<input id="manual-direction-accuracy" name="direction_accuracy_degrees" type="hidden">
<div class="manual-report__occurrence">
<label class="manual-report__label" for="manual-occurred-at">{% trans "When did it happen?" %}</label>
<div class="manual-report__time-row"><input id="manual-occurred-at" name="occurred_at" type="datetime-local" aria-describedby="manual-time-help"><button id="manual-use-now" type="button">{% trans "Use now" %}</button></div>
<label class="manual-report__check"><input id="manual-time-approximate" name="time_approximate" type="checkbox"> {% trans "Time is approximate" %}</label>
<small id="manual-time-help">{% trans "Leave the time empty to use the submission time." %}</small>
</div>
<div class="manual-report__primary">
<div class="manual-report__quantity">
<label class="manual-report__label" for="manual-occurrences">{% trans "How many times did you hear it?" %}</label>
@@ -28,6 +34,13 @@
<input id="manual-occurrences" name="occurrences" type="number" min="1" max="1000" value="1" required inputmode="numeric">
<button id="manual-increase" type="button" aria-label="{% trans 'Increase occurrences' %}">+</button>
</div>
<p id="manual-burst-status" class="manual-report__burst-status" role="status">{% trans "Ordinary report" %}</p>
</div>
<div id="manual-burst-duration" class="manual-report__duration">
<label class="manual-report__label" for="manual-duration-minutes">{% trans "Estimated observation window (minutes, for 3+ bangs)" %}</label>
<input id="manual-duration-minutes" name="duration_minutes" type="number" min="1" max="1440" value="15" inputmode="numeric">
<label class="manual-report__check"><input id="manual-duration-confirmed" name="duration_confirmed" type="checkbox"> {% trans "Use this estimated window for burst intensity" %}</label>
<small>{% trans "Optional. Without an accepted window, BoomCast reports the count without an intensity rating." %}</small>
</div>
{% include "fireworks_detect/includes/manual_direction_panel.html" %}
</div>
@@ -55,7 +68,7 @@
<p id="burst-error" role="alert" hidden></p>
</div>
</section>
<button id="manual-submit" class="manual-report__submit" type="button"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
<button id="manual-submit" class="manual-report__submit" type="submit"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
</form>
<div id="manual-submission" class="manual-report__submission" aria-live="polite"></div>
<div id="manual-compass-home">
@@ -1,8 +1,8 @@
{% load i18n %}
<section class="map-panel" aria-label="{% trans "Manual fireworks report map" %}">
<div class="map-header"><strong>{% trans "Manual reports · privacy-preserving H3 cells" %}</strong><span class="live"><i></i> {% blocktrans with resolution=h3_resolution %}H3 resolution {{ resolution }} · sensor layer disabled{% endblocktrans %}</span></div>
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="{% trans "Interactive map of manual fireworks reports" %}"></div>
<aside class="legend" aria-label="{% trans "Map legend" %}"><h2>{% trans "Manual reports" %}</h2><div><span class="legend-dot"></span> {% trans "Report marker at H3-cell centre" %}</div><div><span class="legend-ring"></span> {% blocktrans with resolution=h3_resolution %}H3 cell (resolution {{ resolution }}){% endblocktrans %}</div><div><span class="legend-line"></span> {% trans "Saved compass direction" %}</div></aside>
<section class="map-panel" aria-label="{% trans "Reviewed fireworks report map" %}">
<div class="map-header"><strong>{% trans "Reviewed reports · privacy-preserving H3 cells" %}</strong><span class="live"><i></i> {% blocktrans with resolution=h3_resolution %}H3 resolution {{ resolution }}{% endblocktrans %}</span></div>
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="{% trans "Interactive map of reviewed fireworks reports" %}"></div>
<aside class="legend" aria-label="{% trans "Map legend" %}"><h2>{% trans "Map legend" %}</h2>{% if map_source != "sensor" %}<div><span class="legend-dot"></span> {% trans "Manual report" %}</div>{% endif %}{% if map_source == "sensor" or map_source == "all" %}<div><span class="legend-sensor"></span> {% trans "Sensor event" %}</div>{% endif %}<div><span class="legend-ring"></span> {% blocktrans with resolution=h3_resolution %}H3 cell (resolution {{ resolution }}){% endblocktrans %}</div>{% if map_source != "sensor" %}<div><span class="legend-line"></span> {% trans "Saved compass direction" %}</div>{% endif %}</aside>
</div>
</section>
{{ h3_cells|json_script:"h3-cells-data" }}
@@ -6,12 +6,24 @@
<p>{{ error }}</p>
{% else %}
<span class="manual-submission__icon" aria-hidden="true">✓</span>
<strong>{% trans "Report received!" %}</strong>
<strong>{% if updated %}{% trans "Report updated!" %}{% else %}{% trans "Report received!" %}{% endif %}</strong>
<p>{% trans "Thank you. Your report helps map fireworks nearby." %}</p>
<p class="manual-submission__summary">
{{ pending.created_at|date:"H:i" }} ·
{% if pending.occurrence_time_approximate %}{% trans "Approximately" %} {% endif %}{{ pending.captured_at|date:"j M Y, H:i" }} ·
{% blocktrans count count=pending.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}
{% if direction_label %} · {{ direction_label }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
{% if pending.direction_degrees is not None %} · {{ direction_label|default:pending.direction_cardinal }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
</p>
<p>{% if pending.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Ordinary report" %}{% endif %} · {% trans "Submitted" %} {{ pending.created_at|date:"j M Y, H:i" }}</p>
{% if pending.is_burst %}<p>{% trans "Duration" %}: {% if pending.observation_duration_minutes %}{{ pending.observation_duration_minutes }} {% trans "minutes (estimated)" %}{% else %}{% trans "Unknown" %}{% endif %}</p>
<p>{% trans "Intensity" %}: {% if pending.burst_intensity %}{{ pending.burst_intensity_display }} ({{ pending.bangs_per_15_minutes|floatformat:1 }} {% trans "bangs per 15 minutes" %}){% else %}{% trans "Not rated" %}{% endif %}</p>{% endif %}
{% if editable %}<form class="manual-submission__edit" method="post" action="{% url 'fireworks_detect:update_manual_pending' pending.pk %}" hx-post="{% url 'fireworks_detect:update_manual_pending' pending.pk %}" hx-target="#manual-submission" hx-swap="outerHTML">
{% csrf_token %}
<label for="manual-edit-count">{% trans "Correct bang count" %}</label>
<input id="manual-edit-count" name="occurrences" type="number" min="1" max="1000" value="{{ pending.occurrences }}" required>
<label for="manual-edit-duration">{% trans "Estimated minutes for a burst" %}</label>
<input id="manual-edit-duration" name="duration_minutes" type="number" min="1" max="1440" value="{{ pending.observation_duration_minutes|default:15 }}">
<label><input name="duration_confirmed" type="checkbox" {% if pending.observation_duration_kind %}checked{% endif %}> {% trans "Use this estimated window" %}</label>
<button type="submit">{% trans "Update report" %}</button>
</form>{% endif %}
{% endif %}
</div>
@@ -14,12 +14,12 @@
{% include "fireworks_detect/includes/navigation.html" with active_page="map" %}
<section class="headline" aria-labelledby="map-title">
<div><p class="kicker">{% trans "Manual report intelligence" %}</p><h1 id="map-title">{% trans "Sound activity map." %}</h1></div>
<p>{% trans "Reviewed manual reports with a captured location appear as their H3 cell, not their precise coordinates. Saved phone compass readings show the reported direction of the sound." %}</p>
<div><p class="kicker">{% trans "Reviewed sound reports" %}</p><h1 id="map-title">{% trans "Sound activity map." %}</h1></div>
<p>{% trans "Reviewed reports with a stored location appear at their H3 cell centre, not their precise coordinates. Sensor events use only saved event locations; device-reported coordinates are not trusted for this map." %}</p>
</section>
<form class="filters" method="get" action="{% url 'fireworks_detect:map' %}" aria-label="{% trans "Map filters" %}">
<div class="filter"><label for="event-source">{% trans "Source" %}</label><select id="event-source" disabled><option selected>{% trans "Manual reports" %}</option><option>{% trans "Sensor events — coming soon" %}</option></select></div>
<div class="filter"><label for="event-source">{% trans "Source" %}</label><select id="event-source" name="source"><option value="manual" {% if map_filters.source == "manual" %}selected{% endif %}>{% trans "Manual reports" %}</option><option value="sensor" {% if map_filters.source == "sensor" %}selected{% endif %}>{% trans "Sensor events" %}</option><option value="all" {% if map_filters.source == "all" %}selected{% endif %}>{% trans "Both sources" %}</option></select></div>
<div class="filter"><label for="range">{% trans "Period" %}</label><select id="range" name="range"><option value="7" {% if map_filters.range == "7" %}selected{% endif %}>{% trans "Last 7 days" %}</option><option value="14" {% if map_filters.range == "14" %}selected{% endif %}>{% trans "Last 2 weeks" %}</option><option value="30" {% if map_filters.range == "30" %}selected{% endif %}>{% trans "Last 30 days" %}</option><option value="all" {% if map_filters.range == "all" %}selected{% endif %}>{% trans "All time" %}</option><option value="custom" {% if map_filters.range == "custom" %}selected{% endif %}>{% trans "Custom range" %}</option></select></div>
<div class="filter"><label for="from-date">{% trans "From" %}</label><input id="from-date" name="from" type="date" value="{{ map_filters.date_from }}"></div>
<div class="filter"><label for="to-date">{% trans "To" %}</label><input id="to-date" name="to" type="date" value="{{ map_filters.date_to }}"></div>
+17 -1
View File
@@ -44,11 +44,18 @@ class SensorSubmissionTests(TestCase):
def test_authenticated_upload_is_classified_and_retry_is_idempotent(self):
response_body = io.BytesIO(json.dumps({"predictions": [{"class": "Fireworks", "score": 0.8}], "duration_seconds": 1}).encode())
with TemporaryDirectory() as media, override_settings(MEDIA_ROOT=media), patch("fireworks_detect.views.urlopen", return_value=response_body) as classify:
first = self.submit(trigger_type="audio_spike", latitude="52.1")
first = self.submit(
trigger_type="audio_spike", latitude="52.1",
capture_started_at="2026-10-09T10:00:00Z",
triggered_at="2026-10-09T10:00:02Z",
queued_at="2026-10-09T10:00:05Z",
)
second = self.submit()
self.assertEqual(first.status_code, 201)
self.assertEqual(second.status_code, 200)
self.assertEqual(first.json()["submission_id"], second.json()["submission_id"])
self.assertEqual(first.json()["event_id"], "device-event-1")
self.assertEqual(second.json()["event_id"], "device-event-1")
self.assertEqual(PendingEvent.objects.count(), 1)
self.assertEqual(SensorSubmission.objects.count(), 1)
self.assertEqual(classify.call_count, 1)
@@ -57,8 +64,17 @@ class SensorSubmissionTests(TestCase):
self.assertEqual(pending.source_type, "sensor")
self.assertFalse(pending.latitude)
self.assertEqual(pending.device_metadata["latitude"], "52.1")
self.assertEqual(pending.device_metadata["triggered_at"], "2026-10-09T10:00:02Z")
self.assertTrue(pending.audio_file.storage.exists(pending.audio_file.name))
def test_unknown_capture_time_is_explicit_and_retained(self):
response_body = io.BytesIO(json.dumps({"predictions": [], "duration_seconds": 1}).encode())
with TemporaryDirectory() as media, override_settings(MEDIA_ROOT=media), patch("fireworks_detect.views.urlopen", return_value=response_body):
response = self.submit(captured_at="", time_state="unknown")
self.assertEqual(response.status_code, 201)
self.assertIsNone(PendingEvent.objects.get().captured_at)
self.assertEqual(PendingEvent.objects.get().device_metadata["time_state"], "unknown")
def test_pending_admin_shows_sensor_details(self):
staff = get_user_model().objects.create_superuser("reviewer-sensor", password="test")
pending = PendingEvent.objects.create(sensor=self.sensor, source_type="sensor", original_filename="event.wav", classifier_response={"predictions": [{"class": "Fireworks", "score": 0.8}]}, firmware_version="0.1.0-concept", device_metadata={"trigger_type": "audio_spike"})
+143 -5
View File
@@ -14,7 +14,8 @@ from django.urls import reverse
from django.utils import timezone
from .h3_utils import cell_from_coordinates, h3_resolution
from .models import ClassificationRule, Event, PendingEvent
from .models import ClassificationRule, Event, ManualReportRevision, PendingEvent
from .bursts import burst_intensity, burst_rate
class ClassificationRuleApiTests(TestCase):
@@ -88,6 +89,114 @@ class ManualPendingEventTests(TestCase):
self.assertContains(response, 'data-result="error"', status_code=400)
self.assertFalse(PendingEvent.objects.exists())
def test_burst_boundaries_and_intensity_rates(self):
for count, duration, category in ((1, 15, None), (2, 15, None), (3, 15, "light"), (10, 15, "intense"), (10, 30, "moderate"), (10, 60, "light")):
with self.subTest(count=count, duration=duration):
pending = PendingEvent(occurrences=count, observation_duration_minutes=duration, observation_duration_kind="estimated")
self.assertEqual(pending.is_burst, count >= 3)
self.assertEqual(pending.burst_intensity, category)
self.assertEqual(burst_rate(10, 30), Decimal("5"))
self.assertEqual(burst_intensity(10, None), None)
def test_server_rendered_quick_report_with_estimated_duration_and_approximate_time(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "10", "occurred_at": "2026-10-09T20:30", "time_approximate": "on",
"duration_minutes": "30", "duration_confirmed": "on",
})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Burst Event")
self.assertContains(response, "Moderate")
pending = PendingEvent.objects.get()
self.assertEqual(pending.occurrences, 10)
self.assertEqual(pending.observation_duration_minutes, 30)
self.assertEqual(pending.observation_duration_kind, "estimated")
self.assertTrue(pending.occurrence_time_approximate)
self.assertNotEqual(pending.captured_at, pending.created_at)
self.assertEqual(pending.bangs_per_15_minutes, Decimal("5"))
reviewed = pending.approve()
self.assertEqual(reviewed.observation_duration_minutes, 30)
self.assertEqual(reviewed.captured_at, pending.captured_at)
self.assertEqual(reviewed.submitted_at, pending.created_at)
def test_unaccepted_window_has_no_intensity_and_legacy_burst_stays_compatible(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {"occurrences": "3", "duration_minutes": "15"})
self.assertEqual(response.status_code, 200)
pending = PendingEvent.objects.get()
self.assertTrue(pending.is_burst)
self.assertIsNone(pending.observation_duration_minutes)
self.assertIsNone(pending.burst_intensity)
old = Event.objects.create(occurrences=10, original_filename="old report", classifier_response={}, source_type="manual")
self.assertTrue(old.is_burst)
self.assertIsNone(old.burst_intensity)
accepted = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "3", "duration_confirmed": "on",
})
self.assertEqual(accepted.status_code, 200)
self.assertEqual(PendingEvent.objects.latest("pk").observation_duration_minutes, 15)
measured = Event.objects.create(occurrences=10, original_filename="measured", classifier_response={},
observation_duration_minutes=30, observation_duration_kind="measured")
self.assertEqual(measured.burst_intensity, "moderate")
self.assertEqual(measured.observation_duration_kind, "measured")
def test_session_scoped_count_edits_recalculate_and_preserve_original_time(self):
self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "2", "occurred_at": "2026-10-09T20:30",
})
pending = PendingEvent.objects.get()
occurred_at, submitted_at = pending.captured_at, pending.created_at
url = reverse("fireworks_detect:update_manual_pending", args=[pending.pk])
response = self.client.post(url, {"occurrences": "3", "duration_minutes": "15", "duration_confirmed": "on"})
self.assertEqual(response.status_code, 200)
pending.refresh_from_db()
self.assertEqual(pending.burst_intensity, "light")
self.client.post(url, {"occurrences": "10", "duration_minutes": "10", "duration_confirmed": "on"})
pending.refresh_from_db()
self.assertEqual(pending.burst_intensity, "intense")
self.client.post(url, {"occurrences": "10", "duration_minutes": "30", "duration_confirmed": "on"})
pending.refresh_from_db()
self.assertEqual(pending.burst_intensity, "moderate")
self.client.post(url, {"occurrences": "2"})
pending.refresh_from_db()
self.assertFalse(pending.is_burst)
self.assertIsNone(pending.burst_intensity)
self.assertEqual(pending.captured_at, occurred_at)
self.assertEqual(pending.created_at, submitted_at)
self.assertEqual(ManualReportRevision.objects.filter(original_pending_id=pending.pk).count(), 4)
from django.test import Client
self.assertEqual(Client().post(url, {"occurrences": "10"}).status_code, 404)
def test_invalid_estimated_duration_and_future_occurrence_are_rejected(self):
for data in (
{"occurrences": "10", "duration_confirmed": "on", "duration_minutes": "0"},
{"occurrences": "10", "duration_confirmed": "on", "duration_minutes": "1441"},
{"occurrences": "10", "occurred_at": (timezone.localtime() + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M")},
):
with self.subTest(data=data):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), data)
self.assertEqual(response.status_code, 400)
self.assertFalse(PendingEvent.objects.exists())
def test_map_data_exposes_derived_burst_fields_without_precise_location(self):
event = Event.objects.create(
original_filename="manual burst", classifier_response={}, source_type="manual", occurrences=10,
latitude=Decimal("52.123456"), longitude=Decimal("5.987654"),
observation_duration_minutes=30, observation_duration_kind="estimated",
occurrence_time_approximate=True, captured_at=timezone.now() - timedelta(hours=1),
)
from .views import _events_for_map
mapped, _ = _events_for_map({"date_from": None, "date_to": None, "visual": "all", "source": "manual"})
item = next(item for item in mapped if item["occurrences"] == 10)
self.assertEqual(item["event_kind"], "burst")
self.assertEqual(item["observation_duration_kind"], "estimated")
self.assertEqual(item["bangs_per_15_minutes"], 5.0)
self.assertEqual(item["burst_intensity"], "moderate")
self.assertTrue(item["occurrence_time_approximate"])
self.assertIsNone(item["submitted_on"])
self.assertNotIn("latitude", item)
self.assertNotIn("longitude", item)
def test_manual_report_accepts_optional_wav_on_the_same_pending_event(self):
from tempfile import TemporaryDirectory
@@ -220,7 +329,7 @@ class ManualPendingEventTests(TestCase):
)
list_response = self.client.get(reverse("fireworks_detect:events_list"))
self.assertContains(list_response, "Manual fireworks report")
self.assertContains(list_response, "Burst Event")
self.assertContains(list_response, "5 occurrences")
self.assertContains(list_response, "Back garden")
@@ -238,7 +347,7 @@ class ManualPendingEventTests(TestCase):
self.assertEqual(h3_resolution(), 8)
self.assertTrue(cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654")))
def test_map_uses_manual_h3_data_and_excludes_sensor_events(self):
def test_map_source_filter_separates_reviewed_sensor_events(self):
manual_cell = cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654"))
sensor_cell = cell_from_coordinates(Decimal("53.123456"), Decimal("5.987654"))
Event.objects.create(
@@ -271,12 +380,41 @@ class ManualPendingEventTests(TestCase):
self.assertContains(response, '"direction_degrees": 237.0')
self.assertContains(response, "data-h3-resolution")
self.assertContains(response, 'type="module"')
self.assertContains(response, "sensor layer disabled")
self.assertContains(response, "Sensor events — coming soon")
self.assertContains(response, 'name="source"')
self.assertContains(response, "Sensor events")
self.assertNotContains(response, sensor_cell)
self.assertNotContains(response, "52.123456")
self.assertNotContains(response, "H3 demo cell")
sensor_response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "sensor"})
self.assertEqual(len(sensor_response.context["map_events"]), 1)
self.assertEqual(sensor_response.context["map_events"][0]["source_type"], "sensor")
self.assertContains(sensor_response, sensor_cell)
self.assertNotContains(sensor_response, manual_cell)
self.assertNotContains(sensor_response, "53.123456")
both_response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "all"})
self.assertEqual(len(both_response.context["map_events"]), 2)
self.assertContains(both_response, manual_cell)
self.assertContains(both_response, sensor_cell)
def test_sensor_map_excludes_pending_and_device_only_locations(self):
pending_cell = cell_from_coordinates(Decimal("51.876543"), Decimal("5.123456"))
PendingEvent.objects.create(
original_filename="pending.wav", classifier_response={},
source_type=PendingEvent.SourceType.SENSOR, h3_cell=pending_cell,
)
Event.objects.create(
original_filename="unlocated.wav", classifier_response={},
source_type=Event.SourceType.SENSOR,
device_metadata={"latitude": "52.654321", "longitude": "5.654321"},
)
response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "sensor"})
self.assertEqual(response.context["map_events"], [])
self.assertNotContains(response, pending_cell)
self.assertNotContains(response, "52.654321")
def test_map_date_range_filters_manual_reports(self):
recent_cell = cell_from_coordinates(Decimal("52.400000"), Decimal("5.700000"))
older_cell = cell_from_coordinates(Decimal("53.400000"), Decimal("5.700000"))
+2
View File
@@ -12,6 +12,7 @@ from .views import (
pending_audio,
manual_direction_panel,
submit_manual_pending_event,
update_manual_pending_event,
submit_pending_event,
sensor_heartbeat,
submit_sensor_pending,
@@ -29,6 +30,7 @@ urlpatterns = [
path("heartbeat/", sensor_heartbeat, name="sensor_heartbeat"),
path("submit-pending/", submit_pending_event, name="submit_pending"),
path("submit-manual-pending/", submit_manual_pending_event, name="submit_manual_pending"),
path("submit-manual-pending/<int:event_id>/update/", update_manual_pending_event, name="update_manual_pending"),
path("manual-direction/", manual_direction_panel, name="manual_direction_panel"),
path("events/", events_view, name="events"),
path("events/list/", events_list, name="events_list"),
+128 -18
View File
@@ -29,7 +29,8 @@ from django.views.decorators.http import require_http_methods
from .h3_utils import cell_boundary, cell_center, cell_from_coordinates, h3_resolution
from .browser_policy import advisory_browser_metadata, browser_config, browser_policy
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor, SensorSubmission
from .models import BrowserProcessingSettings, ClassificationRule, Event, ManualReportRevision, PendingEvent, Sensor, SensorSubmission
from .bursts import BURST_MIN_BANGS, DEFAULT_ESTIMATED_DURATION_MINUTES, burst_intensity, burst_rate
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
@@ -85,17 +86,24 @@ def _map_filters(request):
visual = request.GET.get("visual", "all")
if visual not in {"all", "yes", "no"}:
visual = "all"
source = request.GET.get("source", "manual")
if source not in {"manual", "sensor", "all"}:
source = "manual"
return {
"date_from": date_from,
"date_to": date_to,
"range": selected_range,
"visual": visual,
"source": source,
}
def _events_for_map(filters):
"""Create privacy-preserving map data for reviewed manual reports only."""
events = Event.objects.filter(source_type=Event.SourceType.MANUAL)
"""Create H3 map data for reviewed events with a stored, trusted location."""
source = filters.get("source", "manual")
events = Event.objects.all()
if source != "all":
events = events.filter(source_type=source)
if filters["date_from"]:
events = events.filter(created_at__date__gte=filters["date_from"])
if filters["date_to"]:
@@ -109,7 +117,8 @@ def _events_for_map(filters):
mapped_events = []
for event in events.values(
"h3_cell", "latitude", "longitude", "occurrences", "visually_confirmed",
"direction_degrees", "direction_accuracy_degrees", "created_at",
"direction_degrees", "direction_accuracy_degrees", "created_at", "captured_at", "submitted_at", "source_type",
"observation_duration_minutes", "observation_duration_kind", "occurrence_time_approximate",
):
# Coordinates are used only here to derive an H3 cell; they never leave the server.
h3_cell = event["h3_cell"] or cell_from_coordinates(event["latitude"], event["longitude"])
@@ -124,13 +133,26 @@ def _events_for_map(filters):
"center": center,
"reports": 0,
"occurrences": 0,
"manual_reports": 0,
"sensor_reports": 0,
})
aggregate["reports"] += 1
aggregate["occurrences"] += event["occurrences"]
aggregate[f'{event["source_type"]}_reports'] += 1
rate = burst_rate(event["occurrences"], event["observation_duration_minutes"]) if event["observation_duration_kind"] else None
mapped_events.append({
"cell": h3_cell,
"center": center,
"source_type": event["source_type"],
"occurrences": event["occurrences"],
"event_kind": "burst" if event["occurrences"] >= BURST_MIN_BANGS else "ordinary",
"observation_duration_minutes": event["observation_duration_minutes"],
"observation_duration_kind": event["observation_duration_kind"],
"bangs_per_15_minutes": float(rate) if rate is not None else None,
"burst_intensity": burst_intensity(event["occurrences"], event["observation_duration_minutes"]) if event["observation_duration_kind"] else None,
"occurrence_time_approximate": event["occurrence_time_approximate"],
"occurred_on": (event["captured_at"] or event["created_at"]).date().isoformat(),
"submitted_on": event["submitted_at"].date().isoformat() if event["submitted_at"] else None,
"visually_confirmed": event["visually_confirmed"],
# A day is sufficient for this map and avoids sharing a precise report time.
"reported_on": event["created_at"].date().isoformat(),
@@ -152,11 +174,13 @@ def fireworks_map_view(request):
"h3_cells": h3_cells,
"map_events": map_events,
"mapped_event_count": len(map_events),
"map_source": filters["source"],
"map_filters": {
"date_from": filters["date_from"].isoformat() if filters["date_from"] else "",
"date_to": filters["date_to"].isoformat() if filters["date_to"] else "",
"range": filters["range"],
"visual": filters["visual"],
"source": filters["source"],
},
})
@@ -395,6 +419,10 @@ def submit_manual_pending_event(request):
status=400,
)
details, error = _manual_observation_details(request, occurrences)
if error:
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": error}, status=400)
uploaded_file = request.FILES.get("audio")
if uploaded_file:
if uploaded_file.size > MAX_AUDIO_SIZE or uploaded_file.content_type not in ("audio/wav", "audio/wave", "audio/x-wav"):
@@ -415,6 +443,7 @@ def submit_manual_pending_event(request):
classifier_response={},
source_type=PendingEvent.SourceType.MANUAL,
occurrences=occurrences,
**details,
latitude=latitude,
longitude=longitude,
h3_cell=h3_cell or "",
@@ -422,15 +451,86 @@ def submit_manual_pending_event(request):
direction_accuracy_degrees=direction_accuracy_degrees,
direction_source="device_compass" if direction_degrees is not None else "",
)
owned = request.session.get("manual_pending_ids", [])
request.session["manual_pending_ids"] = (owned + [pending.pk])[-20:]
direction_names = {
"N": _("North"), "NE": _("Northeast"), "E": _("East"), "SE": _("Southeast"),
"S": _("South"), "SW": _("Southwest"), "W": _("West"), "NW": _("Northwest"),
}
return render(request, "fireworks_detect/manual_pending_submission.html", {
"pending": pending,
"editable": True,
"direction_label": direction_names.get(pending.direction_cardinal) if direction_degrees is not None else "",
})
def _manual_observation_details(request, occurrences):
raw_time = request.POST.get("occurred_at", "").strip()
if raw_time:
occurred_at = parse_datetime(raw_time)
if occurred_at is None:
return None, _("Enter a valid occurrence date and time.")
if timezone.is_naive(occurred_at):
occurred_at = timezone.make_aware(occurred_at, timezone.get_current_timezone())
if occurred_at > timezone.now() + timedelta(minutes=5):
return None, _("Occurrence time cannot be in the future.")
else:
occurred_at = timezone.now()
details = {
"captured_at": occurred_at,
"occurrence_time_approximate": request.POST.get("time_approximate") == "on",
"observation_duration_minutes": None,
"observation_duration_kind": "",
}
if occurrences >= BURST_MIN_BANGS and request.POST.get("duration_confirmed") == "on":
raw_duration = request.POST.get("duration_minutes", "").strip()
try:
duration = int(raw_duration) if raw_duration else DEFAULT_ESTIMATED_DURATION_MINUTES
except ValueError:
return None, _("Enter a duration between 1 and 1,440 minutes.")
if not 1 <= duration <= 1440:
return None, _("Enter a duration between 1 and 1,440 minutes.")
details["observation_duration_minutes"] = duration
details["observation_duration_kind"] = PendingEvent.DurationKind.ESTIMATED
return details, None
@require_http_methods(["POST"])
@never_cache
def update_manual_pending_event(request, event_id):
if event_id not in request.session.get("manual_pending_ids", []):
raise Http404
try:
occurrences = int(request.POST.get("occurrences", ""))
except (TypeError, ValueError):
occurrences = 0
if not 1 <= occurrences <= 1000:
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("Choose between 1 and 1,000 occurrences.")}, status=400)
_, error = _manual_observation_details(request, occurrences)
if error:
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": error}, status=400)
# The occurrence time and location belong to the original observation.
duration = None
kind = ""
if occurrences >= BURST_MIN_BANGS and request.POST.get("duration_confirmed") == "on":
raw = request.POST.get("duration_minutes", "").strip()
duration = int(raw) if raw else DEFAULT_ESTIMATED_DURATION_MINUTES
kind = PendingEvent.DurationKind.ESTIMATED
with transaction.atomic():
pending = get_object_or_404(PendingEvent.objects.select_for_update(), pk=event_id, source_type=PendingEvent.SourceType.MANUAL)
ManualReportRevision.objects.create(
pending_event=pending, original_pending_id=pending.pk,
previous_occurrences=pending.occurrences, new_occurrences=occurrences,
previous_duration_minutes=pending.observation_duration_minutes,
new_duration_minutes=duration,
)
pending.occurrences = occurrences
pending.observation_duration_minutes = duration
pending.observation_duration_kind = kind
pending.save(update_fields=["occurrences", "observation_duration_minutes", "observation_duration_kind"])
return render(request, "fireworks_detect/manual_pending_submission.html", {"pending": pending, "editable": True, "updated": True})
@never_cache
def events_list(request):
return render(request, "fireworks_detect/events_list.html", {"events": Event.objects.all()[:30]})
@@ -549,23 +649,30 @@ def submit_sensor_pending(request):
finally:
uploaded.seek(0)
raw_time = request.POST.get("captured_at", "")
try:
captured_at = datetime.fromtimestamp(float(raw_time), datetime_timezone.utc) if re.fullmatch(r"[0-9]{10}(?:\.[0-9]+)?", raw_time) else parse_datetime(raw_time)
if captured_at is None or timezone.is_naive(captured_at):
raise ValueError()
if captured_at > timezone.now() + timedelta(minutes=5):
raise ValueError()
except (ValueError, OverflowError, OSError):
return _submission_error("invalid_capture_time", "captured_at must be a valid past UTC time.")
if not raw_time and request.POST.get("time_state") == "unknown":
captured_at = None
else:
try:
captured_at = datetime.fromtimestamp(float(raw_time), datetime_timezone.utc) if re.fullmatch(r"[0-9]{10}(?:\.[0-9]+)?", raw_time) else parse_datetime(raw_time)
if captured_at is None or timezone.is_naive(captured_at):
raise ValueError()
if captured_at > timezone.now() + timedelta(minutes=5):
raise ValueError()
except (ValueError, OverflowError, OSError):
return _submission_error("invalid_capture_time", "Provide a valid UTC captured_at or time_state=unknown.")
firmware = request.POST.get("firmware_version", "")
if not 1 <= len(firmware) <= 64 or not firmware.isprintable():
return _submission_error("invalid_firmware_version", "Provide a printable firmware_version of at most 64 characters.")
metadata = {}
for key in ("trigger_type", "signal_rms", "signal_peak", "latitude", "longitude"):
metadata = {"time_state": "unknown"} if captured_at is None else {}
for key in ("trigger_type", "signal_rms", "signal_peak", "latitude", "longitude", "capture_started_at", "triggered_at", "queued_at"):
value = request.POST.get(key)
if value is None or value == "":
continue
if key == "trigger_type":
if key.endswith("_at"):
parsed = parse_datetime(value)
if parsed is None or timezone.is_naive(parsed):
return _submission_error("invalid_metadata", f"Invalid {key}.")
elif key == "trigger_type":
if len(value) > 64 or not value.isprintable():
return _submission_error("invalid_metadata", "Invalid trigger_type.")
else:
@@ -585,7 +692,7 @@ def submit_sensor_pending(request):
if existing:
if existing.audio_sha256 != audio_hash:
return _submission_error("event_id_conflict", "event_id already belongs to different audio.", 409)
return JsonResponse({"submission_id": str(existing.submission_id), "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True}, status=200)
return JsonResponse({"submission_id": str(existing.submission_id), "event_id": event_id, "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True}, status=200)
rate_key = f"sensor-submissions:{sensor.pk}"
if cache.get(rate_key, 0) >= 30:
response = _submission_error("rate_limited", "Sensor submission rate exceeded.", 429)
@@ -606,17 +713,20 @@ def submit_sensor_pending(request):
except (HTTPError, URLError, TimeoutError, OSError, ValueError, json.JSONDecodeError):
return _submission_error("classifier_unavailable", "Classification failed; retain the queued recording.", 502)
uploaded.seek(0)
pending = None
try:
with transaction.atomic():
pending = PendingEvent.objects.create(audio_file=uploaded, sensor=sensor, source_type=PendingEvent.SourceType.SENSOR, original_filename=Path(uploaded.name).name[:255], classifier_response=payload, captured_at=captured_at, firmware_version=firmware, device_metadata=metadata)
receipt = SensorSubmission.objects.create(sensor=sensor, event_id=event_id, audio_sha256=audio_hash, pending_event=pending)
except IntegrityError:
if pending and pending.audio_file:
pending.audio_file.storage.delete(pending.audio_file.name)
existing = SensorSubmission.objects.get(sensor=sensor, event_id=event_id)
if existing.audio_sha256 != audio_hash:
return _submission_error("event_id_conflict", "event_id already belongs to different audio.", 409)
return JsonResponse({"submission_id": str(existing.submission_id), "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True})
return JsonResponse({"submission_id": str(existing.submission_id), "event_id": event_id, "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True})
sensor.record_heartbeat(submission=True)
return JsonResponse({"submission_id": str(receipt.submission_id), "pending_event_id": pending.pk, "status": "pending", "classification": payload}, status=201)
return JsonResponse({"submission_id": str(receipt.submission_id), "event_id": event_id, "pending_event_id": pending.pk, "status": "pending", "classification": payload}, status=201)
@csrf_exempt
+13 -5
View File
@@ -24,13 +24,17 @@
const bounds = L.latLngBounds([]);
h3Cells.forEach((cell) => {
const hasManual = cell.manual_reports > 0;
const hasSensor = cell.sensor_reports > 0;
const color = hasManual && hasSensor ? "#a78bfa" : hasSensor ? "#22d3ee" : "#f59e0b";
const polygon = L.polygon(cell.boundary, {
color: "#f59e0b", weight: 2, fillColor: "#f59e0b", fillOpacity: 0.25,
color, weight: 2, fillColor: color, fillOpacity: 0.25,
}).addTo(map);
polygon.bindPopup(
"<span class=\"popup-title\">H3 " + cell.cell + "</span>" +
"<span class=\"popup-meta\">" + cell.reports + " " + (cell.reports === 1 ? (t.report || "report") : (t.reports || "reports")) + " · " + cell.occurrences +
" " + (cell.occurrences === 1 ? (t.occurrence || "occurrence") : (t.occurrences || "occurrences")) + " · " + (t.resolution || "resolution") + " " + h3Resolution + "</span>"
" " + (cell.occurrences === 1 ? (t.occurrence || "occurrence") : (t.occurrences || "occurrences")) + " · " + (t.resolution || "resolution") + " " + h3Resolution +
"<br>" + cell.manual_reports + " " + (t.manualReport || "Manual report") + " · " + cell.sensor_reports + " " + (t.sensorEvent || "Sensor event") + "</span>"
);
bounds.extend(L.latLngBounds(cell.boundary));
});
@@ -60,7 +64,11 @@
const reportIcon = L.divIcon({
className: "", html: "<div class=\"report-icon\">✦</div>", iconSize: [37, 37], iconAnchor: [19, 19],
});
const sensorIcon = L.divIcon({
className: "", html: "<div class=\"sensor-icon\">S</div>", iconSize: [37, 37], iconAnchor: [19, 19],
});
reports.forEach((report) => {
const isSensor = report.source_type === "sensor";
const visualStatus = report.visually_confirmed ? (t.visuallyConfirmed || "Visually confirmed") : (t.notVisuallyConfirmed || "Not visually confirmed");
let detail = report.occurrences + " " + (report.occurrences === 1 ? (t.occurrence || "occurrence") : (t.occurrences || "occurrences")) +
" · " + visualStatus + "<br>" + (t.reported || "Reported") + " " + report.reported_on;
@@ -70,8 +78,8 @@
detail += " (±" + Math.round(report.direction_accuracy_degrees) + "°)";
}
}
L.marker(report.center, { icon: reportIcon }).addTo(map).bindPopup(
"<span class=\"popup-title\">" + (t.manualReport || "Manual report") + " · H3 " + report.cell + "</span>" +
L.marker(report.center, { icon: isSensor ? sensorIcon : reportIcon }).addTo(map).bindPopup(
"<span class=\"popup-title\">" + (isSensor ? (t.sensorEvent || "Sensor event") : (t.manualReport || "Manual report")) + " · H3 " + report.cell + "</span>" +
"<span class=\"popup-meta\">" + detail + "</span>"
);
@@ -98,4 +106,4 @@
input.addEventListener("change", () => { range.value = "custom"; });
});
}
+16
View File
@@ -21,6 +21,10 @@
const reportTime = document.querySelector("#manual-report-time");
const reportHours = document.querySelector("#report-clock-hours");
const reportMinutes = document.querySelector("#report-clock-minutes");
const occurredAt = document.querySelector("#manual-occurred-at");
const useNow = document.querySelector("#manual-use-now");
const burstStatus = document.querySelector("#manual-burst-status");
const burstDuration = document.querySelector("#manual-burst-duration");
let orientationListener;
let compassUnavailableTimeout;
let compassRotation = null;
@@ -47,6 +51,11 @@
updateReportTime();
if (reportTime) window.setInterval(updateReportTime, 60000);
const idleSubmitLabel = submitLabel?.textContent || "I heard fireworks";
useNow?.addEventListener("click", () => {
const now = new Date();
const local = new Date(now.getTime() - now.getTimezoneOffset() * 60000);
occurredAt.value = local.toISOString().slice(0, 16);
});
const setSubmissionState = (next, message = "") => {
manualForm.dataset.state = next;
@@ -70,16 +79,23 @@
return successful;
};
const showBurstState = () => {
const burst = Number(occurrences.value) >= 3;
if (burstStatus) burstStatus.textContent = burst ? (t.burstEvent || "Burst Event") : (t.ordinaryReport || "Ordinary report");
if (burstDuration) burstDuration.hidden = !burst;
};
const setCount = (value) => {
const count = Number.parseInt(value, 10);
occurrences.value = String(Math.min(1000, Math.max(1, Number.isFinite(count) ? count : 1)));
decrease.disabled = occurrences.value === "1";
increase.disabled = occurrences.value === "1000";
showBurstState();
};
setCount(occurrences.value);
decrease.addEventListener("click", () => setCount(Number(occurrences.value) - 1));
increase.addEventListener("click", () => setCount(Number(occurrences.value) + 1));
occurrences.addEventListener("change", () => setCount(occurrences.value));
occurrences.addEventListener("input", showBurstState);
const stopCompassReading = () => {
if (orientationListener) window.removeEventListener("deviceorientation", orientationListener);
@@ -6,6 +6,67 @@
--manual-report-section-gap: 1rem;
}
.manual-report__occurrence, .manual-report__duration {
display: grid;
gap: .55rem;
max-width: 36rem;
margin-bottom: var(--manual-report-section-gap);
padding: .85rem 1rem;
border: 1px solid #584891;
border-radius: 1rem;
background: #151932;
color: #e9def8;
input[type="datetime-local"], input[type="number"] {
width: 100%;
min-height: 2.75rem;
padding: .45rem .65rem;
border: 1px solid #725da4;
border-radius: .55rem;
color: #f5f0ff;
background: #211d3d;
font: inherit;
color-scheme: dark;
}
small { color: #cbbce5; }
}
.manual-report__duration[hidden] { display: none; }
.manual-report__time-row {
display: flex;
gap: .5rem;
align-items: center;
input { min-width: 0; flex: 1; }
button { flex: none; }
}
@media (max-width: 30rem) {
.manual-report__time-row { flex-direction: column; align-items: stretch; }
.manual-report__time-row button { align-self: flex-start; }
}
.manual-report__occurrence button {
justify-self: start;
padding: .35rem .75rem;
border: 1px solid #725da4;
border-radius: .55rem;
color: #f5f0ff;
background: #302553;
cursor: pointer;
}
.manual-report__check {
display: flex;
align-items: center;
gap: .5rem;
color: #e9def8;
}
.manual-report__burst-status { margin: .5rem 0 0; color: #ffbf72; font-weight: 750; }
.manual-submission__edit {
display: grid;
gap: .4rem;
max-width: 18rem;
margin-top: 1rem;
input[type="number"] { min-height: 2.5rem; padding: .4rem; border-radius: .5rem; }
button { min-height: 2.5rem; cursor: pointer; }
}
.manual-report__primary {
display: grid;
gap: var(--manual-report-section-gap);
+37
View File
@@ -258,6 +258,14 @@ body {
background: #8b5cf633;
}
.legend-sensor {
width: .85rem;
height: .85rem;
border: 2px solid #a5f3fc;
border-radius: .2rem;
background: #0891b2;
}
.legend-line {
width: 1.1rem;
border-top: 2px dashed #644b9c;
@@ -277,6 +285,20 @@ body {
box-shadow: 0 .3rem 1rem #a84f2670;
}
.sensor-icon {
display: grid;
width: 2.3rem;
height: 2.3rem;
place-items: center;
border: 2px solid #cffafe;
border-radius: .55rem;
color: #ecfeff;
font-size: 1rem;
font-weight: 900;
background: #087e97;
box-shadow: 0 .3rem 1rem #06465a88;
}
.source-icon {
display: grid;
width: 2.45rem;
@@ -388,6 +410,18 @@ body {
font-size: .78rem;
}
@media (max-width:80rem) {
.filters {
grid-template-columns: repeat(5,minmax(0,1fr));
.filter-submit {
grid-column: 1/3;
}
.map-tag {
grid-column: 5;
}
}
}
@media (max-width:52rem) {
.shell {
width: min(100% - 1.25rem,80rem);
@@ -405,6 +439,9 @@ body {
.filter:first-child {
grid-column: 1/-1;
}
.filter-submit, .map-tag {
grid-column: auto;
}
}
.map {
height: 32rem;
Binary file not shown.
+80
View File
@@ -1403,3 +1403,83 @@ msgstr "Toegang tot de microfoon is geweigerd. Je kunt nog steeds handmatig meld
msgid "Microphone capture failed."
msgstr "Opnemen met de microfoon is mislukt."
msgid "When did it happen?"
msgstr "Wanneer gebeurde het?"
msgid "Use now"
msgstr "Gebruik nu"
msgid "Time is approximate"
msgstr "Tijdstip is ongeveer"
msgid "Leave the time empty to use the submission time."
msgstr "Laat leeg om het verzendtijdstip te gebruiken."
msgid "Ordinary report"
msgstr "Gewone melding"
msgid "Burst Event"
msgstr "Knalreeks"
msgid "Estimated observation window (minutes, for 3+ bangs)"
msgstr "Geschatte tijdsduur (minuten, vanaf 3 knallen)"
msgid "Use this estimated window for burst intensity"
msgstr "Gebruik deze geschatte tijdsduur voor de intensiteit"
msgid "Optional. Without an accepted window, BoomCast reports the count without an intensity rating."
msgstr "Optioneel. Zonder bevestigde tijdsduur toont BoomCast geen intensiteit."
msgid "Correct bang count"
msgstr "Aantal knallen aanpassen"
msgid "Estimated minutes for a burst"
msgstr "Geschatte minuten voor de knalreeks"
msgid "Use this estimated window"
msgstr "Gebruik deze geschatte tijdsduur"
msgid "Update report"
msgstr "Melding bijwerken"
msgid "Duration"
msgstr "Tijdsduur"
msgid "Intensity"
msgstr "Intensiteit"
msgid "Not rated"
msgstr "Niet beoordeeld"
msgid "Unknown"
msgstr "Onbekend"
msgid "Approximately"
msgstr "Ongeveer"
msgid "Submitted"
msgstr "Verzonden"
msgid "Occurred"
msgstr "Gebeurd"
msgid "minutes (estimated)"
msgstr "minuten (geschat)"
msgid "minutes (measured)"
msgstr "minuten (gemeten)"
msgid "bangs per 15 minutes"
msgstr "knallen per 15 minuten"
msgid "Light"
msgstr "Licht"
msgid "Moderate"
msgstr "Matig"
msgid "Intense"
msgstr "Intens"
msgid "Report updated!"
msgstr "Melding bijgewerkt!"
@@ -0,0 +1 @@
RIFF0000WAVEdata
Binary file not shown.
@@ -13,6 +13,7 @@
<section class="sensor-detail__overview" aria-label="{% trans 'Sensor overview' %}">
{% with status=heartbeat %}<span class="sensor-status sensor-status--{{ status.0 }}">● {{ status.1 }}</span>{% endwith %}
<dl class="sensor-detail__facts">
<div><dt>{% trans "Sensor ID" %}</dt><dd><code>{{ sensor.pk }}</code></dd></div>
<div><dt>{% trans "Last heartbeat" %}</dt><dd>{{ sensor.last_heartbeat|date:"j M Y, H:i"|default:"—" }}</dd></div>
<div><dt>{% trans "Last submission" %}</dt><dd>{{ sensor.last_submission|date:"j M Y, H:i"|default:"—" }}</dd></div>
<div><dt>{% trans "Token prefix" %}</dt><dd><code>{{ sensor.token_prefix|default:"—" }}</code></dd></div>
@@ -7,6 +7,7 @@
<div class="sensor-card__heading"><h3>{{ sensor.name }}</h3>{% with status=sensor.heartbeat_status %}<span class="sensor-status sensor-status--{{ status.0 }}">● {{ status.1 }}</span>{% endwith %}</div>
<span class="sensor-access {% if not sensor.is_active %}sensor-access--off{% endif %}">{% if sensor.is_active %}{% trans "Enabled" %}{% else %}{% trans "Disabled" %}{% endif %}</span>
<dl class="sensor-card__facts">
<div><dt>{% trans "Sensor ID" %}</dt><dd><code>{{ sensor.pk }}</code></dd></div>
<div><dt>{% trans "Last heartbeat" %}</dt><dd>{{ sensor.last_heartbeat|date:"j M Y, H:i"|default:"—" }}</dd></div>
<div><dt>{% trans "Created" %}</dt><dd>{{ sensor.created_at|date:"j M Y" }}</dd></div>
<div><dt>{% trans "Token prefix" %}</dt><dd><code>{{ sensor.token_prefix|default:"—" }}</code></dd></div>
+2
View File
@@ -32,6 +32,7 @@ class SensorSettingsTests(TestCase):
listing = self.client.get(reverse("user_settings"))
self.assertContains(listing, "Balcony")
self.assertContains(listing, "Portable")
self.assertContains(listing, f"<code>{sensor.pk}</code>", html=True)
self.assertNotContains(listing, "System")
self.assertNotContains(listing, "Bob&#x27;s device")
self.client.force_login(self.bob)
@@ -45,6 +46,7 @@ class SensorSettingsTests(TestCase):
detail = self.client.get(reverse("manage_sensor", args=[sensor.pk]), **headers)
self.assertContains(detail, "Balcony")
self.assertContains(detail, f"<code>{sensor.pk}</code>", html=True)
self.assertContains(detail, reverse("sensor_list"))
self.assertNotContains(detail, "<!doctype html>")
@@ -0,0 +1 @@
/* empty css *//* empty css */import"./fireworks-home.js-CZsCTUTv.js";import"./map.js-ZTK3kmoy.js";import"../../../manual-report-44fwUW4y.js";import"../../../theme-DXAi27ON.js";
@@ -0,0 +1 @@
/* empty css */import"../../../manual-report-44fwUW4y.js";import"../../../theme-DXAi27ON.js";
@@ -0,0 +1 @@
/* empty css *//* empty css */import"../../../theme-DXAi27ON.js";const e=window.BOOMCAST_I18N||{},u=document.getElementById("event-map"),f=u.dataset.h3Resolution,n=L.map(u,{zoomControl:!1,scrollWheelZoom:!1}).setView([52.1326,5.2913],7);L.control.zoom({position:"bottomleft"}).addTo(n);const m=L.control({position:"topright"});m.onAdd=()=>{const o=L.DomUtil.create("div","map-compass");return o.setAttribute("role","img"),o.setAttribute("aria-label",e.mapCompass||"Map compass: north is up"),o.innerHTML='<span class="compass-n">N</span><span class="compass-e">E</span><span class="compass-s">S</span><span class="compass-w">W</span><span class="compass-needle">↑</span>',L.DomEvent.disableClickPropagation(o),o};m.addTo(n);L.tileLayer("https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png",{maxZoom:18,attribution:"&copy; OpenStreetMap contributors"}).addTo(n);const M=JSON.parse(document.getElementById("h3-cells-data").textContent),y=JSON.parse(document.getElementById("map-events-data").textContent),d=L.latLngBounds([]);M.forEach(o=>{const s=o.manual_reports>0,c=o.sensor_reports>0,t=s&&c?"#a78bfa":c?"#22d3ee":"#f59e0b";L.polygon(o.boundary,{color:t,weight:2,fillColor:t,fillOpacity:.25}).addTo(n).bindPopup('<span class="popup-title">H3 '+o.cell+'</span><span class="popup-meta">'+o.reports+" "+(o.reports===1?e.report||"report":e.reports||"reports")+" · "+o.occurrences+" "+(o.occurrences===1?e.occurrence||"occurrence":e.occurrences||"occurrences")+" · "+(e.resolution||"resolution")+" "+f+"<br>"+o.manual_reports+" "+(e.manualReport||"Manual report")+" · "+o.sensor_reports+" "+(e.sensorEvent||"Sensor event")+"</span>"),d.extend(L.latLngBounds(o.boundary))});function v(o){return["N","NE","E","SE","S","SW","W","NW"][Math.floor((o+22.5)%360/45)]}function b(o,s,c){const a=s*Math.PI/180,r=o[0]*Math.PI/180,h=o[1]*Math.PI/180,i=c/6378137,l=Math.asin(Math.sin(r)*Math.cos(i)+Math.cos(r)*Math.sin(i)*Math.cos(a)),g=h+Math.atan2(Math.sin(a)*Math.sin(i)*Math.cos(r),Math.cos(i)-Math.sin(r)*Math.sin(l));return[l*180/Math.PI,g*180/Math.PI]}const S=L.divIcon({className:"",html:'<div class="report-icon">✦</div>',iconSize:[37,37],iconAnchor:[19,19]}),_=L.divIcon({className:"",html:'<div class="sensor-icon">S</div>',iconSize:[37,37],iconAnchor:[19,19]});y.forEach(o=>{const s=o.source_type==="sensor",c=o.visually_confirmed?e.visuallyConfirmed||"Visually confirmed":e.notVisuallyConfirmed||"Not visually confirmed";let t=o.occurrences+" "+(o.occurrences===1?e.occurrence||"occurrence":e.occurrences||"occurrences")+" · "+c+"<br>"+(e.reported||"Reported")+" "+o.reported_on;if(o.direction_degrees!==null&&(t+="<br>"+(e.compassDirection||"Compass direction")+" "+Math.round(o.direction_degrees)+"° ("+v(o.direction_degrees)+")",o.direction_accuracy_degrees!==null&&(t+=" (±"+Math.round(o.direction_accuracy_degrees)+"°)")),L.marker(o.center,{icon:s?_:S}).addTo(n).bindPopup('<span class="popup-title">'+(s?e.sensorEvent||"Sensor event":e.manualReport||"Manual report")+" · H3 "+o.cell+'</span><span class="popup-meta">'+t+"</span>"),o.direction_degrees!==null){const a=b(o.center,o.direction_degrees,900);L.polyline([o.center,a],{color:"#fff7e6",weight:9,opacity:.8}).addTo(n),L.polyline([o.center,a],{color:"#6d45a0",weight:5,opacity:1}).addTo(n);const r=L.divIcon({className:"",html:'<div class="direction-marker"><span style="transform:rotate('+o.direction_degrees+'deg)">↑</span></div>',iconSize:[56,56],iconAnchor:[28,28]});L.marker(a,{icon:r,interactive:!1}).addTo(n)}});d.isValid()&&n.fitBounds(d.pad(.18));const p=document.getElementById("range");p&&document.querySelectorAll("#from-date, #to-date").forEach(o=>{o.addEventListener("change",()=>{p.value="custom"})});
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -81,6 +81,9 @@ window.BOOMCAST_I18N = {
irrelevantGateMessage: "{% trans 'BoomCast could not identify a sound this service currently looks for. You can still submit it for manual review.' as value %}{{ value|escapejs }}",
gateChooseMessage: "{% trans 'Recording checked. Choose another recording or submit for manual review.' as value %}{{ value|escapejs }}",
secureVideoFailed: "{% trans 'Could not prepare this video for upload. Please choose an audio recording.' as value %}{{ value|escapejs }}",
manualReport: "{% trans 'Manual report' as value %}{{ value|escapejs }}"
manualReport: "{% trans 'Manual report' as value %}{{ value|escapejs }}",
burstEvent: "{% trans 'Burst Event' as value %}{{ value|escapejs }}",
ordinaryReport: "{% trans 'Ordinary report' as value %}{{ value|escapejs }}",
sensorEvent: "{% trans 'Sensor event' as value %}{{ value|escapejs }}"
};
</script>