mirror of
https://github.com/smittix/intercept.git
synced 2026-06-17 09:59:47 -07:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ec19d4b55e |
@@ -55,9 +55,6 @@ intercept_agent_*.cfg
|
|||||||
/tmp/
|
/tmp/
|
||||||
*.tmp
|
*.tmp
|
||||||
|
|
||||||
# Weather satellite runtime data (decoded images, samples, SatDump output)
|
|
||||||
data/weather_sat/
|
|
||||||
|
|
||||||
# Env files
|
# Env files
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
|
|||||||
@@ -2,39 +2,6 @@
|
|||||||
|
|
||||||
All notable changes to iNTERCEPT will be documented in this file.
|
All notable changes to iNTERCEPT will be documented in this file.
|
||||||
|
|
||||||
## [2.15.0] - 2026-02-09
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- **Real-time WebSocket Waterfall** - I/Q capture with server-side FFT
|
|
||||||
- Click-to-tune, zoom controls, and auto-scaling quantization
|
|
||||||
- Shared waterfall UI across SDR modes with function bar controls
|
|
||||||
- WebSocket frame serialization and connection reuse
|
|
||||||
- **Cross-Module Frequency Routing** - Tune from Listening Post directly to decoders
|
|
||||||
- **Pure Python SSTV Decoder** - Replaces broken slowrx C dependency
|
|
||||||
- Real-time decode progress with partial image streaming
|
|
||||||
- VIS detector state in signal monitor diagnostics
|
|
||||||
- Image gallery with delete and download functionality
|
|
||||||
- **Real-time Signal Scope** - Live signal visualization for pager, sensor, and SSTV modes
|
|
||||||
- **SSTV Image Gallery** - Delete and download decoded images
|
|
||||||
- **USB Device Probe** - Detect broken SDR devices before rtl_fm crashes
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- DMR dsd-fme protocol flags, device label, and tuning controls
|
|
||||||
- DMR frontend/backend state desync causing 409 on start
|
|
||||||
- Digital voice decoder producing no output due to wrong dsd-fme flags
|
|
||||||
- SDR device lock-up from unreleased device registry on process crash
|
|
||||||
- APRS crash on large station count and station list overflow
|
|
||||||
- Settings modal overflowing viewport on smaller screens
|
|
||||||
- Waterfall crash on zoom by reusing WebSocket and adding USB release retry
|
|
||||||
- PD120 SSTV decode hang and false leader tone detection
|
|
||||||
- WebSocket waterfall blocked by login redirect
|
|
||||||
- TSCM sweep KeyError on RiskLevel.NEEDS_REVIEW
|
|
||||||
|
|
||||||
### Removed
|
|
||||||
- GSM Spy functionality removed for legal compliance
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## [2.14.0] - 2026-02-06
|
## [2.14.0] - 2026-02-06
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -4,26 +4,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
|
|
||||||
## Project Overview
|
## Project Overview
|
||||||
|
|
||||||
INTERCEPT is a web-based Signal Intelligence (SIGINT) platform providing a unified Flask interface for software-defined radio (SDR) tools. It supports pager decoding, 433MHz sensors, ADS-B aircraft tracking, ACARS messaging, WiFi/Bluetooth scanning, satellite tracking, ISS SSTV decoding, AIS vessel tracking, weather satellite imagery (NOAA APT & Meteor LRPT), and Meshtastic mesh networking.
|
INTERCEPT is a web-based Signal Intelligence (SIGINT) platform providing a unified Flask interface for software-defined radio (SDR) tools. It supports pager decoding, 433MHz sensors, ADS-B aircraft tracking, ACARS messaging, WiFi/Bluetooth scanning, and satellite tracking.
|
||||||
|
|
||||||
## Common Commands
|
## Common Commands
|
||||||
|
|
||||||
### Docker (Primary)
|
### Setup and Running
|
||||||
```bash
|
|
||||||
# Build and run (basic profile)
|
|
||||||
docker compose --profile basic up -d
|
|
||||||
|
|
||||||
# Build and run with ADS-B history (Postgres)
|
|
||||||
docker compose --profile history up -d
|
|
||||||
|
|
||||||
# Rebuild after code changes
|
|
||||||
docker compose --profile basic up -d --build
|
|
||||||
|
|
||||||
# Multi-arch build (amd64 + arm64 for RPi)
|
|
||||||
./build-multiarch.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
### Local Setup (Alternative)
|
|
||||||
```bash
|
```bash
|
||||||
# Initial setup (installs dependencies and configures SDR tools)
|
# Initial setup (installs dependencies and configures SDR tools)
|
||||||
./setup.sh
|
./setup.sh
|
||||||
@@ -81,12 +66,8 @@ Each signal type has its own Flask blueprint:
|
|||||||
- `wifi.py`, `wifi_v2.py` - WiFi scanning (legacy and unified APIs)
|
- `wifi.py`, `wifi_v2.py` - WiFi scanning (legacy and unified APIs)
|
||||||
- `bluetooth.py`, `bluetooth_v2.py` - Bluetooth scanning (legacy and unified APIs)
|
- `bluetooth.py`, `bluetooth_v2.py` - Bluetooth scanning (legacy and unified APIs)
|
||||||
- `satellite.py` - Pass prediction using TLE data
|
- `satellite.py` - Pass prediction using TLE data
|
||||||
- `sstv.py` - ISS SSTV image decoding via slowrx
|
|
||||||
- `weather_sat.py` - NOAA APT & Meteor LRPT via SatDump
|
|
||||||
- `ais.py` - AIS vessel tracking and VHF DSC distress monitoring
|
|
||||||
- `aprs.py` - Amateur packet radio via direwolf
|
- `aprs.py` - Amateur packet radio via direwolf
|
||||||
- `rtlamr.py` - Utility meter reading
|
- `rtlamr.py` - Utility meter reading
|
||||||
- `meshtastic_routes.py` - Meshtastic LoRa mesh networking
|
|
||||||
|
|
||||||
### Core Utilities (utils/)
|
### Core Utilities (utils/)
|
||||||
|
|
||||||
@@ -110,15 +91,6 @@ Each signal type has its own Flask blueprint:
|
|||||||
- Platform-agnostic scanner with parsers for airodump-ng, nmcli, iw, iwlist, airport (macOS)
|
- Platform-agnostic scanner with parsers for airodump-ng, nmcli, iw, iwlist, airport (macOS)
|
||||||
- `channel_analyzer.py` - Frequency band analysis
|
- `channel_analyzer.py` - Frequency band analysis
|
||||||
|
|
||||||
**Weather Satellite** (`utils/weather_sat.py`):
|
|
||||||
- Singleton `WeatherSatDecoder` using SatDump CLI for NOAA APT and Meteor LRPT
|
|
||||||
- Subprocess management with stdout parsing, image watcher via rglob
|
|
||||||
- Pass prediction using skyfield TLE data
|
|
||||||
|
|
||||||
**SSTV Decoder** (`utils/sstv.py`):
|
|
||||||
- ISS SSTV reception via slowrx with Doppler tracking
|
|
||||||
- Singleton pattern, image gallery with timestamped filenames
|
|
||||||
|
|
||||||
### Key Patterns
|
### Key Patterns
|
||||||
|
|
||||||
**Server-Sent Events (SSE)**: All real-time features stream via SSE endpoints (`/stream_pager`, `/stream_sensor`, etc.). Pattern uses `queue.Queue` with timeout and keepalive messages.
|
**Server-Sent Events (SSE)**: All real-time features stream via SSE endpoints (`/stream_pager`, `/stream_sensor`, etc.). Pattern uses `queue.Queue` with timeout and keepalive messages.
|
||||||
@@ -140,25 +112,9 @@ Each signal type has its own Flask blueprint:
|
|||||||
| acarsdec | ACARS messages | Output parsing |
|
| acarsdec | ACARS messages | Output parsing |
|
||||||
| airmon-ng/airodump-ng | WiFi scanning | Monitor mode, CSV parsing |
|
| airmon-ng/airodump-ng | WiFi scanning | Monitor mode, CSV parsing |
|
||||||
| bluetoothctl/hcitool | Bluetooth | Fallback when DBus unavailable |
|
| bluetoothctl/hcitool | Bluetooth | Fallback when DBus unavailable |
|
||||||
| slowrx | SSTV decoding | Subprocess with audio pipe |
|
|
||||||
| SatDump | Weather satellites | CLI live mode, NOAA APT + Meteor LRPT |
|
|
||||||
| AIS-catcher | AIS vessel tracking | JSON output parsing |
|
|
||||||
| direwolf | APRS | TNC modem for packet radio |
|
|
||||||
|
|
||||||
### Frontend Structure
|
|
||||||
- **Templates**: `templates/index.html` (main SPA), `templates/partials/modes/*.html` (sidebar panels), `templates/partials/nav.html` (global nav)
|
|
||||||
- **JS Modules**: `static/js/modes/*.js` - IIFE pattern per mode (e.g., `WeatherSat`, `SSTV`, `Meshtastic`)
|
|
||||||
- **CSS**: `static/css/modes/*.css` - scoped styles per mode, CSS variables for theming (`--bg-card`, `--accent-cyan`, `--font-mono`)
|
|
||||||
- **Mode Integration**: Each mode needs entries in `index.html` at ~12 points: CSS include, welcome card, partial include, visuals container, JS include, `validModes` set, `modeGroups` map, classList toggle, `modeNames`, visuals display toggle, titles, and init call in `switchMode()`
|
|
||||||
|
|
||||||
### Docker
|
|
||||||
- `Dockerfile` - Single-stage build with all SDR tools compiled from source (dump1090, AIS-catcher, slowrx, SatDump, etc.)
|
|
||||||
- `docker-compose.yml` - Two profiles: `basic` (standalone) and `history` (with Postgres for ADS-B)
|
|
||||||
- `build-multiarch.sh` - Multi-arch build script for amd64 + arm64 (RPi5)
|
|
||||||
- Data persisted via `./data:/app/data` volume mount
|
|
||||||
|
|
||||||
### Configuration
|
### Configuration
|
||||||
- `config.py` - Environment variable support with `INTERCEPT_` prefix (e.g., `INTERCEPT_PORT`, `INTERCEPT_WEATHER_SAT_GAIN`)
|
- `config.py` - Environment variable support with `INTERCEPT_` prefix
|
||||||
- Database: SQLite in `instance/` directory for settings, baselines, history
|
- Database: SQLite in `instance/` directory for settings, baselines, history
|
||||||
|
|
||||||
## Testing Notes
|
## Testing Notes
|
||||||
|
|||||||
+1
-74
@@ -9,9 +9,6 @@ LABEL description="Signal Intelligence Platform for SDR monitoring"
|
|||||||
# Set working directory
|
# Set working directory
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Pre-accept tshark non-root capture prompt for non-interactive install
|
|
||||||
RUN echo 'wireshark-common wireshark-common/install-setuid boolean true' | debconf-set-selections
|
|
||||||
|
|
||||||
# Install system dependencies for SDR tools
|
# Install system dependencies for SDR tools
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
# RTL-SDR tools
|
# RTL-SDR tools
|
||||||
@@ -24,15 +21,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
multimon-ng \
|
multimon-ng \
|
||||||
# Audio tools for Listening Post
|
# Audio tools for Listening Post
|
||||||
ffmpeg \
|
ffmpeg \
|
||||||
# SSTV decoder runtime libs
|
|
||||||
libsndfile1 \
|
|
||||||
# SatDump runtime libs (weather satellite decoding)
|
|
||||||
libpng16-16 \
|
|
||||||
libtiff6 \
|
|
||||||
libjemalloc2 \
|
|
||||||
libvolk-bin \
|
|
||||||
libnng1 \
|
|
||||||
libzstd1 \
|
|
||||||
# WiFi tools (aircrack-ng suite)
|
# WiFi tools (aircrack-ng suite)
|
||||||
aircrack-ng \
|
aircrack-ng \
|
||||||
iw \
|
iw \
|
||||||
@@ -53,8 +41,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
soapysdr-module-rtlsdr \
|
soapysdr-module-rtlsdr \
|
||||||
soapysdr-module-hackrf \
|
soapysdr-module-hackrf \
|
||||||
soapysdr-module-lms7 \
|
soapysdr-module-lms7 \
|
||||||
soapysdr-module-airspy \
|
|
||||||
airspy \
|
|
||||||
limesuite \
|
limesuite \
|
||||||
hackrf \
|
hackrf \
|
||||||
# Utilities
|
# Utilities
|
||||||
@@ -70,22 +56,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
cmake \
|
cmake \
|
||||||
libncurses-dev \
|
libncurses-dev \
|
||||||
libsndfile1-dev \
|
libsndfile1-dev \
|
||||||
# GTK is required for slowrx (SSTV decoder GUI dependency).
|
|
||||||
# Note: slowrx is kept for backwards compatibility, but the pure Python
|
|
||||||
# SSTV decoder in utils/sstv/ is now the primary implementation.
|
|
||||||
# GTK can be removed if slowrx is deprecated in future releases.
|
|
||||||
libgtk-3-dev \
|
|
||||||
libasound2-dev \
|
|
||||||
libsoapysdr-dev \
|
libsoapysdr-dev \
|
||||||
libhackrf-dev \
|
libhackrf-dev \
|
||||||
liblimesuite-dev \
|
liblimesuite-dev \
|
||||||
libfftw3-dev \
|
|
||||||
libpng-dev \
|
|
||||||
libtiff-dev \
|
|
||||||
libjemalloc-dev \
|
|
||||||
libvolk-dev \
|
|
||||||
libnng-dev \
|
|
||||||
libzstd-dev \
|
|
||||||
libsqlite3-dev \
|
libsqlite3-dev \
|
||||||
libcurl4-openssl-dev \
|
libcurl4-openssl-dev \
|
||||||
zlib1g-dev \
|
zlib1g-dev \
|
||||||
@@ -140,43 +113,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
&& make \
|
&& make \
|
||||||
&& cp acarsdec /usr/bin/acarsdec \
|
&& cp acarsdec /usr/bin/acarsdec \
|
||||||
&& rm -rf /tmp/acarsdec \
|
&& rm -rf /tmp/acarsdec \
|
||||||
# Build slowrx (SSTV decoder) — pinned to known-good commit
|
|
||||||
&& cd /tmp \
|
|
||||||
&& git clone https://github.com/windytan/slowrx.git \
|
|
||||||
&& cd slowrx \
|
|
||||||
&& git checkout ca6d7012 \
|
|
||||||
&& make \
|
|
||||||
&& install -m 0755 slowrx /usr/local/bin/slowrx \
|
|
||||||
&& rm -rf /tmp/slowrx \
|
|
||||||
# Build SatDump (weather satellite decoder - NOAA APT & Meteor LRPT) — pinned to v1.2.2
|
|
||||||
&& cd /tmp \
|
|
||||||
&& git clone --depth 1 --branch 1.2.2 https://github.com/SatDump/SatDump.git \
|
|
||||||
&& cd SatDump \
|
|
||||||
&& mkdir build && cd build \
|
|
||||||
&& cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_GUI=OFF -DCMAKE_INSTALL_LIBDIR=lib .. \
|
|
||||||
&& make -j$(nproc) \
|
|
||||||
&& make install \
|
|
||||||
&& ldconfig \
|
|
||||||
# Ensure SatDump plugins are in the expected path (handles multiarch differences)
|
|
||||||
&& mkdir -p /usr/local/lib/satdump/plugins \
|
|
||||||
&& if [ -z "$(ls /usr/local/lib/satdump/plugins/*.so 2>/dev/null)" ]; then \
|
|
||||||
for dir in /usr/local/lib/*/satdump/plugins /usr/lib/*/satdump/plugins /usr/lib/satdump/plugins; do \
|
|
||||||
if [ -d "$dir" ] && [ -n "$(ls "$dir"/*.so 2>/dev/null)" ]; then \
|
|
||||||
ln -sf "$dir"/*.so /usr/local/lib/satdump/plugins/; \
|
|
||||||
break; \
|
|
||||||
fi; \
|
|
||||||
done; \
|
|
||||||
fi \
|
|
||||||
&& cd /tmp \
|
|
||||||
&& rm -rf /tmp/SatDump \
|
|
||||||
# Build rtlamr (utility meter decoder - requires Go)
|
|
||||||
&& cd /tmp \
|
|
||||||
&& curl -fsSL "https://go.dev/dl/go1.22.5.linux-$(dpkg --print-architecture).tar.gz" | tar -C /usr/local -xz \
|
|
||||||
&& export PATH="$PATH:/usr/local/go/bin" \
|
|
||||||
&& export GOPATH=/tmp/gopath \
|
|
||||||
&& go install github.com/bemasher/rtlamr@latest \
|
|
||||||
&& cp /tmp/gopath/bin/rtlamr /usr/bin/rtlamr \
|
|
||||||
&& rm -rf /usr/local/go /tmp/gopath \
|
|
||||||
# Build mbelib (required by DSD)
|
# Build mbelib (required by DSD)
|
||||||
&& cd /tmp \
|
&& cd /tmp \
|
||||||
&& git clone https://github.com/lwvmobile/mbelib.git \
|
&& git clone https://github.com/lwvmobile/mbelib.git \
|
||||||
@@ -199,7 +135,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
&& ldconfig \
|
&& ldconfig \
|
||||||
&& rm -rf /tmp/dsd-fme \
|
&& rm -rf /tmp/dsd-fme \
|
||||||
# Cleanup build tools to reduce image size
|
# Cleanup build tools to reduce image size
|
||||||
# libgtk-3-dev is explicitly removed; runtime GTK libs remain for slowrx
|
|
||||||
&& apt-get remove -y \
|
&& apt-get remove -y \
|
||||||
build-essential \
|
build-essential \
|
||||||
git \
|
git \
|
||||||
@@ -207,14 +142,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
cmake \
|
cmake \
|
||||||
libncurses-dev \
|
libncurses-dev \
|
||||||
libsndfile1-dev \
|
libsndfile1-dev \
|
||||||
libgtk-3-dev \
|
|
||||||
libasound2-dev \
|
|
||||||
libpng-dev \
|
|
||||||
libtiff-dev \
|
|
||||||
libjemalloc-dev \
|
|
||||||
libvolk-dev \
|
|
||||||
libnng-dev \
|
|
||||||
libzstd-dev \
|
|
||||||
libsoapysdr-dev \
|
libsoapysdr-dev \
|
||||||
libhackrf-dev \
|
libhackrf-dev \
|
||||||
liblimesuite-dev \
|
liblimesuite-dev \
|
||||||
@@ -237,7 +164,7 @@ RUN pip install --no-cache-dir -r requirements.txt
|
|||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Create data directory for persistence
|
# Create data directory for persistence
|
||||||
RUN mkdir -p /app/data /app/data/weather_sat
|
RUN mkdir -p /app/data
|
||||||
|
|
||||||
# Expose web interface port
|
# Expose web interface port
|
||||||
EXPOSE 5050
|
EXPOSE 5050
|
||||||
|
|||||||
@@ -33,9 +33,8 @@ Support the developer of this open-source project
|
|||||||
- **ACARS Messaging** - Aircraft datalink messages via acarsdec
|
- **ACARS Messaging** - Aircraft datalink messages via acarsdec
|
||||||
- **DMR Digital Voice** - DMR/P25/NXDN/D-STAR decoding via dsd-fme with visual synthesizer
|
- **DMR Digital Voice** - DMR/P25/NXDN/D-STAR decoding via dsd-fme with visual synthesizer
|
||||||
- **Listening Post** - Frequency scanner with audio monitoring
|
- **Listening Post** - Frequency scanner with audio monitoring
|
||||||
- **Weather Satellites** - NOAA APT and Meteor LRPT image decoding via SatDump
|
|
||||||
- **WebSDR** - Remote HF/shortwave listening via WebSDR servers
|
- **WebSDR** - Remote HF/shortwave listening via WebSDR servers
|
||||||
- **ISS SSTV** - Slow-scan TV image reception from the International Space Station
|
- **ISS SSTV** - Receive slow-scan TV from the International Space Station
|
||||||
- **HF SSTV** - Terrestrial SSTV on shortwave frequencies
|
- **HF SSTV** - Terrestrial SSTV on shortwave frequencies
|
||||||
- **Satellite Tracking** - Pass prediction using TLE data
|
- **Satellite Tracking** - Pass prediction using TLE data
|
||||||
- **ADS-B History** - Persistent aircraft history with reporting dashboard (Postgres optional)
|
- **ADS-B History** - Persistent aircraft history with reporting dashboard (Postgres optional)
|
||||||
@@ -61,54 +60,15 @@ cd intercept
|
|||||||
sudo -E venv/bin/python intercept.py
|
sudo -E venv/bin/python intercept.py
|
||||||
```
|
```
|
||||||
|
|
||||||
### Docker
|
### Docker (Alternative)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/smittix/intercept.git
|
git clone https://github.com/smittix/intercept.git
|
||||||
cd intercept
|
cd intercept
|
||||||
docker compose --profile basic up -d --build
|
docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
> **Note:** Docker requires privileged mode for USB SDR access. SDR devices are passed through via `/dev/bus/usb`.
|
> **Note:** Docker requires privileged mode for USB SDR access. See `docker-compose.yml` for configuration options.
|
||||||
|
|
||||||
#### Multi-Architecture Builds (amd64 + arm64)
|
|
||||||
|
|
||||||
Cross-compile on an x64 machine and push to a registry. This is much faster than building natively on an RPi.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# One-time setup on your x64 build machine
|
|
||||||
docker run --privileged --rm tonistiigi/binfmt --install all
|
|
||||||
docker buildx create --name intercept-builder --use --bootstrap
|
|
||||||
|
|
||||||
# Build and push for both architectures
|
|
||||||
REGISTRY=ghcr.io/youruser ./build-multiarch.sh --push
|
|
||||||
|
|
||||||
# On the RPi5, just pull and run
|
|
||||||
INTERCEPT_IMAGE=ghcr.io/youruser/intercept:latest docker compose --profile basic up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
Build script options:
|
|
||||||
|
|
||||||
| Flag | Description |
|
|
||||||
|------|-------------|
|
|
||||||
| `--push` | Push to container registry |
|
|
||||||
| `--load` | Load into local Docker (single platform only) |
|
|
||||||
| `--arm64-only` | Build arm64 only (for RPi deployment) |
|
|
||||||
| `--amd64-only` | Build amd64 only |
|
|
||||||
|
|
||||||
Environment variables: `REGISTRY`, `IMAGE_NAME`, `IMAGE_TAG`
|
|
||||||
|
|
||||||
#### Using a Pre-built Image
|
|
||||||
|
|
||||||
If you've pushed to a registry, you can skip building entirely on the target machine:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Set in .env or export
|
|
||||||
INTERCEPT_IMAGE=ghcr.io/youruser/intercept:latest
|
|
||||||
|
|
||||||
# Then just run
|
|
||||||
docker compose --profile basic up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
### ADS-B History (Optional)
|
### ADS-B History (Optional)
|
||||||
|
|
||||||
@@ -240,7 +200,6 @@ Created by **smittix** - [GitHub](https://github.com/smittix)
|
|||||||
[acarsdec](https://github.com/TLeconte/acarsdec) |
|
[acarsdec](https://github.com/TLeconte/acarsdec) |
|
||||||
[aircrack-ng](https://www.aircrack-ng.org/) |
|
[aircrack-ng](https://www.aircrack-ng.org/) |
|
||||||
[Leaflet.js](https://leafletjs.com/) |
|
[Leaflet.js](https://leafletjs.com/) |
|
||||||
[SatDump](https://github.com/SatDump/SatDump) |
|
|
||||||
[Celestrak](https://celestrak.org/) |
|
[Celestrak](https://celestrak.org/) |
|
||||||
[Priyom.org](https://priyom.org/)
|
[Priyom.org](https://priyom.org/)
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ from typing import Any
|
|||||||
|
|
||||||
from flask import Flask, render_template, jsonify, send_file, Response, request,redirect, url_for, flash, session
|
from flask import Flask, render_template, jsonify, send_file, Response, request,redirect, url_for, flash, session
|
||||||
from werkzeug.security import check_password_hash
|
from werkzeug.security import check_password_hash
|
||||||
from config import VERSION, CHANGELOG, SHARED_OBSERVER_LOCATION_ENABLED, DEFAULT_LATITUDE, DEFAULT_LONGITUDE
|
from config import VERSION, CHANGELOG, SHARED_OBSERVER_LOCATION_ENABLED
|
||||||
from utils.dependencies import check_tool, check_all_dependencies, TOOL_DEPENDENCIES
|
from utils.dependencies import check_tool, check_all_dependencies, TOOL_DEPENDENCIES
|
||||||
from utils.process import cleanup_stale_processes
|
from utils.process import cleanup_stale_processes
|
||||||
from utils.sdr import SDRFactory
|
from utils.sdr import SDRFactory
|
||||||
@@ -236,76 +236,47 @@ cleanup_manager.register(deauth_alerts)
|
|||||||
# SDR DEVICE REGISTRY
|
# SDR DEVICE REGISTRY
|
||||||
# ============================================
|
# ============================================
|
||||||
# Tracks which mode is using which SDR device to prevent conflicts
|
# Tracks which mode is using which SDR device to prevent conflicts
|
||||||
# Key: device_index (int), Value: {sdr_type: mode_name}
|
# Key: device_index (int), Value: mode_name (str)
|
||||||
sdr_device_registry: dict[int, dict[str, str]] = {}
|
sdr_device_registry: dict[int, str] = {}
|
||||||
sdr_device_registry_lock = threading.Lock()
|
sdr_device_registry_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
def claim_sdr_device(device_index: int, mode_name: str, sdr_type: str = 'rtlsdr') -> str | None:
|
def claim_sdr_device(device_index: int, mode_name: str) -> str | None:
|
||||||
"""Claim an SDR device for a mode.
|
"""Claim an SDR device for a mode.
|
||||||
|
|
||||||
Checks the in-app registry first, then probes the USB device to
|
|
||||||
catch stale handles held by external processes (e.g. a leftover
|
|
||||||
rtl_fm from a previous crash).
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
device_index: The SDR device index to claim
|
device_index: The SDR device index to claim
|
||||||
mode_name: Name of the mode claiming the device (e.g., 'sensor', 'rtlamr')
|
mode_name: Name of the mode claiming the device (e.g., 'sensor', 'rtlamr')
|
||||||
sdr_type: SDR hardware type (e.g., 'rtlsdr', 'hackrf')
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Error message if device is in use, None if successfully claimed
|
Error message if device is in use, None if successfully claimed
|
||||||
"""
|
"""
|
||||||
sdr_type_key = str(sdr_type or 'rtlsdr').lower()
|
|
||||||
|
|
||||||
with sdr_device_registry_lock:
|
with sdr_device_registry_lock:
|
||||||
device_entry = sdr_device_registry.get(device_index, {})
|
if device_index in sdr_device_registry:
|
||||||
if sdr_type_key in device_entry:
|
in_use_by = sdr_device_registry[device_index]
|
||||||
in_use_by = device_entry[sdr_type_key]
|
|
||||||
return f'SDR device {device_index} is in use by {in_use_by}. Stop {in_use_by} first or use a different device.'
|
return f'SDR device {device_index} is in use by {in_use_by}. Stop {in_use_by} first or use a different device.'
|
||||||
|
sdr_device_registry[device_index] = mode_name
|
||||||
# Probe the USB device to catch external processes holding the handle
|
|
||||||
# Only relevant for RTL-SDR devices
|
|
||||||
if sdr_type_key == 'rtlsdr':
|
|
||||||
try:
|
|
||||||
from utils.sdr.detection import probe_rtlsdr_device
|
|
||||||
usb_error = probe_rtlsdr_device(device_index)
|
|
||||||
if usb_error:
|
|
||||||
return usb_error
|
|
||||||
except Exception:
|
|
||||||
pass # If probe fails, let the caller proceed normally
|
|
||||||
|
|
||||||
if device_index not in sdr_device_registry:
|
|
||||||
sdr_device_registry[device_index] = {}
|
|
||||||
sdr_device_registry[device_index][sdr_type_key] = mode_name
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def release_sdr_device(device_index: int, sdr_type: str = 'rtlsdr') -> None:
|
def release_sdr_device(device_index: int) -> None:
|
||||||
"""Release an SDR device from the registry.
|
"""Release an SDR device from the registry.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
device_index: The SDR device index to release
|
device_index: The SDR device index to release
|
||||||
sdr_type: SDR hardware type (e.g., 'rtlsdr', 'hackrf')
|
|
||||||
"""
|
"""
|
||||||
sdr_type_key = str(sdr_type or 'rtlsdr').lower()
|
|
||||||
with sdr_device_registry_lock:
|
with sdr_device_registry_lock:
|
||||||
entry = sdr_device_registry.get(device_index)
|
sdr_device_registry.pop(device_index, None)
|
||||||
if not entry:
|
|
||||||
return
|
|
||||||
entry.pop(sdr_type_key, None)
|
|
||||||
if not entry:
|
|
||||||
sdr_device_registry.pop(device_index, None)
|
|
||||||
|
|
||||||
|
|
||||||
def get_sdr_device_status() -> dict[int, dict[str, str]]:
|
def get_sdr_device_status() -> dict[int, str]:
|
||||||
"""Get current SDR device allocations.
|
"""Get current SDR device allocations.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Dictionary mapping device indices to {sdr_type: mode_name}
|
Dictionary mapping device indices to mode names
|
||||||
"""
|
"""
|
||||||
with sdr_device_registry_lock:
|
with sdr_device_registry_lock:
|
||||||
return {idx: dict(modes) for idx, modes in sdr_device_registry.items()}
|
return dict(sdr_device_registry)
|
||||||
|
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
@@ -321,10 +292,6 @@ def require_login():
|
|||||||
if request.path.startswith('/listening/audio/'):
|
if request.path.startswith('/listening/audio/'):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Allow WebSocket upgrade requests (page load already required auth)
|
|
||||||
if request.path.startswith('/ws/'):
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Controller API endpoints use API key auth, not session auth
|
# Controller API endpoints use API key auth, not session auth
|
||||||
# Allow agent push/pull endpoints without session login
|
# Allow agent push/pull endpoints without session login
|
||||||
if request.path.startswith('/controller/'):
|
if request.path.startswith('/controller/'):
|
||||||
@@ -385,8 +352,6 @@ def index() -> str:
|
|||||||
version=VERSION,
|
version=VERSION,
|
||||||
changelog=CHANGELOG,
|
changelog=CHANGELOG,
|
||||||
shared_observer_location=SHARED_OBSERVER_LOCATION_ENABLED,
|
shared_observer_location=SHARED_OBSERVER_LOCATION_ENABLED,
|
||||||
default_latitude=DEFAULT_LATITUDE,
|
|
||||||
default_longitude=DEFAULT_LONGITUDE,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -411,11 +376,8 @@ def get_devices_status() -> Response:
|
|||||||
result = []
|
result = []
|
||||||
for device in devices:
|
for device in devices:
|
||||||
d = device.to_dict()
|
d = device.to_dict()
|
||||||
sdr_type_key = device.sdr_type.value if hasattr(device.sdr_type, 'value') else str(device.sdr_type)
|
d['in_use'] = device.index in registry
|
||||||
sdr_type_key = str(sdr_type_key).lower()
|
d['used_by'] = registry.get(device.index)
|
||||||
device_registry = registry.get(device.index, {})
|
|
||||||
d['in_use'] = sdr_type_key in device_registry
|
|
||||||
d['used_by'] = device_registry.get(sdr_type_key)
|
|
||||||
result.append(d)
|
result.append(d)
|
||||||
|
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
@@ -709,8 +671,8 @@ def kill_all() -> Response:
|
|||||||
'rtl_fm', 'multimon-ng', 'rtl_433',
|
'rtl_fm', 'multimon-ng', 'rtl_433',
|
||||||
'airodump-ng', 'aireplay-ng', 'airmon-ng',
|
'airodump-ng', 'aireplay-ng', 'airmon-ng',
|
||||||
'dump1090', 'acarsdec', 'direwolf', 'AIS-catcher',
|
'dump1090', 'acarsdec', 'direwolf', 'AIS-catcher',
|
||||||
'hcitool', 'bluetoothctl', 'satdump', 'dsd',
|
'hcitool', 'bluetoothctl', 'dsd',
|
||||||
'rtl_tcp', 'rtl_power', 'rtlamr', 'ffmpeg'
|
'rtl_tcp', 'rtl_power', 'rtlamr', 'ffmpeg',
|
||||||
]
|
]
|
||||||
|
|
||||||
for proc in processes_to_kill:
|
for proc in processes_to_kill:
|
||||||
@@ -775,7 +737,7 @@ def kill_all() -> Response:
|
|||||||
# Reset Bluetooth v2 scanner
|
# Reset Bluetooth v2 scanner
|
||||||
try:
|
try:
|
||||||
reset_bluetooth_scanner()
|
reset_bluetooth_scanner()
|
||||||
killed.append('bluetooth')
|
killed.append('bluetooth_scanner')
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -868,18 +830,6 @@ def main() -> None:
|
|||||||
from utils.database import init_db
|
from utils.database import init_db
|
||||||
init_db()
|
init_db()
|
||||||
|
|
||||||
# Register database cleanup functions
|
|
||||||
from utils.database import (
|
|
||||||
cleanup_old_signal_history,
|
|
||||||
cleanup_old_timeline_entries,
|
|
||||||
cleanup_old_dsc_alerts,
|
|
||||||
cleanup_old_payloads
|
|
||||||
)
|
|
||||||
cleanup_manager.register_db_cleanup(cleanup_old_signal_history, interval_multiplier=1440) # Every 24 hours
|
|
||||||
cleanup_manager.register_db_cleanup(cleanup_old_timeline_entries, interval_multiplier=1440) # Every 24 hours
|
|
||||||
cleanup_manager.register_db_cleanup(cleanup_old_dsc_alerts, interval_multiplier=1440) # Every 24 hours
|
|
||||||
cleanup_manager.register_db_cleanup(cleanup_old_payloads, interval_multiplier=1440) # Every 24 hours
|
|
||||||
|
|
||||||
# Start automatic cleanup of stale data entries
|
# Start automatic cleanup of stale data entries
|
||||||
cleanup_manager.start()
|
cleanup_manager.start()
|
||||||
|
|
||||||
@@ -887,15 +837,6 @@ def main() -> None:
|
|||||||
from routes import register_blueprints
|
from routes import register_blueprints
|
||||||
register_blueprints(app)
|
register_blueprints(app)
|
||||||
|
|
||||||
# Initialize TLE auto-refresh (must be after blueprint registration)
|
|
||||||
try:
|
|
||||||
from routes.satellite import init_tle_auto_refresh
|
|
||||||
import os
|
|
||||||
if not os.environ.get('TESTING'):
|
|
||||||
init_tle_auto_refresh()
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Failed to initialize TLE auto-refresh: {e}")
|
|
||||||
|
|
||||||
# Update TLE data in background thread (non-blocking)
|
# Update TLE data in background thread (non-blocking)
|
||||||
def update_tle_background():
|
def update_tle_background():
|
||||||
try:
|
try:
|
||||||
@@ -928,14 +869,6 @@ def main() -> None:
|
|||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
print(f"KiwiSDR audio proxy disabled: {e}")
|
print(f"KiwiSDR audio proxy disabled: {e}")
|
||||||
|
|
||||||
# Initialize WebSocket for waterfall streaming
|
|
||||||
try:
|
|
||||||
from routes.waterfall_websocket import init_waterfall_websocket
|
|
||||||
init_waterfall_websocket(app)
|
|
||||||
print("WebSocket waterfall streaming enabled")
|
|
||||||
except ImportError as e:
|
|
||||||
print(f"WebSocket waterfall disabled: {e}")
|
|
||||||
|
|
||||||
print(f"Open http://localhost:{args.port} in your browser")
|
print(f"Open http://localhost:{args.port} in your browser")
|
||||||
print()
|
print()
|
||||||
print("Press Ctrl+C to stop")
|
print("Press Ctrl+C to stop")
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# INTERCEPT - Multi-architecture Docker image builder
|
|
||||||
#
|
|
||||||
# Builds for both linux/amd64 and linux/arm64 using Docker buildx.
|
|
||||||
# Run this on your x64 machine to cross-compile the arm64 image
|
|
||||||
# instead of building natively on the RPi5.
|
|
||||||
#
|
|
||||||
# Prerequisites (one-time setup):
|
|
||||||
# docker run --privileged --rm tonistiigi/binfmt --install all
|
|
||||||
# docker buildx create --name intercept-builder --use --bootstrap
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# ./build-multiarch.sh # Build both platforms, load locally
|
|
||||||
# ./build-multiarch.sh --push # Build and push to registry
|
|
||||||
# ./build-multiarch.sh --arm64-only # Build arm64 only (for RPi)
|
|
||||||
# REGISTRY=ghcr.io/user ./build-multiarch.sh --push
|
|
||||||
#
|
|
||||||
# Environment variables:
|
|
||||||
# REGISTRY - Container registry (default: docker.io/library)
|
|
||||||
# IMAGE_NAME - Image name (default: intercept)
|
|
||||||
# IMAGE_TAG - Image tag (default: latest)
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Configuration
|
|
||||||
REGISTRY="${REGISTRY:-}"
|
|
||||||
IMAGE_NAME="${IMAGE_NAME:-intercept}"
|
|
||||||
IMAGE_TAG="${IMAGE_TAG:-latest}"
|
|
||||||
BUILDER_NAME="intercept-builder"
|
|
||||||
PLATFORMS="linux/amd64,linux/arm64"
|
|
||||||
|
|
||||||
# Parse arguments
|
|
||||||
PUSH=false
|
|
||||||
LOAD=false
|
|
||||||
ARM64_ONLY=false
|
|
||||||
|
|
||||||
for arg in "$@"; do
|
|
||||||
case $arg in
|
|
||||||
--push) PUSH=true ;;
|
|
||||||
--load) LOAD=true ;;
|
|
||||||
--arm64-only)
|
|
||||||
ARM64_ONLY=true
|
|
||||||
PLATFORMS="linux/arm64"
|
|
||||||
;;
|
|
||||||
--amd64-only)
|
|
||||||
PLATFORMS="linux/amd64"
|
|
||||||
;;
|
|
||||||
--help|-h)
|
|
||||||
echo "Usage: $0 [--push] [--load] [--arm64-only] [--amd64-only]"
|
|
||||||
echo ""
|
|
||||||
echo "Options:"
|
|
||||||
echo " --push Push to container registry"
|
|
||||||
echo " --load Load into local Docker (single platform only)"
|
|
||||||
echo " --arm64-only Build arm64 only (for RPi5 deployment)"
|
|
||||||
echo " --amd64-only Build amd64 only"
|
|
||||||
echo ""
|
|
||||||
echo "Environment variables:"
|
|
||||||
echo " REGISTRY Container registry (e.g. ghcr.io/username)"
|
|
||||||
echo " IMAGE_NAME Image name (default: intercept)"
|
|
||||||
echo " IMAGE_TAG Image tag (default: latest)"
|
|
||||||
echo ""
|
|
||||||
echo "Examples:"
|
|
||||||
echo " $0 --push # Build both, push"
|
|
||||||
echo " REGISTRY=ghcr.io/myuser $0 --push # Push to GHCR"
|
|
||||||
echo " $0 --arm64-only --load # Build arm64, load locally"
|
|
||||||
echo " $0 --arm64-only --push && ssh rpi docker pull # Build + deploy to RPi"
|
|
||||||
exit 0
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
echo "Unknown option: $arg"
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
# Build full image reference
|
|
||||||
if [ -n "$REGISTRY" ]; then
|
|
||||||
FULL_IMAGE="${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}"
|
|
||||||
else
|
|
||||||
FULL_IMAGE="${IMAGE_NAME}:${IMAGE_TAG}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "============================================"
|
|
||||||
echo " INTERCEPT Multi-Architecture Builder"
|
|
||||||
echo "============================================"
|
|
||||||
echo " Image: ${FULL_IMAGE}"
|
|
||||||
echo " Platforms: ${PLATFORMS}"
|
|
||||||
echo " Push: ${PUSH}"
|
|
||||||
echo "============================================"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Check if buildx builder exists, create if not
|
|
||||||
if ! docker buildx inspect "$BUILDER_NAME" >/dev/null 2>&1; then
|
|
||||||
echo "Creating buildx builder: ${BUILDER_NAME}"
|
|
||||||
docker buildx create --name "$BUILDER_NAME" --use --bootstrap
|
|
||||||
|
|
||||||
# Check for QEMU support
|
|
||||||
if ! docker run --rm --privileged tonistiigi/binfmt --install all >/dev/null 2>&1; then
|
|
||||||
echo "WARNING: QEMU binfmt setup may have failed."
|
|
||||||
echo "Run: docker run --privileged --rm tonistiigi/binfmt --install all"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
docker buildx use "$BUILDER_NAME"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Build command
|
|
||||||
BUILD_CMD="docker buildx build --platform ${PLATFORMS} --tag ${FULL_IMAGE}"
|
|
||||||
|
|
||||||
if [ "$PUSH" = true ]; then
|
|
||||||
BUILD_CMD="${BUILD_CMD} --push"
|
|
||||||
echo "Will push to: ${FULL_IMAGE}"
|
|
||||||
elif [ "$LOAD" = true ]; then
|
|
||||||
# --load only works with single platform
|
|
||||||
if echo "$PLATFORMS" | grep -q ","; then
|
|
||||||
echo "ERROR: --load only works with a single platform."
|
|
||||||
echo "Use --arm64-only or --amd64-only with --load."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
BUILD_CMD="${BUILD_CMD} --load"
|
|
||||||
echo "Will load into local Docker"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Building..."
|
|
||||||
echo "Command: ${BUILD_CMD} ."
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
$BUILD_CMD .
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "============================================"
|
|
||||||
echo " Build complete!"
|
|
||||||
if [ "$PUSH" = true ]; then
|
|
||||||
echo " Image pushed to: ${FULL_IMAGE}"
|
|
||||||
echo ""
|
|
||||||
echo " Pull on RPi5:"
|
|
||||||
echo " docker pull ${FULL_IMAGE}"
|
|
||||||
fi
|
|
||||||
echo "============================================"
|
|
||||||
@@ -7,23 +7,10 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
|
|
||||||
# Application version
|
# Application version
|
||||||
VERSION = "2.15.0"
|
VERSION = "2.14.0"
|
||||||
|
|
||||||
# Changelog - latest release notes (shown on welcome screen)
|
# Changelog - latest release notes (shown on welcome screen)
|
||||||
CHANGELOG = [
|
CHANGELOG = [
|
||||||
{
|
|
||||||
"version": "2.15.0",
|
|
||||||
"date": "February 2026",
|
|
||||||
"highlights": [
|
|
||||||
"Real-time WebSocket waterfall with I/Q capture and server-side FFT",
|
|
||||||
"Cross-module frequency routing from Listening Post to decoders",
|
|
||||||
"Pure Python SSTV decoder replacing broken slowrx dependency",
|
|
||||||
"Real-time signal scope for pager, sensor, and SSTV modes",
|
|
||||||
"USB-level device probe to prevent cryptic rtl_fm crashes",
|
|
||||||
"DMR dsd-fme protocol fixes, tuning controls, and state sync",
|
|
||||||
"SDR device lock-up fix from unreleased device registry on crash",
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"version": "2.14.0",
|
"version": "2.14.0",
|
||||||
"date": "February 2026",
|
"date": "February 2026",
|
||||||
@@ -211,37 +198,21 @@ ADSB_HISTORY_QUEUE_SIZE = _get_env_int('ADSB_HISTORY_QUEUE_SIZE', 50000)
|
|||||||
|
|
||||||
# Observer location settings
|
# Observer location settings
|
||||||
SHARED_OBSERVER_LOCATION_ENABLED = _get_env_bool('SHARED_OBSERVER_LOCATION', True)
|
SHARED_OBSERVER_LOCATION_ENABLED = _get_env_bool('SHARED_OBSERVER_LOCATION', True)
|
||||||
DEFAULT_LATITUDE = _get_env_float('DEFAULT_LAT', 0.0)
|
|
||||||
DEFAULT_LONGITUDE = _get_env_float('DEFAULT_LON', 0.0)
|
|
||||||
|
|
||||||
# Satellite settings
|
# Satellite settings
|
||||||
SATELLITE_UPDATE_INTERVAL = _get_env_int('SATELLITE_UPDATE_INTERVAL', 30)
|
SATELLITE_UPDATE_INTERVAL = _get_env_int('SATELLITE_UPDATE_INTERVAL', 30)
|
||||||
SATELLITE_TRAJECTORY_POINTS = _get_env_int('SATELLITE_TRAJECTORY_POINTS', 30)
|
SATELLITE_TRAJECTORY_POINTS = _get_env_int('SATELLITE_TRAJECTORY_POINTS', 30)
|
||||||
SATELLITE_ORBIT_MINUTES = _get_env_int('SATELLITE_ORBIT_MINUTES', 45)
|
SATELLITE_ORBIT_MINUTES = _get_env_int('SATELLITE_ORBIT_MINUTES', 45)
|
||||||
|
|
||||||
# Weather satellite settings
|
|
||||||
WEATHER_SAT_DEFAULT_GAIN = _get_env_float('WEATHER_SAT_GAIN', 40.0)
|
|
||||||
WEATHER_SAT_SAMPLE_RATE = _get_env_int('WEATHER_SAT_SAMPLE_RATE', 1000000)
|
|
||||||
WEATHER_SAT_MIN_ELEVATION = _get_env_float('WEATHER_SAT_MIN_ELEVATION', 15.0)
|
|
||||||
WEATHER_SAT_PREDICTION_HOURS = _get_env_int('WEATHER_SAT_PREDICTION_HOURS', 24)
|
|
||||||
WEATHER_SAT_SCHEDULE_REFRESH_MINUTES = _get_env_int('WEATHER_SAT_SCHEDULE_REFRESH_MINUTES', 30)
|
|
||||||
WEATHER_SAT_CAPTURE_BUFFER_SECONDS = _get_env_int('WEATHER_SAT_CAPTURE_BUFFER_SECONDS', 30)
|
|
||||||
|
|
||||||
# Update checking
|
# Update checking
|
||||||
GITHUB_REPO = _get_env('GITHUB_REPO', 'smittix/intercept')
|
GITHUB_REPO = _get_env('GITHUB_REPO', 'smittix/intercept')
|
||||||
UPDATE_CHECK_ENABLED = _get_env_bool('UPDATE_CHECK_ENABLED', True)
|
UPDATE_CHECK_ENABLED = _get_env_bool('UPDATE_CHECK_ENABLED', True)
|
||||||
UPDATE_CHECK_INTERVAL_HOURS = _get_env_int('UPDATE_CHECK_INTERVAL_HOURS', 6)
|
UPDATE_CHECK_INTERVAL_HOURS = _get_env_int('UPDATE_CHECK_INTERVAL_HOURS', 6)
|
||||||
|
|
||||||
# Alerting
|
|
||||||
ALERT_WEBHOOK_URL = _get_env('ALERT_WEBHOOK_URL', '')
|
|
||||||
ALERT_WEBHOOK_SECRET = _get_env('ALERT_WEBHOOK_SECRET', '')
|
|
||||||
ALERT_WEBHOOK_TIMEOUT = _get_env_int('ALERT_WEBHOOK_TIMEOUT', 5)
|
|
||||||
|
|
||||||
# Admin credentials
|
# Admin credentials
|
||||||
ADMIN_USERNAME = _get_env('ADMIN_USERNAME', 'admin')
|
ADMIN_USERNAME = _get_env('ADMIN_USERNAME', 'admin')
|
||||||
ADMIN_PASSWORD = _get_env('ADMIN_PASSWORD', 'admin')
|
ADMIN_PASSWORD = _get_env('ADMIN_PASSWORD', 'admin')
|
||||||
|
|
||||||
|
|
||||||
def configure_logging() -> None:
|
def configure_logging() -> None:
|
||||||
"""Configure application logging."""
|
"""Configure application logging."""
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
|
|||||||
+10
-28
@@ -1,31 +1,27 @@
|
|||||||
# INTERCEPT - Signal Intelligence Platform
|
# INTERCEPT - Signal Intelligence Platform
|
||||||
# Docker Compose configuration for easy deployment
|
# Docker Compose configuration for easy deployment
|
||||||
#
|
#
|
||||||
# Basic usage (build locally):
|
# Basic usage:
|
||||||
# docker compose --profile basic up -d --build
|
# docker compose up -d
|
||||||
#
|
|
||||||
# Basic usage (pre-built image from registry):
|
|
||||||
# INTERCEPT_IMAGE=ghcr.io/user/intercept:latest docker compose --profile basic up -d
|
|
||||||
#
|
#
|
||||||
# With ADS-B history (Postgres):
|
# With ADS-B history (Postgres):
|
||||||
# docker compose --profile history up -d
|
# docker compose --profile history up -d
|
||||||
|
|
||||||
services:
|
services:
|
||||||
intercept:
|
intercept:
|
||||||
# When INTERCEPT_IMAGE is set, use that pre-built image; otherwise build locally
|
|
||||||
image: ${INTERCEPT_IMAGE:-intercept:latest}
|
|
||||||
build: .
|
build: .
|
||||||
container_name: intercept
|
container_name: intercept
|
||||||
ports:
|
ports:
|
||||||
- "5050:5050"
|
- "5050:5050"
|
||||||
# Privileged mode required for USB SDR device access
|
# Privileged mode required for USB SDR device access
|
||||||
|
# Alternatively, use device mapping (see below)
|
||||||
privileged: true
|
privileged: true
|
||||||
# USB device mapping for all USB devices
|
# USB device mapping (alternative to privileged mode)
|
||||||
devices:
|
# devices:
|
||||||
- /dev/bus/usb:/dev/bus/usb
|
# - /dev/bus/usb:/dev/bus/usb
|
||||||
volumes:
|
# volumes:
|
||||||
# Persist decoded images and database across container rebuilds
|
# Persist data directory
|
||||||
- ./data:/app/data
|
# - ./data:/app/data
|
||||||
# Optional: mount logs directory
|
# Optional: mount logs directory
|
||||||
# - ./logs:/app/logs
|
# - ./logs:/app/logs
|
||||||
environment:
|
environment:
|
||||||
@@ -44,9 +40,6 @@ services:
|
|||||||
- INTERCEPT_ADSB_AUTO_START=${INTERCEPT_ADSB_AUTO_START:-false}
|
- INTERCEPT_ADSB_AUTO_START=${INTERCEPT_ADSB_AUTO_START:-false}
|
||||||
# Shared observer location across modules
|
# Shared observer location across modules
|
||||||
- INTERCEPT_SHARED_OBSERVER_LOCATION=${INTERCEPT_SHARED_OBSERVER_LOCATION:-true}
|
- INTERCEPT_SHARED_OBSERVER_LOCATION=${INTERCEPT_SHARED_OBSERVER_LOCATION:-true}
|
||||||
# Default observer coordinates (set to your location to skip the GPS prompt)
|
|
||||||
# - INTERCEPT_DEFAULT_LAT=${INTERCEPT_DEFAULT_LAT:-0}
|
|
||||||
# - INTERCEPT_DEFAULT_LON=${INTERCEPT_DEFAULT_LON:-0}
|
|
||||||
# Network mode for WiFi scanning (requires host network)
|
# Network mode for WiFi scanning (requires host network)
|
||||||
# network_mode: host
|
# network_mode: host
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
@@ -60,23 +53,15 @@ services:
|
|||||||
# ADS-B history with Postgres persistence
|
# ADS-B history with Postgres persistence
|
||||||
# Enable with: docker compose --profile history up -d
|
# Enable with: docker compose --profile history up -d
|
||||||
intercept-history:
|
intercept-history:
|
||||||
# Same image/build fallback pattern as above
|
|
||||||
image: ${INTERCEPT_IMAGE:-intercept:latest}
|
|
||||||
build: .
|
build: .
|
||||||
container_name: intercept-history
|
container_name: intercept
|
||||||
profiles:
|
profiles:
|
||||||
- history
|
- history
|
||||||
depends_on:
|
depends_on:
|
||||||
- adsb_db
|
- adsb_db
|
||||||
ports:
|
ports:
|
||||||
- "5050:5050"
|
- "5050:5050"
|
||||||
# Privileged mode required for USB SDR device access
|
|
||||||
privileged: true
|
privileged: true
|
||||||
# USB device mapping for all USB devices
|
|
||||||
devices:
|
|
||||||
- /dev/bus/usb:/dev/bus/usb
|
|
||||||
volumes:
|
|
||||||
- ./data:/app/data
|
|
||||||
environment:
|
environment:
|
||||||
- INTERCEPT_HOST=0.0.0.0
|
- INTERCEPT_HOST=0.0.0.0
|
||||||
- INTERCEPT_PORT=5050
|
- INTERCEPT_PORT=5050
|
||||||
@@ -91,9 +76,6 @@ services:
|
|||||||
- INTERCEPT_ADSB_AUTO_START=${INTERCEPT_ADSB_AUTO_START:-false}
|
- INTERCEPT_ADSB_AUTO_START=${INTERCEPT_ADSB_AUTO_START:-false}
|
||||||
# Shared observer location across modules
|
# Shared observer location across modules
|
||||||
- INTERCEPT_SHARED_OBSERVER_LOCATION=${INTERCEPT_SHARED_OBSERVER_LOCATION:-true}
|
- INTERCEPT_SHARED_OBSERVER_LOCATION=${INTERCEPT_SHARED_OBSERVER_LOCATION:-true}
|
||||||
# Default observer coordinates (set to your location to skip the GPS prompt)
|
|
||||||
# - INTERCEPT_DEFAULT_LAT=${INTERCEPT_DEFAULT_LAT:-0}
|
|
||||||
# - INTERCEPT_DEFAULT_LON=${INTERCEPT_DEFAULT_LON:-0}
|
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "-sf", "http://localhost:5050/health"]
|
test: ["CMD", "curl", "-sf", "http://localhost:5050/health"]
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Download sample NOAA APT recordings for testing the weather satellite
|
|
||||||
# test-decode feature. These are FM-demodulated audio WAV files.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# ./download-weather-sat-samples.sh
|
|
||||||
# docker exec intercept /app/download-weather-sat-samples.sh
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SAMPLE_DIR="$(dirname "$0")/data/weather_sat/samples"
|
|
||||||
mkdir -p "$SAMPLE_DIR"
|
|
||||||
|
|
||||||
echo "Downloading NOAA APT sample files to $SAMPLE_DIR ..."
|
|
||||||
|
|
||||||
# Full satellite pass recorded over Argentina (NOAA, 11025 Hz mono WAV)
|
|
||||||
# Source: https://github.com/martinber/noaa-apt
|
|
||||||
if [ ! -f "$SAMPLE_DIR/noaa_apt_argentina.wav" ]; then
|
|
||||||
echo " -> noaa_apt_argentina.wav (18 MB) ..."
|
|
||||||
curl -fSL -o "$SAMPLE_DIR/noaa_apt_argentina.wav" \
|
|
||||||
"https://noaa-apt.mbernardi.com.ar/examples/argentina.wav"
|
|
||||||
else
|
|
||||||
echo " -> noaa_apt_argentina.wav (already exists)"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Done. Test decode with:"
|
|
||||||
echo " Satellite: NOAA-18"
|
|
||||||
echo " File path: data/weather_sat/samples/noaa_apt_argentina.wav"
|
|
||||||
echo " Sample rate: 11025 Hz"
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
DMSP 5D-3 F16 (USA 172)
|
|
||||||
1 28054U 03048A 26037.66410905 .00000171 00000+0 11311-3 0 9991
|
|
||||||
2 28054 99.0018 60.5544 0007736 150.6435 318.8272 14.14449870151032
|
|
||||||
METEOSAT-9 (MSG-2)
|
|
||||||
1 28912U 05049B 26037.20698824 .00000122 00000+0 00000+0 0 9990
|
|
||||||
2 28912 9.0646 55.4438 0001292 220.3216 340.7358 1.00280364 5681
|
|
||||||
DMSP 5D-3 F17 (USA 191)
|
|
||||||
1 29522U 06050A 26037.63495522 .00000221 00000+0 13641-3 0 9997
|
|
||||||
2 29522 98.7406 46.8646 0011088 71.3269 288.9107 14.14949568993957
|
|
||||||
FENGYUN 3A
|
|
||||||
1 32958U 08026A 26037.29889977 .00000162 00000+0 97205-4 0 9995
|
|
||||||
2 32958 98.6761 340.6748 0009336 139.4536 220.7337 14.19536323916838
|
|
||||||
GOES 14
|
|
||||||
1 35491U 09033A 26037.59737599 .00000128 00000+0 00000+0 0 9998
|
|
||||||
2 35491 1.3510 84.7861 0001663 279.3774 203.6871 1.00112472 5283
|
|
||||||
DMSP 5D-3 F18 (USA 210)
|
|
||||||
1 35951U 09057A 26037.59574243 .00000344 00000+0 20119-3 0 9997
|
|
||||||
2 35951 98.8912 18.7405 0010014 262.2671 97.7365 14.14814612841124
|
|
||||||
EWS-G2 (GOES 15)
|
|
||||||
1 36411U 10008A 26037.42417604 .00000037 00000+0 00000+0 0 9998
|
|
||||||
2 36411 0.9477 85.6904 0004764 200.6178 64.5237 1.00275731 58322
|
|
||||||
COMS 1
|
|
||||||
1 36744U 10032A 26037.66884865 -.00000343 00000+0 00000+0 0 9998
|
|
||||||
2 36744 4.4730 77.2684 0001088 239.9858 188.4845 1.00274368 49786
|
|
||||||
FENGYUN 3B
|
|
||||||
1 37214U 10059A 26037.62488625 .00000510 00000+0 28715-3 0 9992
|
|
||||||
2 37214 98.9821 82.9728 0021838 194.4193 280.6049 14.14810700788968
|
|
||||||
SUOMI NPP
|
|
||||||
1 37849U 11061A 26037.58885771 .00000151 00000+0 92735-4 0 9993
|
|
||||||
2 37849 98.7835 339.4455 0001677 23.1332 336.9919 14.19534335739918
|
|
||||||
METEOSAT-10 (MSG-3)
|
|
||||||
1 38552U 12035B 26037.34062893 -.00000007 00000+0 00000+0 0 9993
|
|
||||||
2 38552 4.3618 61.5789 0002324 286.1065 271.3938 1.00272839 49549
|
|
||||||
METOP-B
|
|
||||||
1 38771U 12049A 26037.61376690 .00000161 00000+0 93652-4 0 9994
|
|
||||||
2 38771 98.6708 91.6029 0002456 28.4142 331.7169 14.21434029694718
|
|
||||||
INSAT-3D
|
|
||||||
1 39216U 13038B 26037.58021591 -.00000338 00000+0 00000+0 0 9998
|
|
||||||
2 39216 1.5890 84.3012 0001719 220.0673 170.6954 1.00273812 45771
|
|
||||||
FENGYUN 3C
|
|
||||||
1 39260U 13052A 26037.57879946 .00000181 00000+0 11337-3 0 9991
|
|
||||||
2 39260 98.4839 17.5531 0015475 42.6626 317.5748 14.15718213640089
|
|
||||||
METEOR-M 2
|
|
||||||
1 40069U 14037A 26037.57010537 .00000364 00000+0 18579-3 0 9995
|
|
||||||
2 40069 98.4979 18.0359 0006835 60.5067 299.6792 14.21415164600761
|
|
||||||
HIMAWARI-8
|
|
||||||
1 40267U 14060A 26037.58238259 -.00000273 00000+0 00000+0 0 9991
|
|
||||||
2 40267 0.0457 252.0286 0000958 31.3580 203.5957 1.00278490 41450
|
|
||||||
FENGYUN 2G
|
|
||||||
1 40367U 14090A 26037.64556289 -.00000299 00000+0 00000+0 0 9996
|
|
||||||
2 40367 5.3089 74.4184 0001565 198.1345 195.9683 1.00263067 40698
|
|
||||||
METEOSAT-11 (MSG-4)
|
|
||||||
1 40732U 15034A 26037.62779616 .00000065 00000+0 00000+0 0 9990
|
|
||||||
2 40732 2.8728 71.8294 0001180 241.7344 58.8290 1.00268087 5909
|
|
||||||
ELEKTRO-L 2
|
|
||||||
1 41105U 15074A 26037.40900929 -.00000118 00000+0 00000+0 0 9998
|
|
||||||
2 41105 6.3653 72.1489 0003612 229.0998 328.0297 1.00272232 37198
|
|
||||||
INSAT-3DR
|
|
||||||
1 41752U 16054A 26037.65505200 -.00000075 00000+0 00000+0 0 9997
|
|
||||||
2 41752 0.0554 93.8053 0013744 184.8269 167.9427 1.00271627 34504
|
|
||||||
HIMAWARI-9
|
|
||||||
1 41836U 16064A 26037.58238259 -.00000273 00000+0 00000+0 0 9990
|
|
||||||
2 41836 0.0124 137.0088 0001068 210.1850 139.9064 1.00271322 33905
|
|
||||||
GOES 16
|
|
||||||
1 41866U 16071A 26037.60517604 -.00000089 00000+0 00000+0 0 9993
|
|
||||||
2 41866 0.1490 94.1417 0002832 199.6896 316.0413 1.00271854 33798
|
|
||||||
FENGYUN 4A
|
|
||||||
1 41882U 16077A 26037.65041625 -.00000356 00000+0 00000+0 0 9994
|
|
||||||
2 41882 1.9907 81.7886 0006284 132.9819 279.8453 1.00276098 33627
|
|
||||||
CYGFM05
|
|
||||||
1 41884U 16078A 26037.42561482 .00027408 00000+0 46309-3 0 9992
|
|
||||||
2 41884 34.9596 42.6579 0007295 332.2973 27.7361 15.50585086508404
|
|
||||||
CYGFM04
|
|
||||||
1 41885U 16078B 26037.34428483 .00032519 00000+0 49575-3 0 9994
|
|
||||||
2 41885 34.9348 16.2836 0005718 359.2189 0.8525 15.53424088508589
|
|
||||||
CYGFM02
|
|
||||||
1 41886U 16078C 26037.35007768 .00035591 00000+0 50564-3 0 9998
|
|
||||||
2 41886 34.9436 13.7490 0006836 2.8379 357.2383 15.55324468508720
|
|
||||||
CYGFM01
|
|
||||||
1 41887U 16078D 26037.39685921 .00028560 00000+0 47572-3 0 9999
|
|
||||||
2 41887 34.9425 44.8029 0007415 323.1915 36.8298 15.50976884508344
|
|
||||||
CYGFM08
|
|
||||||
1 41888U 16078E 26037.34185185 .00031327 00000+0 49606-3 0 9997
|
|
||||||
2 41888 34.9457 27.4597 0008083 350.5361 9.5208 15.52364941508578
|
|
||||||
CYGFM07
|
|
||||||
1 41890U 16078G 26037.32199955 .00032204 00000+0 49829-3 0 9990
|
|
||||||
2 41890 34.9475 16.2411 0005914 7.0804 353.0002 15.53017084508593
|
|
||||||
CYGFM03
|
|
||||||
1 41891U 16078H 26037.35550653 .00031487 00000+0 48940-3 0 9995
|
|
||||||
2 41891 34.9430 17.9804 0005939 349.1458 10.9136 15.52895386508574
|
|
||||||
FENGYUN 3D
|
|
||||||
1 43010U 17072A 26037.62659924 .00000092 00000+0 65298-4 0 9990
|
|
||||||
2 43010 98.9980 9.7978 0002479 69.6779 290.4663 14.19704535426460
|
|
||||||
NOAA 20 (JPSS-1)
|
|
||||||
1 43013U 17073A 26037.60336371 .00000124 00000+0 79520-4 0 9999
|
|
||||||
2 43013 98.7658 338.3064 0000377 14.6433 345.4754 14.19527655425942
|
|
||||||
GOES 17
|
|
||||||
1 43226U 18022A 26037.60794939 -.00000180 00000+0 00000+0 0 9993
|
|
||||||
2 43226 0.6016 88.1527 0002754 213.0089 324.8756 1.00269924 29115
|
|
||||||
FENGYUN 2H
|
|
||||||
1 43491U 18050A 26037.66161282 -.00000125 00000+0 00000+0 0 9992
|
|
||||||
2 43491 2.6948 80.6967 0002145 171.8276 201.3055 1.00274855 28134
|
|
||||||
METOP-C
|
|
||||||
1 43689U 18087A 26037.63948662 .00000167 00000+0 96262-4 0 9998
|
|
||||||
2 43689 98.6834 99.5280 0001629 143.8933 216.2355 14.21510040376280
|
|
||||||
GEO-KOMPSAT-2A
|
|
||||||
1 43823U 18100A 26037.57995591 .00000000 00000+0 00000+0 0 9996
|
|
||||||
2 43823 0.0152 95.1913 0001141 313.4173 65.1318 1.00271011 26327
|
|
||||||
METEOR-M2 2
|
|
||||||
1 44387U 19038A 26037.58492015 .00000244 00000+0 12531-3 0 9993
|
|
||||||
2 44387 98.9044 23.0180 0002141 55.2566 304.8814 14.24320728342700
|
|
||||||
ARKTIKA-M 1
|
|
||||||
1 47719U 21016A 26035.90384421 -.00000136 00000+0 00000+0 0 9994
|
|
||||||
2 47719 63.1930 76.4940 7230705 269.3476 15.2984 2.00623094 36131
|
|
||||||
FENGYUN 3E
|
|
||||||
1 49008U 21062A 26037.62586080 .00000245 00000+0 13631-3 0 9992
|
|
||||||
2 49008 98.7499 42.4910 0002627 96.2819 263.8657 14.19890127238058
|
|
||||||
GOES 18
|
|
||||||
1 51850U 22021A 26037.59876267 .00000098 00000+0 00000+0 0 9999
|
|
||||||
2 51850 0.0198 91.3546 0000843 290.2366 193.6737 1.00273310 5288
|
|
||||||
NOAA 21 (JPSS-2)
|
|
||||||
1 54234U 22150A 26037.56792604 .00000152 00000+0 92800-4 0 9995
|
|
||||||
2 54234 98.7521 338.1972 0001388 169.8161 190.3044 14.19543641168012
|
|
||||||
METEOSAT-12 (MTG-I1)
|
|
||||||
1 54743U 22170C 26037.62580281 -.00000006 00000+0 00000+0 0 9990
|
|
||||||
2 54743 0.7119 25.1556 0002027 273.4388 63.0828 1.00270670 11667
|
|
||||||
TIANMU-1 03
|
|
||||||
1 55973U 23039A 26037.63298084 .00025307 00000+0 57478-3 0 9994
|
|
||||||
2 55973 97.5143 206.9374 0002852 198.5193 161.5950 15.43014921160671
|
|
||||||
TIANMU-1 04
|
|
||||||
1 55974U 23039B 26037.59957323 .00027172 00000+0 60888-3 0 9999
|
|
||||||
2 55974 97.5075 206.0729 0003605 196.0743 164.0390 15.43399931160675
|
|
||||||
TIANMU-1 05
|
|
||||||
1 55975U 23039C 26037.60840428 .00024975 00000+0 56836-3 0 9995
|
|
||||||
2 55975 97.5122 206.5750 0002421 224.3240 135.7814 15.42959696160653
|
|
||||||
TIANMU-1 06
|
|
||||||
1 55976U 23039D 26037.60004198 .00024821 00000+0 55598-3 0 9996
|
|
||||||
2 55976 97.5133 207.0788 0002810 218.0193 142.0857 15.43432906160673
|
|
||||||
FENGYUN 3G
|
|
||||||
1 56232U 23055A 26037.30935013 .00046475 00000+0 74423-3 0 9993
|
|
||||||
2 56232 49.9940 300.8928 0009962 237.3703 122.6303 15.52544991159665
|
|
||||||
METEOR-M2 3
|
|
||||||
1 57166U 23091A 26037.62090481 .00000022 00000+0 28455-4 0 9999
|
|
||||||
2 57166 98.6282 95.1607 0004003 174.5474 185.5750 14.24034408135931
|
|
||||||
TIANMU-1 07
|
|
||||||
1 57399U 23101A 26037.63242936 .00011510 00000+0 41012-3 0 9991
|
|
||||||
2 57399 97.2786 91.2606 0002747 218.4597 141.6448 15.29074661141694
|
|
||||||
TIANMU-1 08
|
|
||||||
1 57400U 23101B 26037.66743594 .00011474 00000+0 41016-3 0 9996
|
|
||||||
2 57400 97.2774 91.0783 0004440 227.8102 132.2762 15.28966110141699
|
|
||||||
TIANMU-1 09
|
|
||||||
1 57401U 23101C 26037.65072558 .00011360 00000+0 40433-3 0 9997
|
|
||||||
2 57401 97.2732 90.5514 0003773 229.5297 130.5615 15.29113177141698
|
|
||||||
TIANMU-1 10
|
|
||||||
1 57402U 23101D 26037.61974057 .00011836 00000+0 42113-3 0 9994
|
|
||||||
2 57402 97.2810 91.4302 0005461 233.7620 126.3116 15.29106286141685
|
|
||||||
FENGYUN 3F
|
|
||||||
1 57490U 23111A 26037.61228373 .00000135 00000+0 84019-4 0 9997
|
|
||||||
2 57490 98.6988 109.9815 0001494 99.6638 260.4707 14.19912110130332
|
|
||||||
ARKTIKA-M 2
|
|
||||||
1 58584U 23198A 26037.15964049 .00000160 00000+0 00000+0 0 9994
|
|
||||||
2 58584 63.2225 168.8508 6872222 267.8808 18.8364 2.00612776 15698
|
|
||||||
TIANMU-1 11
|
|
||||||
1 58645U 23205A 26037.58628093 .00009545 00000+0 37951-3 0 9999
|
|
||||||
2 58645 97.3574 61.2485 0010997 103.8713 256.3749 15.25445149117601
|
|
||||||
TIANMU-1 12
|
|
||||||
1 58646U 23205B 26037.61705312 .00010066 00000+0 40129-3 0 9995
|
|
||||||
2 58646 97.3561 61.0663 0009308 89.8253 270.4052 15.25355570117590
|
|
||||||
TIANMU-1 13
|
|
||||||
1 58647U 23205C 26037.64894829 .00010029 00000+0 39925-3 0 9992
|
|
||||||
2 58647 97.3589 61.3229 0009456 74.8265 285.4018 15.25403883117592
|
|
||||||
TIANMU-1 14
|
|
||||||
1 58648U 23205D 26037.63305929 .00009719 00000+0 38718-3 0 9993
|
|
||||||
2 58648 97.3523 60.6045 0010314 77.9995 282.2399 15.25381326117592
|
|
||||||
TIANMU-1 19
|
|
||||||
1 58660U 23208A 26037.58812600 .00016491 00000+0 58449-3 0 9991
|
|
||||||
2 58660 97.4377 153.5627 0006125 66.0574 294.1307 15.29155961117352
|
|
||||||
TIANMU-1 20
|
|
||||||
1 58661U 23208B 26037.59661536 .00016638 00000+0 56823-3 0 9990
|
|
||||||
2 58661 97.4315 154.0738 0008420 72.4906 287.7255 15.30347593117439
|
|
||||||
TIANMU-1 21
|
|
||||||
1 58662U 23208C 26037.56944589 .00017161 00000+0 55253-3 0 9998
|
|
||||||
2 58662 97.4367 156.2063 0008160 67.8039 292.4068 15.32247056117540
|
|
||||||
TIANMU-1 22
|
|
||||||
1 58663U 23208D 26037.59847459 .00015396 00000+0 55169-3 0 9994
|
|
||||||
2 58663 97.4371 153.6033 0005010 87.2275 272.9538 15.28818503117364
|
|
||||||
TIANMU-1 15
|
|
||||||
1 58700U 24004A 26037.63062994 .00009739 00000+0 38850-3 0 9991
|
|
||||||
2 58700 97.4651 223.9243 0008449 88.7599 271.4607 15.25356935115862
|
|
||||||
TIANMU-1 16
|
|
||||||
1 58701U 24004B 26037.61474986 .00010691 00000+0 42590-3 0 9993
|
|
||||||
2 58701 97.4590 223.2544 0006831 91.0928 269.1093 15.25387104115863
|
|
||||||
TIANMU-1 17
|
|
||||||
1 58702U 24004C 26037.59783649 .00011079 00000+0 44078-3 0 9994
|
|
||||||
2 58702 97.4624 223.6760 0006020 92.0871 268.1056 15.25425175115852
|
|
||||||
TIANMU-1 18
|
|
||||||
1 58703U 24004D 26037.64767373 .00010786 00000+0 42976-3 0 9996
|
|
||||||
2 58703 97.4642 223.9320 0005432 91.0134 269.1726 15.25387870115860
|
|
||||||
INSAT-3DS
|
|
||||||
1 58990U 24033A 26037.64159978 -.00000153 00000+0 00000+0 0 9998
|
|
||||||
2 58990 0.0277 242.2492 0001855 99.2205 108.3003 1.00271452 45758
|
|
||||||
METEOR-M2 4
|
|
||||||
1 59051U 24039A 26037.62796654 .00000070 00000+0 51194-4 0 9991
|
|
||||||
2 59051 98.6849 358.6843 0006923 178.9165 181.2029 14.22412185100701
|
|
||||||
GOES 19
|
|
||||||
1 60133U 24119A 26037.61098274 -.00000246 00000+0 00000+0 0 9996
|
|
||||||
2 60133 0.0027 288.6290 0001204 74.2636 278.5881 1.00270967 5651
|
|
||||||
FENGYUN 3H
|
|
||||||
1 65815U 25219A 26037.60879211 .00000151 00000+0 91464-4 0 9990
|
|
||||||
2 65815 98.6649 341.0050 0001596 86.5100 273.6260 14.19924132 18857
|
|
||||||
+18
-125
@@ -679,7 +679,6 @@ class ModeManager:
|
|||||||
running_modes_detail[mode] = {
|
running_modes_detail[mode] = {
|
||||||
'started_at': info.get('started_at'),
|
'started_at': info.get('started_at'),
|
||||||
'device': params.get('device', params.get('device_index', 0)),
|
'device': params.get('device', params.get('device_index', 0)),
|
||||||
'sdr_type': str(params.get('sdr_type', 'rtlsdr')).lower(),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
status = {
|
status = {
|
||||||
@@ -699,22 +698,20 @@ class ModeManager:
|
|||||||
# Modes that use RTL-SDR devices
|
# Modes that use RTL-SDR devices
|
||||||
SDR_MODES = {'adsb', 'sensor', 'pager', 'ais', 'acars', 'dsc', 'rtlamr', 'listening_post'}
|
SDR_MODES = {'adsb', 'sensor', 'pager', 'ais', 'acars', 'dsc', 'rtlamr', 'listening_post'}
|
||||||
|
|
||||||
def get_sdr_in_use(self, device: int = 0, sdr_type: str = 'rtlsdr') -> str | None:
|
def get_sdr_in_use(self, device: int = 0) -> str | None:
|
||||||
"""Check if an SDR device is in use by another mode.
|
"""Check if an SDR device is in use by another mode.
|
||||||
|
|
||||||
Returns the mode name using the device, or None if available.
|
Returns the mode name using the device, or None if available.
|
||||||
"""
|
"""
|
||||||
sdr_type_key = str(sdr_type or 'rtlsdr').lower()
|
|
||||||
for mode, info in self.running_modes.items():
|
for mode, info in self.running_modes.items():
|
||||||
if mode in self.SDR_MODES:
|
if mode in self.SDR_MODES:
|
||||||
mode_device = info.get('params', {}).get('device', 0)
|
mode_device = info.get('params', {}).get('device', 0)
|
||||||
mode_sdr_type = str(info.get('params', {}).get('sdr_type', 'rtlsdr')).lower()
|
|
||||||
# Normalize to int for comparison
|
# Normalize to int for comparison
|
||||||
try:
|
try:
|
||||||
mode_device = int(mode_device)
|
mode_device = int(mode_device)
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
mode_device = 0
|
mode_device = 0
|
||||||
if mode_device == device and mode_sdr_type == sdr_type_key:
|
if mode_device == device:
|
||||||
return mode
|
return mode
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -734,8 +731,7 @@ class ModeManager:
|
|||||||
device = int(device)
|
device = int(device)
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
device = 0
|
device = 0
|
||||||
sdr_type = str(params.get('sdr_type', 'rtlsdr')).lower()
|
in_use_by = self.get_sdr_in_use(device)
|
||||||
in_use_by = self.get_sdr_in_use(device, sdr_type)
|
|
||||||
if in_use_by:
|
if in_use_by:
|
||||||
return {
|
return {
|
||||||
'status': 'error',
|
'status': 'error',
|
||||||
@@ -847,7 +843,6 @@ class ModeManager:
|
|||||||
'anomalies': getattr(self, 'tscm_anomalies', []),
|
'anomalies': getattr(self, 'tscm_anomalies', []),
|
||||||
'baseline': getattr(self, 'tscm_baseline', {}),
|
'baseline': getattr(self, 'tscm_baseline', {}),
|
||||||
'wifi_devices': list(self.wifi_networks.values()),
|
'wifi_devices': list(self.wifi_networks.values()),
|
||||||
'wifi_clients': list(getattr(self, 'tscm_wifi_clients', {}).values()),
|
|
||||||
'bt_devices': list(self.bluetooth_devices.values()),
|
'bt_devices': list(self.bluetooth_devices.values()),
|
||||||
'rf_signals': getattr(self, 'tscm_rf_signals', []),
|
'rf_signals': getattr(self, 'tscm_rf_signals', []),
|
||||||
}
|
}
|
||||||
@@ -1104,11 +1099,6 @@ class ModeManager:
|
|||||||
# Mode-specific cleanup
|
# Mode-specific cleanup
|
||||||
if mode == 'adsb':
|
if mode == 'adsb':
|
||||||
self.adsb_aircraft.clear()
|
self.adsb_aircraft.clear()
|
||||||
if 'adsb_mlat' in self.output_threads:
|
|
||||||
thread = self.output_threads['adsb_mlat']
|
|
||||||
if thread and thread.is_alive():
|
|
||||||
thread.join(timeout=1)
|
|
||||||
del self.output_threads['adsb_mlat']
|
|
||||||
elif mode == 'wifi':
|
elif mode == 'wifi':
|
||||||
self.wifi_networks.clear()
|
self.wifi_networks.clear()
|
||||||
self.wifi_clients.clear()
|
self.wifi_clients.clear()
|
||||||
@@ -1126,7 +1116,6 @@ class ModeManager:
|
|||||||
self.tscm_anomalies = []
|
self.tscm_anomalies = []
|
||||||
self.tscm_baseline = {}
|
self.tscm_baseline = {}
|
||||||
self.tscm_rf_signals = []
|
self.tscm_rf_signals = []
|
||||||
self.tscm_wifi_clients = {}
|
|
||||||
# Clear reported threat tracking sets
|
# Clear reported threat tracking sets
|
||||||
if hasattr(self, '_tscm_reported_wifi'):
|
if hasattr(self, '_tscm_reported_wifi'):
|
||||||
self._tscm_reported_wifi.clear()
|
self._tscm_reported_wifi.clear()
|
||||||
@@ -1324,16 +1313,10 @@ class ModeManager:
|
|||||||
sdr_type_str = params.get('sdr_type', 'rtlsdr')
|
sdr_type_str = params.get('sdr_type', 'rtlsdr')
|
||||||
remote_sbs_host = params.get('remote_sbs_host')
|
remote_sbs_host = params.get('remote_sbs_host')
|
||||||
remote_sbs_port = params.get('remote_sbs_port', 30003)
|
remote_sbs_port = params.get('remote_sbs_port', 30003)
|
||||||
mlat_sbs_host = params.get('mlat_sbs_host')
|
|
||||||
mlat_sbs_port = params.get('mlat_sbs_port', 30105)
|
|
||||||
|
|
||||||
# If remote SBS host provided, just connect to it
|
# If remote SBS host provided, just connect to it
|
||||||
if remote_sbs_host:
|
if remote_sbs_host:
|
||||||
result = self._start_adsb_sbs_connection(remote_sbs_host, remote_sbs_port, source_tag='adsb', thread_name='adsb')
|
return self._start_adsb_sbs_connection(remote_sbs_host, remote_sbs_port)
|
||||||
if mlat_sbs_host:
|
|
||||||
self._start_adsb_sbs_connection(mlat_sbs_host, mlat_sbs_port, source_tag='mlat', thread_name='adsb_mlat')
|
|
||||||
result['mlat_source'] = f'{mlat_sbs_host}:{mlat_sbs_port}'
|
|
||||||
return result
|
|
||||||
|
|
||||||
# Check if dump1090 already running on port 30003
|
# Check if dump1090 already running on port 30003
|
||||||
try:
|
try:
|
||||||
@@ -1343,11 +1326,7 @@ class ModeManager:
|
|||||||
sock.close()
|
sock.close()
|
||||||
if result == 0:
|
if result == 0:
|
||||||
logger.info("dump1090 already running, connecting to SBS port")
|
logger.info("dump1090 already running, connecting to SBS port")
|
||||||
result = self._start_adsb_sbs_connection('localhost', 30003, source_tag='adsb', thread_name='adsb')
|
return self._start_adsb_sbs_connection('localhost', 30003)
|
||||||
if mlat_sbs_host:
|
|
||||||
self._start_adsb_sbs_connection(mlat_sbs_host, mlat_sbs_port, source_tag='mlat', thread_name='adsb_mlat')
|
|
||||||
result['mlat_source'] = f'{mlat_sbs_host}:{mlat_sbs_port}'
|
|
||||||
return result
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -1404,11 +1383,7 @@ class ModeManager:
|
|||||||
return {'status': 'error', 'message': f'dump1090 failed to start: {stderr[:200]}'}
|
return {'status': 'error', 'message': f'dump1090 failed to start: {stderr[:200]}'}
|
||||||
|
|
||||||
# Connect to SBS port
|
# Connect to SBS port
|
||||||
result = self._start_adsb_sbs_connection('localhost', 30003, source_tag='adsb', thread_name='adsb')
|
return self._start_adsb_sbs_connection('localhost', 30003)
|
||||||
if mlat_sbs_host:
|
|
||||||
self._start_adsb_sbs_connection(mlat_sbs_host, mlat_sbs_port, source_tag='mlat', thread_name='adsb_mlat')
|
|
||||||
result['mlat_source'] = f'{mlat_sbs_host}:{mlat_sbs_port}'
|
|
||||||
return result
|
|
||||||
|
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
return {'status': 'error', 'message': 'dump1090 not found'}
|
return {'status': 'error', 'message': 'dump1090 not found'}
|
||||||
@@ -1437,15 +1412,15 @@ class ModeManager:
|
|||||||
return path
|
return path
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _start_adsb_sbs_connection(self, host: str, port: int, *, source_tag: str = 'adsb', thread_name: str = 'adsb') -> dict:
|
def _start_adsb_sbs_connection(self, host: str, port: int) -> dict:
|
||||||
"""Connect to SBS port and start parsing."""
|
"""Connect to SBS port and start parsing."""
|
||||||
thread = threading.Thread(
|
thread = threading.Thread(
|
||||||
target=self._adsb_sbs_reader,
|
target=self._adsb_sbs_reader,
|
||||||
args=(host, port, source_tag),
|
args=(host, port),
|
||||||
daemon=True
|
daemon=True
|
||||||
)
|
)
|
||||||
thread.start()
|
thread.start()
|
||||||
self.output_threads[thread_name] = thread
|
self.output_threads['adsb'] = thread
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'status': 'started',
|
'status': 'started',
|
||||||
@@ -1454,7 +1429,7 @@ class ModeManager:
|
|||||||
'gps_enabled': gps_manager.is_running
|
'gps_enabled': gps_manager.is_running
|
||||||
}
|
}
|
||||||
|
|
||||||
def _adsb_sbs_reader(self, host: str, port: int, source_tag: str = 'adsb'):
|
def _adsb_sbs_reader(self, host: str, port: int):
|
||||||
"""Read and parse SBS data from dump1090."""
|
"""Read and parse SBS data from dump1090."""
|
||||||
mode = 'adsb'
|
mode = 'adsb'
|
||||||
stop_event = self.stop_events.get(mode)
|
stop_event = self.stop_events.get(mode)
|
||||||
@@ -1466,7 +1441,7 @@ class ModeManager:
|
|||||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
sock.settimeout(5.0)
|
sock.settimeout(5.0)
|
||||||
sock.connect((host, port))
|
sock.connect((host, port))
|
||||||
logger.info(f"Connected to SBS at {host}:{port} ({source_tag})")
|
logger.info(f"Connected to SBS at {host}:{port}")
|
||||||
retry_count = 0
|
retry_count = 0
|
||||||
|
|
||||||
buffer = ""
|
buffer = ""
|
||||||
@@ -1481,7 +1456,7 @@ class ModeManager:
|
|||||||
|
|
||||||
while '\n' in buffer:
|
while '\n' in buffer:
|
||||||
line, buffer = buffer.split('\n', 1)
|
line, buffer = buffer.split('\n', 1)
|
||||||
self._parse_sbs_line(line.strip(), source_tag)
|
self._parse_sbs_line(line.strip())
|
||||||
|
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
continue
|
continue
|
||||||
@@ -1498,7 +1473,7 @@ class ModeManager:
|
|||||||
|
|
||||||
logger.info("ADS-B SBS reader stopped")
|
logger.info("ADS-B SBS reader stopped")
|
||||||
|
|
||||||
def _parse_sbs_line(self, line: str, source_tag: str = 'adsb'):
|
def _parse_sbs_line(self, line: str):
|
||||||
"""Parse SBS format line and update aircraft dict."""
|
"""Parse SBS format line and update aircraft dict."""
|
||||||
if not line:
|
if not line:
|
||||||
return
|
return
|
||||||
@@ -1532,8 +1507,6 @@ class ModeManager:
|
|||||||
if parts[14] and parts[15]:
|
if parts[14] and parts[15]:
|
||||||
aircraft['lat'] = float(parts[14])
|
aircraft['lat'] = float(parts[14])
|
||||||
aircraft['lon'] = float(parts[15])
|
aircraft['lon'] = float(parts[15])
|
||||||
if source_tag:
|
|
||||||
aircraft['position_source'] = source_tag
|
|
||||||
|
|
||||||
elif msg_type == '4' and len(parts) > 16:
|
elif msg_type == '4' and len(parts) > 16:
|
||||||
if parts[12]:
|
if parts[12]:
|
||||||
@@ -1568,7 +1541,6 @@ class ModeManager:
|
|||||||
"""Start WiFi scanning using Intercept's UnifiedWiFiScanner."""
|
"""Start WiFi scanning using Intercept's UnifiedWiFiScanner."""
|
||||||
interface = params.get('interface')
|
interface = params.get('interface')
|
||||||
channel = params.get('channel')
|
channel = params.get('channel')
|
||||||
channels = params.get('channels')
|
|
||||||
band = params.get('band', 'abg')
|
band = params.get('band', 'abg')
|
||||||
scan_type = params.get('scan_type', 'deep')
|
scan_type = params.get('scan_type', 'deep')
|
||||||
|
|
||||||
@@ -1599,21 +1571,8 @@ class ModeManager:
|
|||||||
else:
|
else:
|
||||||
scan_band = 'all'
|
scan_band = 'all'
|
||||||
|
|
||||||
channel_list = None
|
|
||||||
if channels:
|
|
||||||
if isinstance(channels, str):
|
|
||||||
channel_list = [c.strip() for c in channels.split(',') if c.strip()]
|
|
||||||
elif isinstance(channels, (list, tuple, set)):
|
|
||||||
channel_list = list(channels)
|
|
||||||
else:
|
|
||||||
channel_list = [channels]
|
|
||||||
try:
|
|
||||||
channel_list = [int(c) for c in channel_list]
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return {'status': 'error', 'message': 'Invalid channels'}
|
|
||||||
|
|
||||||
# Start deep scan
|
# Start deep scan
|
||||||
if scanner.start_deep_scan(interface=interface, band=scan_band, channel=channel, channels=channel_list):
|
if scanner.start_deep_scan(interface=interface, band=scan_band, channel=channel):
|
||||||
# Start thread to sync data to agent's dictionaries
|
# Start thread to sync data to agent's dictionaries
|
||||||
thread = threading.Thread(
|
thread = threading.Thread(
|
||||||
target=self._wifi_data_sync,
|
target=self._wifi_data_sync,
|
||||||
@@ -1634,7 +1593,7 @@ class ModeManager:
|
|||||||
|
|
||||||
except ImportError:
|
except ImportError:
|
||||||
# Fallback to direct airodump-ng
|
# Fallback to direct airodump-ng
|
||||||
return self._start_wifi_fallback(interface, channel, band, channels)
|
return self._start_wifi_fallback(interface, channel, band)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"WiFi scanner error: {e}")
|
logger.error(f"WiFi scanner error: {e}")
|
||||||
return {'status': 'error', 'message': str(e)}
|
return {'status': 'error', 'message': str(e)}
|
||||||
@@ -1671,13 +1630,7 @@ class ModeManager:
|
|||||||
if hasattr(self, '_wifi_scanner_instance') and self._wifi_scanner_instance:
|
if hasattr(self, '_wifi_scanner_instance') and self._wifi_scanner_instance:
|
||||||
self._wifi_scanner_instance.stop_deep_scan()
|
self._wifi_scanner_instance.stop_deep_scan()
|
||||||
|
|
||||||
def _start_wifi_fallback(
|
def _start_wifi_fallback(self, interface: str | None, channel: int | None, band: str) -> dict:
|
||||||
self,
|
|
||||||
interface: str | None,
|
|
||||||
channel: int | None,
|
|
||||||
band: str,
|
|
||||||
channels: list[int] | str | None = None,
|
|
||||||
) -> dict:
|
|
||||||
"""Fallback WiFi deep scan using airodump-ng directly."""
|
"""Fallback WiFi deep scan using airodump-ng directly."""
|
||||||
if not interface:
|
if not interface:
|
||||||
return {'status': 'error', 'message': 'WiFi interface required'}
|
return {'status': 'error', 'message': 'WiFi interface required'}
|
||||||
@@ -1705,22 +1658,7 @@ class ModeManager:
|
|||||||
cmd = [airodump_path, '-w', csv_path, '--output-format', output_formats, '--band', band]
|
cmd = [airodump_path, '-w', csv_path, '--output-format', output_formats, '--band', band]
|
||||||
if gps_manager.is_running:
|
if gps_manager.is_running:
|
||||||
cmd.append('--gpsd')
|
cmd.append('--gpsd')
|
||||||
channel_list = None
|
if channel:
|
||||||
if channels:
|
|
||||||
if isinstance(channels, str):
|
|
||||||
channel_list = [c.strip() for c in channels.split(',') if c.strip()]
|
|
||||||
elif isinstance(channels, (list, tuple, set)):
|
|
||||||
channel_list = list(channels)
|
|
||||||
else:
|
|
||||||
channel_list = [channels]
|
|
||||||
try:
|
|
||||||
channel_list = [int(c) for c in channel_list]
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return {'status': 'error', 'message': 'Invalid channels'}
|
|
||||||
|
|
||||||
if channel_list:
|
|
||||||
cmd.extend(['-c', ','.join(str(c) for c in channel_list)])
|
|
||||||
elif channel:
|
|
||||||
cmd.extend(['-c', str(channel)])
|
cmd.extend(['-c', str(channel)])
|
||||||
cmd.append(interface)
|
cmd.append(interface)
|
||||||
|
|
||||||
@@ -3175,10 +3113,7 @@ class ModeManager:
|
|||||||
self.tscm_anomalies = []
|
self.tscm_anomalies = []
|
||||||
if not hasattr(self, 'tscm_rf_signals'):
|
if not hasattr(self, 'tscm_rf_signals'):
|
||||||
self.tscm_rf_signals = []
|
self.tscm_rf_signals = []
|
||||||
if not hasattr(self, 'tscm_wifi_clients'):
|
|
||||||
self.tscm_wifi_clients = {}
|
|
||||||
self.tscm_anomalies.clear()
|
self.tscm_anomalies.clear()
|
||||||
self.tscm_wifi_clients.clear()
|
|
||||||
|
|
||||||
# Get params for what to scan
|
# Get params for what to scan
|
||||||
scan_wifi = params.get('wifi', True)
|
scan_wifi = params.get('wifi', True)
|
||||||
@@ -3233,7 +3168,7 @@ class ModeManager:
|
|||||||
stop_event = self.stop_events.get(mode)
|
stop_event = self.stop_events.get(mode)
|
||||||
|
|
||||||
# Import existing Intercept TSCM functions
|
# Import existing Intercept TSCM functions
|
||||||
from routes.tscm import _scan_wifi_networks, _scan_wifi_clients, _scan_bluetooth_devices, _scan_rf_signals
|
from routes.tscm import _scan_wifi_networks, _scan_bluetooth_devices, _scan_rf_signals
|
||||||
logger.info("TSCM imports successful")
|
logger.info("TSCM imports successful")
|
||||||
|
|
||||||
sweep_ranges = None
|
sweep_ranges = None
|
||||||
@@ -3268,7 +3203,6 @@ class ModeManager:
|
|||||||
|
|
||||||
# Track devices seen during this sweep (like local mode's all_wifi/all_bt dicts)
|
# Track devices seen during this sweep (like local mode's all_wifi/all_bt dicts)
|
||||||
seen_wifi = {}
|
seen_wifi = {}
|
||||||
seen_wifi_clients = {}
|
|
||||||
seen_bt = {}
|
seen_bt = {}
|
||||||
|
|
||||||
last_rf_scan = 0
|
last_rf_scan = 0
|
||||||
@@ -3329,47 +3263,6 @@ class ModeManager:
|
|||||||
enriched['recommended_action'] = profile.recommended_action
|
enriched['recommended_action'] = profile.recommended_action
|
||||||
|
|
||||||
self.wifi_networks[bssid] = enriched
|
self.wifi_networks[bssid] = enriched
|
||||||
|
|
||||||
# WiFi clients (monitor mode only)
|
|
||||||
try:
|
|
||||||
wifi_clients = _scan_wifi_clients(wifi_interface or '')
|
|
||||||
for client in wifi_clients:
|
|
||||||
mac = (client.get('mac') or '').upper()
|
|
||||||
if not mac or mac in seen_wifi_clients:
|
|
||||||
continue
|
|
||||||
seen_wifi_clients[mac] = client
|
|
||||||
|
|
||||||
rssi_val = client.get('rssi_current')
|
|
||||||
if rssi_val is None:
|
|
||||||
rssi_val = client.get('rssi_median') or client.get('rssi_ema')
|
|
||||||
|
|
||||||
client_device = {
|
|
||||||
'mac': mac,
|
|
||||||
'vendor': client.get('vendor'),
|
|
||||||
'name': client.get('vendor') or 'WiFi Client',
|
|
||||||
'rssi': rssi_val,
|
|
||||||
'associated_bssid': client.get('associated_bssid'),
|
|
||||||
'probed_ssids': client.get('probed_ssids', []),
|
|
||||||
'probe_count': client.get('probe_count', len(client.get('probed_ssids', []))),
|
|
||||||
'is_client': True,
|
|
||||||
}
|
|
||||||
|
|
||||||
if self._tscm_correlation:
|
|
||||||
profile = self._tscm_correlation.analyze_wifi_device(client_device)
|
|
||||||
client_device['classification'] = profile.risk_level.value
|
|
||||||
client_device['score'] = profile.total_score
|
|
||||||
client_device['score_modifier'] = profile.score_modifier
|
|
||||||
client_device['known_device'] = profile.known_device
|
|
||||||
client_device['known_device_name'] = profile.known_device_name
|
|
||||||
client_device['indicators'] = [
|
|
||||||
{'type': i.type.value, 'desc': i.description}
|
|
||||||
for i in profile.indicators
|
|
||||||
]
|
|
||||||
client_device['recommended_action'] = profile.recommended_action
|
|
||||||
|
|
||||||
self.tscm_wifi_clients[mac] = client_device
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"WiFi client scan error: {e}")
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug(f"WiFi scan error: {e}")
|
logger.debug(f"WiFi scan error: {e}")
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "intercept"
|
name = "intercept"
|
||||||
version = "2.15.0"
|
version = "2.14.0"
|
||||||
description = "Signal Intelligence Platform - Pager/433MHz/ADS-B/Satellite/WiFi/Bluetooth"
|
description = "Signal Intelligence Platform - Pager/433MHz/ADS-B/Satellite/WiFi/Bluetooth"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.9"
|
requires-python = ">=3.9"
|
||||||
|
|||||||
@@ -26,12 +26,9 @@ def register_blueprints(app):
|
|||||||
from .offline import offline_bp
|
from .offline import offline_bp
|
||||||
from .updater import updater_bp
|
from .updater import updater_bp
|
||||||
from .sstv import sstv_bp
|
from .sstv import sstv_bp
|
||||||
from .weather_sat import weather_sat_bp
|
|
||||||
from .sstv_general import sstv_general_bp
|
from .sstv_general import sstv_general_bp
|
||||||
from .dmr import dmr_bp
|
from .dmr import dmr_bp
|
||||||
from .websdr import websdr_bp
|
from .websdr import websdr_bp
|
||||||
from .alerts import alerts_bp
|
|
||||||
from .recordings import recordings_bp
|
|
||||||
|
|
||||||
app.register_blueprint(pager_bp)
|
app.register_blueprint(pager_bp)
|
||||||
app.register_blueprint(sensor_bp)
|
app.register_blueprint(sensor_bp)
|
||||||
@@ -57,12 +54,9 @@ def register_blueprints(app):
|
|||||||
app.register_blueprint(offline_bp) # Offline mode settings
|
app.register_blueprint(offline_bp) # Offline mode settings
|
||||||
app.register_blueprint(updater_bp) # GitHub update checking
|
app.register_blueprint(updater_bp) # GitHub update checking
|
||||||
app.register_blueprint(sstv_bp) # ISS SSTV decoder
|
app.register_blueprint(sstv_bp) # ISS SSTV decoder
|
||||||
app.register_blueprint(weather_sat_bp) # NOAA/Meteor weather satellite decoder
|
|
||||||
app.register_blueprint(sstv_general_bp) # General terrestrial SSTV
|
app.register_blueprint(sstv_general_bp) # General terrestrial SSTV
|
||||||
app.register_blueprint(dmr_bp) # DMR / P25 / Digital Voice
|
app.register_blueprint(dmr_bp) # DMR / P25 / Digital Voice
|
||||||
app.register_blueprint(websdr_bp) # HF/Shortwave WebSDR
|
app.register_blueprint(websdr_bp) # HF/Shortwave WebSDR
|
||||||
app.register_blueprint(alerts_bp) # Cross-mode alerts
|
|
||||||
app.register_blueprint(recordings_bp) # Session recordings
|
|
||||||
|
|
||||||
# Initialize TSCM state with queue and lock from app
|
# Initialize TSCM state with queue and lock from app
|
||||||
import app as app_module
|
import app as app_module
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import app as app_module
|
|||||||
from utils.logging import sensor_logger as logger
|
from utils.logging import sensor_logger as logger
|
||||||
from utils.validation import validate_device_index, validate_gain, validate_ppm
|
from utils.validation import validate_device_index, validate_gain, validate_ppm
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.constants import (
|
from utils.constants import (
|
||||||
PROCESS_TERMINATE_TIMEOUT,
|
PROCESS_TERMINATE_TIMEOUT,
|
||||||
SSE_KEEPALIVE_INTERVAL,
|
SSE_KEEPALIVE_INTERVAL,
|
||||||
@@ -394,10 +393,6 @@ def stream_acars() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = app_module.acars_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
msg = app_module.acars_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('acars', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
+25
-88
@@ -35,9 +35,6 @@ from config import (
|
|||||||
ADSB_DB_USER,
|
ADSB_DB_USER,
|
||||||
ADSB_AUTO_START,
|
ADSB_AUTO_START,
|
||||||
ADSB_HISTORY_ENABLED,
|
ADSB_HISTORY_ENABLED,
|
||||||
ADSB_MLAT_ENABLED,
|
|
||||||
ADSB_MLAT_SBS_HOST,
|
|
||||||
ADSB_MLAT_SBS_PORT,
|
|
||||||
SHARED_OBSERVER_LOCATION_ENABLED,
|
SHARED_OBSERVER_LOCATION_ENABLED,
|
||||||
)
|
)
|
||||||
from utils.logging import adsb_logger as logger
|
from utils.logging import adsb_logger as logger
|
||||||
@@ -46,7 +43,6 @@ from utils.validation import (
|
|||||||
validate_rtl_tcp_host, validate_rtl_tcp_port
|
validate_rtl_tcp_host, validate_rtl_tcp_port
|
||||||
)
|
)
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.sdr import SDRFactory, SDRType
|
from utils.sdr import SDRFactory, SDRType
|
||||||
from utils.constants import (
|
from utils.constants import (
|
||||||
ADSB_SBS_PORT,
|
ADSB_SBS_PORT,
|
||||||
@@ -74,10 +70,7 @@ adsb_last_message_time = None
|
|||||||
adsb_bytes_received = 0
|
adsb_bytes_received = 0
|
||||||
adsb_lines_received = 0
|
adsb_lines_received = 0
|
||||||
adsb_active_device = None # Track which device index is being used
|
adsb_active_device = None # Track which device index is being used
|
||||||
adsb_active_sdr_type = None
|
|
||||||
_sbs_error_logged = False # Suppress repeated connection error logs
|
_sbs_error_logged = False # Suppress repeated connection error logs
|
||||||
adsb_connected_sources: set[str] = set()
|
|
||||||
_adsb_connection_lock = threading.Lock()
|
|
||||||
|
|
||||||
# Track ICAOs already looked up in aircraft database (avoid repeated lookups)
|
# Track ICAOs already looked up in aircraft database (avoid repeated lookups)
|
||||||
_looked_up_icaos: set[str] = set()
|
_looked_up_icaos: set[str] = set()
|
||||||
@@ -324,29 +317,7 @@ def check_dump1090_service():
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _reset_adsb_state() -> None:
|
def parse_sbs_stream(service_addr):
|
||||||
global adsb_connected, adsb_messages_received, adsb_last_message_time, adsb_bytes_received, adsb_lines_received, _sbs_error_logged
|
|
||||||
adsb_connected = False
|
|
||||||
adsb_messages_received = 0
|
|
||||||
adsb_last_message_time = None
|
|
||||||
adsb_bytes_received = 0
|
|
||||||
adsb_lines_received = 0
|
|
||||||
_sbs_error_logged = False
|
|
||||||
with _adsb_connection_lock:
|
|
||||||
adsb_connected_sources.clear()
|
|
||||||
|
|
||||||
|
|
||||||
def _set_adsb_connected(source_key: str, connected: bool) -> None:
|
|
||||||
global adsb_connected
|
|
||||||
with _adsb_connection_lock:
|
|
||||||
if connected:
|
|
||||||
adsb_connected_sources.add(source_key)
|
|
||||||
else:
|
|
||||||
adsb_connected_sources.discard(source_key)
|
|
||||||
adsb_connected = bool(adsb_connected_sources)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_sbs_stream(service_addr: str, source_tag: str | None = None):
|
|
||||||
"""Parse SBS format data from dump1090 SBS port."""
|
"""Parse SBS format data from dump1090 SBS port."""
|
||||||
global adsb_using_service, adsb_connected, adsb_messages_received, adsb_last_message_time, adsb_bytes_received, adsb_lines_received, _sbs_error_logged
|
global adsb_using_service, adsb_connected, adsb_messages_received, adsb_last_message_time, adsb_bytes_received, adsb_lines_received, _sbs_error_logged
|
||||||
|
|
||||||
@@ -355,23 +326,26 @@ def parse_sbs_stream(service_addr: str, source_tag: str | None = None):
|
|||||||
|
|
||||||
host, port = service_addr.split(':')
|
host, port = service_addr.split(':')
|
||||||
port = int(port)
|
port = int(port)
|
||||||
source_label = source_tag or 'adsb'
|
|
||||||
|
|
||||||
logger.info(f"SBS stream parser started ({source_label}), connecting to {host}:{port}")
|
logger.info(f"SBS stream parser started, connecting to {host}:{port}")
|
||||||
|
adsb_connected = False
|
||||||
|
adsb_messages_received = 0
|
||||||
|
_sbs_error_logged = False
|
||||||
|
|
||||||
while adsb_using_service:
|
while adsb_using_service:
|
||||||
try:
|
try:
|
||||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
sock.settimeout(SBS_SOCKET_TIMEOUT)
|
sock.settimeout(SBS_SOCKET_TIMEOUT)
|
||||||
sock.connect((host, port))
|
sock.connect((host, port))
|
||||||
_set_adsb_connected(service_addr, True)
|
adsb_connected = True
|
||||||
_sbs_error_logged = False # Reset so we log next error
|
_sbs_error_logged = False # Reset so we log next error
|
||||||
logger.info(f"Connected to SBS stream ({source_label})")
|
logger.info("Connected to SBS stream")
|
||||||
|
|
||||||
buffer = ""
|
buffer = ""
|
||||||
last_update = time.time()
|
last_update = time.time()
|
||||||
pending_updates = set()
|
pending_updates = set()
|
||||||
local_lines_received = 0
|
adsb_bytes_received = 0
|
||||||
|
adsb_lines_received = 0
|
||||||
|
|
||||||
while adsb_using_service:
|
while adsb_using_service:
|
||||||
try:
|
try:
|
||||||
@@ -389,14 +363,13 @@ def parse_sbs_stream(service_addr: str, source_tag: str | None = None):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
adsb_lines_received += 1
|
adsb_lines_received += 1
|
||||||
local_lines_received += 1
|
|
||||||
# Log first few lines for debugging
|
# Log first few lines for debugging
|
||||||
if local_lines_received <= 3:
|
if adsb_lines_received <= 3:
|
||||||
logger.info(f"SBS line ({source_label}) {local_lines_received}: {line[:100]}")
|
logger.info(f"SBS line {adsb_lines_received}: {line[:100]}")
|
||||||
|
|
||||||
parts = line.split(',')
|
parts = line.split(',')
|
||||||
if len(parts) < 11 or parts[0] != 'MSG':
|
if len(parts) < 11 or parts[0] != 'MSG':
|
||||||
if local_lines_received <= 5:
|
if adsb_lines_received <= 5:
|
||||||
logger.debug(f"Skipping non-MSG line: {line[:50]}")
|
logger.debug(f"Skipping non-MSG line: {line[:50]}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -447,8 +420,6 @@ def parse_sbs_stream(service_addr: str, source_tag: str | None = None):
|
|||||||
try:
|
try:
|
||||||
aircraft['lat'] = float(parts[14])
|
aircraft['lat'] = float(parts[14])
|
||||||
aircraft['lon'] = float(parts[15])
|
aircraft['lon'] = float(parts[15])
|
||||||
if source_label:
|
|
||||||
aircraft['position_source'] = source_label
|
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -522,26 +493,18 @@ def parse_sbs_stream(service_addr: str, source_tag: str | None = None):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
sock.close()
|
sock.close()
|
||||||
_set_adsb_connected(service_addr, False)
|
adsb_connected = False
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
_set_adsb_connected(service_addr, False)
|
adsb_connected = False
|
||||||
if not _sbs_error_logged:
|
if not _sbs_error_logged:
|
||||||
logger.warning(f"SBS connection error: {e}, reconnecting...")
|
logger.warning(f"SBS connection error: {e}, reconnecting...")
|
||||||
_sbs_error_logged = True
|
_sbs_error_logged = True
|
||||||
time.sleep(SBS_RECONNECT_DELAY)
|
time.sleep(SBS_RECONNECT_DELAY)
|
||||||
|
|
||||||
_set_adsb_connected(service_addr, False)
|
adsb_connected = False
|
||||||
logger.info("SBS stream parser stopped")
|
logger.info("SBS stream parser stopped")
|
||||||
|
|
||||||
|
|
||||||
def _start_mlat_stream(host: str, port: int) -> str:
|
|
||||||
mlat_addr = f"{host}:{port}"
|
|
||||||
logger.info(f"Connecting to MLAT SBS at {mlat_addr}")
|
|
||||||
thread = threading.Thread(target=parse_sbs_stream, args=(mlat_addr, 'mlat'), daemon=True)
|
|
||||||
thread.start()
|
|
||||||
return mlat_addr
|
|
||||||
|
|
||||||
|
|
||||||
@adsb_bp.route('/tools')
|
@adsb_bp.route('/tools')
|
||||||
def check_adsb_tools():
|
def check_adsb_tools():
|
||||||
"""Check for ADS-B decoding tools and hardware."""
|
"""Check for ADS-B decoding tools and hardware."""
|
||||||
@@ -616,7 +579,7 @@ def adsb_session():
|
|||||||
@adsb_bp.route('/start', methods=['POST'])
|
@adsb_bp.route('/start', methods=['POST'])
|
||||||
def start_adsb():
|
def start_adsb():
|
||||||
"""Start ADS-B tracking."""
|
"""Start ADS-B tracking."""
|
||||||
global adsb_using_service, adsb_active_device, adsb_active_sdr_type
|
global adsb_using_service, adsb_active_device
|
||||||
|
|
||||||
with app_module.adsb_lock:
|
with app_module.adsb_lock:
|
||||||
if adsb_using_service:
|
if adsb_using_service:
|
||||||
@@ -637,22 +600,10 @@ def start_adsb():
|
|||||||
device = validate_device_index(data.get('device', '0'))
|
device = validate_device_index(data.get('device', '0'))
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return jsonify({'status': 'error', 'message': str(e)}), 400
|
return jsonify({'status': 'error', 'message': str(e)}), 400
|
||||||
_reset_adsb_state()
|
|
||||||
|
|
||||||
# Check for remote SBS connection (e.g., remote dump1090)
|
# Check for remote SBS connection (e.g., remote dump1090)
|
||||||
remote_sbs_host = data.get('remote_sbs_host')
|
remote_sbs_host = data.get('remote_sbs_host')
|
||||||
remote_sbs_port = data.get('remote_sbs_port', 30003)
|
remote_sbs_port = data.get('remote_sbs_port', 30003)
|
||||||
mlat_sbs_host = (data.get('mlat_sbs_host') or '').strip()
|
|
||||||
mlat_sbs_port = data.get('mlat_sbs_port', ADSB_MLAT_SBS_PORT)
|
|
||||||
if not mlat_sbs_host and ADSB_MLAT_ENABLED and ADSB_MLAT_SBS_HOST:
|
|
||||||
mlat_sbs_host = ADSB_MLAT_SBS_HOST
|
|
||||||
mlat_sbs_port = ADSB_MLAT_SBS_PORT
|
|
||||||
if mlat_sbs_host:
|
|
||||||
try:
|
|
||||||
mlat_sbs_host = validate_rtl_tcp_host(mlat_sbs_host)
|
|
||||||
mlat_sbs_port = validate_rtl_tcp_port(mlat_sbs_port)
|
|
||||||
except ValueError as e:
|
|
||||||
return jsonify({'status': 'error', 'message': str(e)}), 400
|
|
||||||
|
|
||||||
if remote_sbs_host:
|
if remote_sbs_host:
|
||||||
# Validate and connect to remote dump1090 SBS output
|
# Validate and connect to remote dump1090 SBS output
|
||||||
@@ -665,10 +616,8 @@ def start_adsb():
|
|||||||
remote_addr = f"{remote_sbs_host}:{remote_sbs_port}"
|
remote_addr = f"{remote_sbs_host}:{remote_sbs_port}"
|
||||||
logger.info(f"Connecting to remote dump1090 SBS at {remote_addr}")
|
logger.info(f"Connecting to remote dump1090 SBS at {remote_addr}")
|
||||||
adsb_using_service = True
|
adsb_using_service = True
|
||||||
thread = threading.Thread(target=parse_sbs_stream, args=(remote_addr, 'adsb'), daemon=True)
|
thread = threading.Thread(target=parse_sbs_stream, args=(remote_addr,), daemon=True)
|
||||||
thread.start()
|
thread.start()
|
||||||
if mlat_sbs_host:
|
|
||||||
_start_mlat_stream(mlat_sbs_host, mlat_sbs_port)
|
|
||||||
session = _record_session_start(
|
session = _record_session_start(
|
||||||
device_index=device,
|
device_index=device,
|
||||||
sdr_type='remote',
|
sdr_type='remote',
|
||||||
@@ -688,10 +637,8 @@ def start_adsb():
|
|||||||
if existing_service:
|
if existing_service:
|
||||||
logger.info(f"Found existing dump1090 service at {existing_service}")
|
logger.info(f"Found existing dump1090 service at {existing_service}")
|
||||||
adsb_using_service = True
|
adsb_using_service = True
|
||||||
thread = threading.Thread(target=parse_sbs_stream, args=(existing_service, 'adsb'), daemon=True)
|
thread = threading.Thread(target=parse_sbs_stream, args=(existing_service,), daemon=True)
|
||||||
thread.start()
|
thread.start()
|
||||||
if mlat_sbs_host:
|
|
||||||
_start_mlat_stream(mlat_sbs_host, mlat_sbs_port)
|
|
||||||
session = _record_session_start(
|
session = _record_session_start(
|
||||||
device_index=device,
|
device_index=device,
|
||||||
sdr_type='external',
|
sdr_type='external',
|
||||||
@@ -741,7 +688,7 @@ def start_adsb():
|
|||||||
|
|
||||||
# Check if device is available before starting local dump1090
|
# Check if device is available before starting local dump1090
|
||||||
device_int = int(device)
|
device_int = int(device)
|
||||||
error = app_module.claim_sdr_device(device_int, 'adsb', sdr_type.value)
|
error = app_module.claim_sdr_device(device_int, 'adsb')
|
||||||
if error:
|
if error:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'error',
|
'status': 'error',
|
||||||
@@ -778,7 +725,7 @@ def start_adsb():
|
|||||||
|
|
||||||
if app_module.adsb_process.poll() is not None:
|
if app_module.adsb_process.poll() is not None:
|
||||||
# Process exited - release device and get error message
|
# Process exited - release device and get error message
|
||||||
app_module.release_sdr_device(device_int, sdr_type.value)
|
app_module.release_sdr_device(device_int)
|
||||||
stderr_output = ''
|
stderr_output = ''
|
||||||
if app_module.adsb_process.stderr:
|
if app_module.adsb_process.stderr:
|
||||||
try:
|
try:
|
||||||
@@ -824,12 +771,9 @@ def start_adsb():
|
|||||||
})
|
})
|
||||||
|
|
||||||
adsb_using_service = True
|
adsb_using_service = True
|
||||||
adsb_active_device = device # Track which device index is being used
|
adsb_active_device = device # Track which device is being used
|
||||||
adsb_active_sdr_type = sdr_type.value
|
thread = threading.Thread(target=parse_sbs_stream, args=(f'localhost:{ADSB_SBS_PORT}',), daemon=True)
|
||||||
thread = threading.Thread(target=parse_sbs_stream, args=(f'localhost:{ADSB_SBS_PORT}', 'adsb'), daemon=True)
|
|
||||||
thread.start()
|
thread.start()
|
||||||
if mlat_sbs_host:
|
|
||||||
_start_mlat_stream(mlat_sbs_host, mlat_sbs_port)
|
|
||||||
|
|
||||||
session = _record_session_start(
|
session = _record_session_start(
|
||||||
device_index=device,
|
device_index=device,
|
||||||
@@ -847,14 +791,14 @@ def start_adsb():
|
|||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Release device on failure
|
# Release device on failure
|
||||||
app_module.release_sdr_device(device_int, sdr_type.value)
|
app_module.release_sdr_device(device_int)
|
||||||
return jsonify({'status': 'error', 'message': str(e)})
|
return jsonify({'status': 'error', 'message': str(e)})
|
||||||
|
|
||||||
|
|
||||||
@adsb_bp.route('/stop', methods=['POST'])
|
@adsb_bp.route('/stop', methods=['POST'])
|
||||||
def stop_adsb():
|
def stop_adsb():
|
||||||
"""Stop ADS-B tracking."""
|
"""Stop ADS-B tracking."""
|
||||||
global adsb_using_service, adsb_active_device, adsb_active_sdr_type
|
global adsb_using_service, adsb_active_device
|
||||||
data = request.json or {}
|
data = request.json or {}
|
||||||
stop_source = data.get('source')
|
stop_source = data.get('source')
|
||||||
stopped_by = request.remote_addr
|
stopped_by = request.remote_addr
|
||||||
@@ -878,12 +822,10 @@ def stop_adsb():
|
|||||||
|
|
||||||
# Release device from registry
|
# Release device from registry
|
||||||
if adsb_active_device is not None:
|
if adsb_active_device is not None:
|
||||||
app_module.release_sdr_device(adsb_active_device, adsb_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(adsb_active_device)
|
||||||
|
|
||||||
adsb_using_service = False
|
adsb_using_service = False
|
||||||
adsb_active_device = None
|
adsb_active_device = None
|
||||||
adsb_active_sdr_type = None
|
|
||||||
_reset_adsb_state()
|
|
||||||
|
|
||||||
app_module.adsb_aircraft.clear()
|
app_module.adsb_aircraft.clear()
|
||||||
_looked_up_icaos.clear()
|
_looked_up_icaos.clear()
|
||||||
@@ -901,10 +843,6 @@ def stream_adsb():
|
|||||||
try:
|
try:
|
||||||
msg = app_module.adsb_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
msg = app_module.adsb_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('adsb', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
@@ -925,7 +863,6 @@ def adsb_dashboard():
|
|||||||
'adsb_dashboard.html',
|
'adsb_dashboard.html',
|
||||||
shared_observer_location=SHARED_OBSERVER_LOCATION_ENABLED,
|
shared_observer_location=SHARED_OBSERVER_LOCATION_ENABLED,
|
||||||
adsb_auto_start=ADSB_AUTO_START,
|
adsb_auto_start=ADSB_AUTO_START,
|
||||||
adsb_mlat_enabled=ADSB_MLAT_ENABLED,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+5
-13
@@ -19,7 +19,6 @@ from config import SHARED_OBSERVER_LOCATION_ENABLED
|
|||||||
from utils.logging import get_logger
|
from utils.logging import get_logger
|
||||||
from utils.validation import validate_device_index, validate_gain
|
from utils.validation import validate_device_index, validate_gain
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.sdr import SDRFactory, SDRType
|
from utils.sdr import SDRFactory, SDRType
|
||||||
from utils.constants import (
|
from utils.constants import (
|
||||||
AIS_TCP_PORT,
|
AIS_TCP_PORT,
|
||||||
@@ -44,7 +43,6 @@ ais_connected = False
|
|||||||
ais_messages_received = 0
|
ais_messages_received = 0
|
||||||
ais_last_message_time = None
|
ais_last_message_time = None
|
||||||
ais_active_device = None
|
ais_active_device = None
|
||||||
ais_active_sdr_type = None
|
|
||||||
_ais_error_logged = True
|
_ais_error_logged = True
|
||||||
|
|
||||||
# Common installation paths for AIS-catcher
|
# Common installation paths for AIS-catcher
|
||||||
@@ -327,7 +325,7 @@ def ais_status():
|
|||||||
@ais_bp.route('/start', methods=['POST'])
|
@ais_bp.route('/start', methods=['POST'])
|
||||||
def start_ais():
|
def start_ais():
|
||||||
"""Start AIS tracking."""
|
"""Start AIS tracking."""
|
||||||
global ais_running, ais_active_device, ais_active_sdr_type
|
global ais_running, ais_active_device
|
||||||
|
|
||||||
with app_module.ais_lock:
|
with app_module.ais_lock:
|
||||||
if ais_running:
|
if ais_running:
|
||||||
@@ -374,7 +372,7 @@ def start_ais():
|
|||||||
|
|
||||||
# Check if device is available
|
# Check if device is available
|
||||||
device_int = int(device)
|
device_int = int(device)
|
||||||
error = app_module.claim_sdr_device(device_int, 'ais', sdr_type.value)
|
error = app_module.claim_sdr_device(device_int, 'ais')
|
||||||
if error:
|
if error:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'error',
|
'status': 'error',
|
||||||
@@ -413,7 +411,7 @@ def start_ais():
|
|||||||
|
|
||||||
if app_module.ais_process.poll() is not None:
|
if app_module.ais_process.poll() is not None:
|
||||||
# Release device on failure
|
# Release device on failure
|
||||||
app_module.release_sdr_device(device_int, sdr_type.value)
|
app_module.release_sdr_device(device_int)
|
||||||
stderr_output = ''
|
stderr_output = ''
|
||||||
if app_module.ais_process.stderr:
|
if app_module.ais_process.stderr:
|
||||||
try:
|
try:
|
||||||
@@ -427,7 +425,6 @@ def start_ais():
|
|||||||
|
|
||||||
ais_running = True
|
ais_running = True
|
||||||
ais_active_device = device
|
ais_active_device = device
|
||||||
ais_active_sdr_type = sdr_type.value
|
|
||||||
|
|
||||||
# Start TCP parser thread
|
# Start TCP parser thread
|
||||||
thread = threading.Thread(target=parse_ais_stream, args=(tcp_port,), daemon=True)
|
thread = threading.Thread(target=parse_ais_stream, args=(tcp_port,), daemon=True)
|
||||||
@@ -441,7 +438,7 @@ def start_ais():
|
|||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Release device on failure
|
# Release device on failure
|
||||||
app_module.release_sdr_device(device_int, sdr_type.value)
|
app_module.release_sdr_device(device_int)
|
||||||
logger.error(f"Failed to start AIS-catcher: {e}")
|
logger.error(f"Failed to start AIS-catcher: {e}")
|
||||||
return jsonify({'status': 'error', 'message': str(e)}), 500
|
return jsonify({'status': 'error', 'message': str(e)}), 500
|
||||||
|
|
||||||
@@ -468,11 +465,10 @@ def stop_ais():
|
|||||||
|
|
||||||
# Release device from registry
|
# Release device from registry
|
||||||
if ais_active_device is not None:
|
if ais_active_device is not None:
|
||||||
app_module.release_sdr_device(ais_active_device, ais_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(ais_active_device)
|
||||||
|
|
||||||
ais_running = False
|
ais_running = False
|
||||||
ais_active_device = None
|
ais_active_device = None
|
||||||
ais_active_sdr_type = None
|
|
||||||
|
|
||||||
app_module.ais_vessels.clear()
|
app_module.ais_vessels.clear()
|
||||||
return jsonify({'status': 'stopped'})
|
return jsonify({'status': 'stopped'})
|
||||||
@@ -488,10 +484,6 @@ def stream_ais():
|
|||||||
try:
|
try:
|
||||||
msg = app_module.ais_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
msg = app_module.ais_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('ais', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
@@ -1,76 +0,0 @@
|
|||||||
"""Alerting API endpoints."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import queue
|
|
||||||
import time
|
|
||||||
from typing import Generator
|
|
||||||
|
|
||||||
from flask import Blueprint, Response, jsonify, request
|
|
||||||
|
|
||||||
from utils.alerts import get_alert_manager
|
|
||||||
from utils.sse import format_sse
|
|
||||||
|
|
||||||
alerts_bp = Blueprint('alerts', __name__, url_prefix='/alerts')
|
|
||||||
|
|
||||||
|
|
||||||
@alerts_bp.route('/rules', methods=['GET'])
|
|
||||||
def list_rules():
|
|
||||||
manager = get_alert_manager()
|
|
||||||
include_disabled = request.args.get('all') in ('1', 'true', 'yes')
|
|
||||||
return jsonify({'status': 'success', 'rules': manager.list_rules(include_disabled=include_disabled)})
|
|
||||||
|
|
||||||
|
|
||||||
@alerts_bp.route('/rules', methods=['POST'])
|
|
||||||
def create_rule():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
if not isinstance(data.get('match', {}), dict):
|
|
||||||
return jsonify({'status': 'error', 'message': 'match must be a JSON object'}), 400
|
|
||||||
|
|
||||||
manager = get_alert_manager()
|
|
||||||
rule_id = manager.add_rule(data)
|
|
||||||
return jsonify({'status': 'success', 'rule_id': rule_id})
|
|
||||||
|
|
||||||
|
|
||||||
@alerts_bp.route('/rules/<int:rule_id>', methods=['PUT', 'PATCH'])
|
|
||||||
def update_rule(rule_id: int):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
manager = get_alert_manager()
|
|
||||||
ok = manager.update_rule(rule_id, data)
|
|
||||||
if not ok:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Rule not found or no changes'}), 404
|
|
||||||
return jsonify({'status': 'success'})
|
|
||||||
|
|
||||||
|
|
||||||
@alerts_bp.route('/rules/<int:rule_id>', methods=['DELETE'])
|
|
||||||
def delete_rule(rule_id: int):
|
|
||||||
manager = get_alert_manager()
|
|
||||||
ok = manager.delete_rule(rule_id)
|
|
||||||
if not ok:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Rule not found'}), 404
|
|
||||||
return jsonify({'status': 'success'})
|
|
||||||
|
|
||||||
|
|
||||||
@alerts_bp.route('/events', methods=['GET'])
|
|
||||||
def list_events():
|
|
||||||
manager = get_alert_manager()
|
|
||||||
limit = request.args.get('limit', default=100, type=int)
|
|
||||||
mode = request.args.get('mode')
|
|
||||||
severity = request.args.get('severity')
|
|
||||||
events = manager.list_events(limit=limit, mode=mode, severity=severity)
|
|
||||||
return jsonify({'status': 'success', 'events': events})
|
|
||||||
|
|
||||||
|
|
||||||
@alerts_bp.route('/stream', methods=['GET'])
|
|
||||||
def stream_alerts() -> Response:
|
|
||||||
manager = get_alert_manager()
|
|
||||||
|
|
||||||
def generate() -> Generator[str, None, None]:
|
|
||||||
for event in manager.stream_events(timeout=1.0):
|
|
||||||
yield format_sse(event)
|
|
||||||
|
|
||||||
response = Response(generate(), mimetype='text/event-stream')
|
|
||||||
response.headers['Cache-Control'] = 'no-cache'
|
|
||||||
response.headers['X-Accel-Buffering'] = 'no'
|
|
||||||
response.headers['Connection'] = 'keep-alive'
|
|
||||||
return response
|
|
||||||
@@ -22,7 +22,6 @@ import app as app_module
|
|||||||
from utils.logging import sensor_logger as logger
|
from utils.logging import sensor_logger as logger
|
||||||
from utils.validation import validate_device_index, validate_gain, validate_ppm
|
from utils.validation import validate_device_index, validate_gain, validate_ppm
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.constants import (
|
from utils.constants import (
|
||||||
PROCESS_TERMINATE_TIMEOUT,
|
PROCESS_TERMINATE_TIMEOUT,
|
||||||
SSE_KEEPALIVE_INTERVAL,
|
SSE_KEEPALIVE_INTERVAL,
|
||||||
@@ -53,7 +52,6 @@ aprs_packet_count = 0
|
|||||||
aprs_station_count = 0
|
aprs_station_count = 0
|
||||||
aprs_last_packet_time = None
|
aprs_last_packet_time = None
|
||||||
aprs_stations = {} # callsign -> station data
|
aprs_stations = {} # callsign -> station data
|
||||||
APRS_MAX_STATIONS = 500 # Limit tracked stations to prevent memory growth
|
|
||||||
|
|
||||||
# Meter rate limiting
|
# Meter rate limiting
|
||||||
_last_meter_time = 0.0
|
_last_meter_time = 0.0
|
||||||
@@ -1372,13 +1370,6 @@ def stream_aprs_output(rtl_process: subprocess.Popen, decoder_process: subproces
|
|||||||
'last_seen': packet.get('timestamp'),
|
'last_seen': packet.get('timestamp'),
|
||||||
'packet_type': packet.get('packet_type'),
|
'packet_type': packet.get('packet_type'),
|
||||||
}
|
}
|
||||||
# Evict oldest stations when limit is exceeded
|
|
||||||
if len(aprs_stations) > APRS_MAX_STATIONS:
|
|
||||||
oldest = min(
|
|
||||||
aprs_stations,
|
|
||||||
key=lambda k: aprs_stations[k].get('last_seen', ''),
|
|
||||||
)
|
|
||||||
del aprs_stations[oldest]
|
|
||||||
|
|
||||||
app_module.aprs_queue.put(packet)
|
app_module.aprs_queue.put(packet)
|
||||||
|
|
||||||
@@ -1736,10 +1727,6 @@ def stream_aprs() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = app_module.aprs_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
msg = app_module.aprs_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('aprs', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
"""WebSocket-based audio streaming for SDR."""
|
"""WebSocket-based audio streaming for SDR."""
|
||||||
|
|
||||||
import json
|
|
||||||
import shutil
|
|
||||||
import socket
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
import shutil
|
||||||
|
import json
|
||||||
from flask import Flask
|
from flask import Flask
|
||||||
|
|
||||||
# Try to import flask-sock
|
# Try to import flask-sock
|
||||||
@@ -252,19 +251,4 @@ def init_audio_websocket(app: Flask):
|
|||||||
finally:
|
finally:
|
||||||
with process_lock:
|
with process_lock:
|
||||||
kill_audio_processes()
|
kill_audio_processes()
|
||||||
# Complete WebSocket close handshake, then shut down the
|
|
||||||
# raw socket so Werkzeug cannot write its HTTP 200 response
|
|
||||||
# on top of the WebSocket stream.
|
|
||||||
try:
|
|
||||||
ws.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
ws.sock.shutdown(socket.SHUT_RDWR)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
ws.sock.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
logger.info("WebSocket audio client disconnected")
|
logger.info("WebSocket audio client disconnected")
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import app as app_module
|
|||||||
from utils.dependencies import check_tool
|
from utils.dependencies import check_tool
|
||||||
from utils.logging import bluetooth_logger as logger
|
from utils.logging import bluetooth_logger as logger
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.validation import validate_bluetooth_interface
|
from utils.validation import validate_bluetooth_interface
|
||||||
from data.oui import OUI_DATABASE, load_oui_database, get_manufacturer
|
from data.oui import OUI_DATABASE, load_oui_database, get_manufacturer
|
||||||
from data.patterns import AIRTAG_PREFIXES, TILE_PREFIXES, SAMSUNG_TRACKER
|
from data.patterns import AIRTAG_PREFIXES, TILE_PREFIXES, SAMSUNG_TRACKER
|
||||||
@@ -564,10 +563,6 @@ def stream_bt():
|
|||||||
try:
|
try:
|
||||||
msg = app_module.bt_queue.get(timeout=1)
|
msg = app_module.bt_queue.get(timeout=1)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('bluetooth', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
+3
-105
@@ -11,8 +11,6 @@ import csv
|
|||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Generator
|
from typing import Generator
|
||||||
|
|
||||||
@@ -30,18 +28,12 @@ from utils.bluetooth import (
|
|||||||
)
|
)
|
||||||
from utils.database import get_db
|
from utils.database import get_db
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
|
|
||||||
logger = logging.getLogger('intercept.bluetooth_v2')
|
logger = logging.getLogger('intercept.bluetooth_v2')
|
||||||
|
|
||||||
# Blueprint
|
# Blueprint
|
||||||
bluetooth_v2_bp = Blueprint('bluetooth_v2', __name__, url_prefix='/api/bluetooth')
|
bluetooth_v2_bp = Blueprint('bluetooth_v2', __name__, url_prefix='/api/bluetooth')
|
||||||
|
|
||||||
# Seen-before tracking
|
|
||||||
_bt_seen_cache: set[str] = set()
|
|
||||||
_bt_session_seen: set[str] = set()
|
|
||||||
_bt_seen_lock = threading.Lock()
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# DATABASE FUNCTIONS
|
# DATABASE FUNCTIONS
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -181,13 +173,6 @@ def save_observation_history(device: BTDeviceAggregate) -> None:
|
|||||||
''', (device.device_id, device.rssi_current, device.seen_count))
|
''', (device.device_id, device.rssi_current, device.seen_count))
|
||||||
|
|
||||||
|
|
||||||
def load_seen_device_ids() -> set[str]:
|
|
||||||
"""Load distinct device IDs from history for seen-before tracking."""
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute('SELECT DISTINCT device_id FROM bt_observation_history')
|
|
||||||
return {row['device_id'] for row in cursor}
|
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# API ENDPOINTS
|
# API ENDPOINTS
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -236,28 +221,6 @@ def start_scan():
|
|||||||
# Get scanner instance
|
# Get scanner instance
|
||||||
scanner = get_bluetooth_scanner(adapter_id)
|
scanner = get_bluetooth_scanner(adapter_id)
|
||||||
|
|
||||||
# Initialize database tables if needed
|
|
||||||
init_bt_tables()
|
|
||||||
|
|
||||||
def _handle_seen_before(device: BTDeviceAggregate) -> None:
|
|
||||||
try:
|
|
||||||
with _bt_seen_lock:
|
|
||||||
device.seen_before = device.device_id in _bt_seen_cache
|
|
||||||
if device.device_id not in _bt_session_seen:
|
|
||||||
save_observation_history(device)
|
|
||||||
_bt_session_seen.add(device.device_id)
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"BT seen-before update failed: {e}")
|
|
||||||
|
|
||||||
# Setup seen-before callback
|
|
||||||
if scanner._on_device_updated is None:
|
|
||||||
scanner._on_device_updated = _handle_seen_before
|
|
||||||
|
|
||||||
# Ensure cache is initialized
|
|
||||||
with _bt_seen_lock:
|
|
||||||
if not _bt_seen_cache:
|
|
||||||
_bt_seen_cache.update(load_seen_device_ids())
|
|
||||||
|
|
||||||
# Check if already scanning
|
# Check if already scanning
|
||||||
if scanner.is_scanning:
|
if scanner.is_scanning:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
@@ -265,11 +228,8 @@ def start_scan():
|
|||||||
'scan_status': scanner.get_status().to_dict()
|
'scan_status': scanner.get_status().to_dict()
|
||||||
})
|
})
|
||||||
|
|
||||||
# Refresh seen-before cache and reset session set for a new scan
|
# Initialize database tables if needed
|
||||||
with _bt_seen_lock:
|
init_bt_tables()
|
||||||
_bt_seen_cache.clear()
|
|
||||||
_bt_seen_cache.update(load_seen_device_ids())
|
|
||||||
_bt_session_seen.clear()
|
|
||||||
|
|
||||||
# Load active baseline if exists
|
# Load active baseline if exists
|
||||||
baseline_id = get_active_baseline_id()
|
baseline_id = get_active_baseline_id()
|
||||||
@@ -900,10 +860,6 @@ def stream_events():
|
|||||||
"""Generate SSE events from scanner."""
|
"""Generate SSE events from scanner."""
|
||||||
for event in scanner.stream_events(timeout=1.0):
|
for event in scanner.stream_events(timeout=1.0):
|
||||||
event_name, event_data = map_event_type(event)
|
event_name, event_data = map_event_type(event)
|
||||||
try:
|
|
||||||
process_event('bluetooth', event_data, event_name)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(event_data, event=event_name)
|
yield format_sse(event_data, event=event_name)
|
||||||
|
|
||||||
return Response(
|
return Response(
|
||||||
@@ -991,17 +947,6 @@ def get_tscm_bluetooth_snapshot(duration: int = 8) -> list[dict]:
|
|||||||
# Convert to TSCM format with tracker detection data
|
# Convert to TSCM format with tracker detection data
|
||||||
tscm_devices = []
|
tscm_devices = []
|
||||||
for device in devices:
|
for device in devices:
|
||||||
manufacturer_name = device.manufacturer_name
|
|
||||||
if (not manufacturer_name) or str(manufacturer_name).lower().startswith('unknown'):
|
|
||||||
if device.address and not device.is_randomized_mac:
|
|
||||||
try:
|
|
||||||
from data.oui import get_manufacturer
|
|
||||||
oui_vendor = get_manufacturer(device.address)
|
|
||||||
if oui_vendor and oui_vendor != 'Unknown':
|
|
||||||
manufacturer_name = oui_vendor
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
device_data = {
|
device_data = {
|
||||||
'mac': device.address,
|
'mac': device.address,
|
||||||
'address_type': device.address_type,
|
'address_type': device.address_type,
|
||||||
@@ -1011,7 +956,7 @@ def get_tscm_bluetooth_snapshot(duration: int = 8) -> list[dict]:
|
|||||||
'rssi_median': device.rssi_median,
|
'rssi_median': device.rssi_median,
|
||||||
'rssi_ema': round(device.rssi_ema, 1) if device.rssi_ema else None,
|
'rssi_ema': round(device.rssi_ema, 1) if device.rssi_ema else None,
|
||||||
'type': _classify_device_type(device),
|
'type': _classify_device_type(device),
|
||||||
'manufacturer': manufacturer_name,
|
'manufacturer': device.manufacturer_name,
|
||||||
'manufacturer_id': device.manufacturer_id,
|
'manufacturer_id': device.manufacturer_id,
|
||||||
'manufacturer_data': device.manufacturer_bytes.hex() if device.manufacturer_bytes else None,
|
'manufacturer_data': device.manufacturer_bytes.hex() if device.manufacturer_bytes else None,
|
||||||
'protocol': device.protocol,
|
'protocol': device.protocol,
|
||||||
@@ -1233,30 +1178,6 @@ def _classify_device_type(device: BTDeviceAggregate) -> str:
|
|||||||
"""Classify device type from available data."""
|
"""Classify device type from available data."""
|
||||||
name_lower = (device.name or '').lower()
|
name_lower = (device.name or '').lower()
|
||||||
manufacturer_lower = (device.manufacturer_name or '').lower()
|
manufacturer_lower = (device.manufacturer_name or '').lower()
|
||||||
service_uuids = device.service_uuids or []
|
|
||||||
|
|
||||||
if (not manufacturer_lower) or manufacturer_lower.startswith('unknown'):
|
|
||||||
if device.address and not device.is_randomized_mac:
|
|
||||||
try:
|
|
||||||
from data.oui import get_manufacturer
|
|
||||||
oui_vendor = get_manufacturer(device.address)
|
|
||||||
if oui_vendor and oui_vendor != 'Unknown':
|
|
||||||
manufacturer_lower = oui_vendor.lower()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def normalize_uuid(uuid: str) -> str:
|
|
||||||
if not uuid:
|
|
||||||
return ''
|
|
||||||
value = str(uuid).lower().strip()
|
|
||||||
if value.startswith('0x'):
|
|
||||||
value = value[2:]
|
|
||||||
# Bluetooth Base UUID normalization (16-bit UUIDs)
|
|
||||||
if value.endswith('-0000-1000-8000-00805f9b34fb') and len(value) >= 8:
|
|
||||||
return value[4:8]
|
|
||||||
if len(value) == 4:
|
|
||||||
return value
|
|
||||||
return value
|
|
||||||
|
|
||||||
# Check by name patterns
|
# Check by name patterns
|
||||||
if any(x in name_lower for x in ['airpods', 'headphone', 'earbuds', 'buds', 'beats']):
|
if any(x in name_lower for x in ['airpods', 'headphone', 'earbuds', 'buds', 'beats']):
|
||||||
@@ -1276,29 +1197,6 @@ def _classify_device_type(device: BTDeviceAggregate) -> str:
|
|||||||
if any(x in name_lower for x in ['tv', 'chromecast', 'roku', 'firestick']):
|
if any(x in name_lower for x in ['tv', 'chromecast', 'roku', 'firestick']):
|
||||||
return 'media'
|
return 'media'
|
||||||
|
|
||||||
# Tracker signals (metadata or Find My service)
|
|
||||||
if getattr(device, 'is_tracker', False) or getattr(device, 'tracker_type', None):
|
|
||||||
return 'tracker'
|
|
||||||
|
|
||||||
normalized_uuids = {normalize_uuid(u) for u in service_uuids if u}
|
|
||||||
if 'fd6f' in normalized_uuids:
|
|
||||||
return 'tracker'
|
|
||||||
|
|
||||||
# Service UUIDs (GATT / classic)
|
|
||||||
audio_uuids = {'110b', '110a', '111e', '111f', '1108', '1203'}
|
|
||||||
wearable_uuids = {'180d', '1814', '1816'}
|
|
||||||
hid_uuids = {'1812'}
|
|
||||||
beacon_uuids = {'feaa', 'feab', 'feb1', 'febe'}
|
|
||||||
|
|
||||||
if normalized_uuids & audio_uuids:
|
|
||||||
return 'audio'
|
|
||||||
if normalized_uuids & hid_uuids:
|
|
||||||
return 'peripheral'
|
|
||||||
if normalized_uuids & wearable_uuids:
|
|
||||||
return 'wearable'
|
|
||||||
if normalized_uuids & beacon_uuids:
|
|
||||||
return 'beacon'
|
|
||||||
|
|
||||||
# Check by manufacturer
|
# Check by manufacturer
|
||||||
if 'apple' in manufacturer_lower:
|
if 'apple' in manufacturer_lower:
|
||||||
return 'apple_device'
|
return 'apple_device'
|
||||||
|
|||||||
+33
-380
@@ -3,7 +3,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import json
|
|
||||||
import queue
|
import queue
|
||||||
import re
|
import re
|
||||||
import select
|
import select
|
||||||
@@ -19,9 +18,7 @@ from flask import Blueprint, jsonify, request, Response
|
|||||||
import app as app_module
|
import app as app_module
|
||||||
from utils.logging import get_logger
|
from utils.logging import get_logger
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.process import register_process, unregister_process
|
from utils.process import register_process, unregister_process
|
||||||
from utils.validation import validate_frequency, validate_gain, validate_device_index, validate_ppm
|
|
||||||
from utils.constants import (
|
from utils.constants import (
|
||||||
SSE_QUEUE_TIMEOUT,
|
SSE_QUEUE_TIMEOUT,
|
||||||
SSE_KEEPALIVE_INTERVAL,
|
SSE_KEEPALIVE_INTERVAL,
|
||||||
@@ -40,19 +37,11 @@ dmr_rtl_process: Optional[subprocess.Popen] = None
|
|||||||
dmr_dsd_process: Optional[subprocess.Popen] = None
|
dmr_dsd_process: Optional[subprocess.Popen] = None
|
||||||
dmr_thread: Optional[threading.Thread] = None
|
dmr_thread: Optional[threading.Thread] = None
|
||||||
dmr_running = False
|
dmr_running = False
|
||||||
dmr_has_audio = False # True when ffmpeg available and dsd outputs audio
|
|
||||||
dmr_lock = threading.Lock()
|
dmr_lock = threading.Lock()
|
||||||
dmr_queue: queue.Queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
|
dmr_queue: queue.Queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
|
||||||
dmr_active_device: Optional[int] = None
|
dmr_active_device: Optional[int] = None
|
||||||
|
|
||||||
# Audio mux: the sole reader of dsd-fme stdout. Writes to an ffmpeg
|
VALID_PROTOCOLS = ['auto', 'dmr', 'p25', 'nxdn', 'dstar', 'provoice']
|
||||||
# stdin when a streaming client is connected, discards otherwise.
|
|
||||||
# This prevents dsd-fme from blocking on stdout (which would also
|
|
||||||
# freeze stderr / text data output).
|
|
||||||
_active_ffmpeg_stdin: Optional[object] = None # set by stream endpoint
|
|
||||||
|
|
||||||
VALID_PROTOCOLS = ['auto', 'dmr', 'p25', 'p25p2', 'nxdn', 'dstar', 'provoice']
|
|
||||||
VALID_DEMODS = ['nfm', 'fm']
|
|
||||||
|
|
||||||
# Classic dsd flags
|
# Classic dsd flags
|
||||||
_DSD_PROTOCOL_FLAGS = {
|
_DSD_PROTOCOL_FLAGS = {
|
||||||
@@ -64,28 +53,14 @@ _DSD_PROTOCOL_FLAGS = {
|
|||||||
'provoice': ['-fv'],
|
'provoice': ['-fv'],
|
||||||
}
|
}
|
||||||
|
|
||||||
# dsd-fme remapped several flags from classic DSD:
|
# dsd-fme uses different flag names
|
||||||
# -fs = DMR Simplex (NOT -fd which is D-STAR!),
|
|
||||||
# -fd = D-STAR (NOT DMR!), -fp = ProVoice (NOT P25),
|
|
||||||
# -fi = NXDN48 (NOT D-Star), -f1 = P25 Phase 1,
|
|
||||||
# -ft = XDMA multi-protocol decoder
|
|
||||||
_DSD_FME_PROTOCOL_FLAGS = {
|
_DSD_FME_PROTOCOL_FLAGS = {
|
||||||
'auto': ['-ft'], # XDMA: auto-detect DMR/P25/YSF
|
'auto': ['-ft'],
|
||||||
'dmr': ['-fs'], # DMR Simplex (-fd is D-STAR in dsd-fme!)
|
'dmr': ['-fs'],
|
||||||
'p25': ['-f1'], # P25 Phase 1 (-fp is ProVoice in dsd-fme!)
|
'p25': ['-f1'],
|
||||||
'p25p2': ['-f2'], # P25 Phase 2
|
'nxdn': ['-fi'],
|
||||||
'nxdn': ['-fn'], # NXDN96
|
'dstar': [],
|
||||||
'dstar': ['-fd'], # D-STAR (-fd in dsd-fme, NOT DMR!)
|
'provoice': ['-fp'],
|
||||||
'provoice': ['-fp'], # ProVoice (-fp in dsd-fme, not -fv)
|
|
||||||
}
|
|
||||||
|
|
||||||
# Modulation hints: force C4FM for protocols that use it, improving
|
|
||||||
# sync reliability vs letting dsd-fme auto-detect modulation type.
|
|
||||||
_DSD_FME_MODULATION = {
|
|
||||||
'dmr': ['-mc'], # C4FM
|
|
||||||
'p25': ['-mc'], # C4FM (Phase 1)
|
|
||||||
'p25p2': ['-mq'], # CQPSK (Phase 2)
|
|
||||||
'nxdn': ['-mc'], # C4FM
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
@@ -113,83 +88,6 @@ def find_rtl_fm() -> str | None:
|
|||||||
return shutil.which('rtl_fm')
|
return shutil.which('rtl_fm')
|
||||||
|
|
||||||
|
|
||||||
def find_ffmpeg() -> str | None:
|
|
||||||
"""Find ffmpeg for audio encoding."""
|
|
||||||
return shutil.which('ffmpeg')
|
|
||||||
|
|
||||||
|
|
||||||
def _coerce_int(value) -> int | None:
|
|
||||||
try:
|
|
||||||
return int(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_dsd_json(payload: dict, ts: str) -> dict | None:
|
|
||||||
"""Parse JSON output lines from dsd-fme into events."""
|
|
||||||
event_type = str(payload.get('type') or payload.get('event') or payload.get('msg') or payload.get('kind') or '').lower()
|
|
||||||
nested = payload.get('data') if isinstance(payload.get('data'), dict) else {}
|
|
||||||
|
|
||||||
def first_of(keys):
|
|
||||||
for obj in (payload, nested):
|
|
||||||
for key in keys:
|
|
||||||
if key in obj and obj[key] is not None:
|
|
||||||
return obj[key]
|
|
||||||
return None
|
|
||||||
|
|
||||||
talkgroup = _coerce_int(first_of([
|
|
||||||
'tg', 'tgt', 'talkgroup', 'talk_group', 'tgid',
|
|
||||||
'group', 'group_id', 'groupId', 'dst', 'dest',
|
|
||||||
'destination', 'target'
|
|
||||||
]))
|
|
||||||
source = _coerce_int(first_of([
|
|
||||||
'src', 'source', 'src_id', 'source_id', 'sourceId',
|
|
||||||
'uid', 'unit', 'radio', 'rid', 'radio_id', 'radioId'
|
|
||||||
]))
|
|
||||||
slot = _coerce_int(first_of(['slot', 'timeslot', 'time_slot', 'ts']))
|
|
||||||
nac = first_of(['nac'])
|
|
||||||
protocol = first_of(['protocol', 'mode', 'system', 'sys', 'network'])
|
|
||||||
|
|
||||||
if talkgroup is not None and source is not None:
|
|
||||||
event = {
|
|
||||||
'type': 'call',
|
|
||||||
'talkgroup': talkgroup,
|
|
||||||
'source_id': source,
|
|
||||||
'timestamp': ts,
|
|
||||||
}
|
|
||||||
if slot is not None:
|
|
||||||
event['slot'] = slot
|
|
||||||
if protocol:
|
|
||||||
event['protocol'] = str(protocol)
|
|
||||||
return event
|
|
||||||
|
|
||||||
if nac is not None:
|
|
||||||
return {'type': 'nac', 'nac': str(nac), 'timestamp': ts}
|
|
||||||
|
|
||||||
if 'sync' in event_type:
|
|
||||||
return {
|
|
||||||
'type': 'sync',
|
|
||||||
'protocol': str(protocol or event_type),
|
|
||||||
'timestamp': ts,
|
|
||||||
}
|
|
||||||
|
|
||||||
voice_flag = first_of(['voice', 'voice_frame', 'voiceFrame'])
|
|
||||||
if 'voice' in event_type or voice_flag is True:
|
|
||||||
event = {
|
|
||||||
'type': 'voice',
|
|
||||||
'detail': str(first_of(['detail', 'text']) or event_type or 'voice'),
|
|
||||||
'timestamp': ts,
|
|
||||||
}
|
|
||||||
if slot is not None:
|
|
||||||
event['slot'] = slot
|
|
||||||
return event
|
|
||||||
|
|
||||||
if protocol:
|
|
||||||
return {'type': 'sync', 'protocol': str(protocol), 'timestamp': ts}
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def parse_dsd_output(line: str) -> dict | None:
|
def parse_dsd_output(line: str) -> dict | None:
|
||||||
"""Parse a line of DSD stderr output into a structured event.
|
"""Parse a line of DSD stderr output into a structured event.
|
||||||
|
|
||||||
@@ -200,56 +98,15 @@ def parse_dsd_output(line: str) -> dict | None:
|
|||||||
if not line:
|
if not line:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
ts = datetime.now().strftime('%H:%M:%S')
|
|
||||||
|
|
||||||
# Frame-level error / OK indicators (useful for quality metrics)
|
|
||||||
if re.search(r'\bDUID\s+ERR\b', line, re.IGNORECASE):
|
|
||||||
return {
|
|
||||||
'type': 'frame_error',
|
|
||||||
'kind': 'duid',
|
|
||||||
'detail': line[:200],
|
|
||||||
'timestamp': ts,
|
|
||||||
}
|
|
||||||
if re.search(r'\bR-?S\s+ERR\b', line, re.IGNORECASE):
|
|
||||||
return {
|
|
||||||
'type': 'frame_error',
|
|
||||||
'kind': 'rs',
|
|
||||||
'detail': line[:200],
|
|
||||||
'timestamp': ts,
|
|
||||||
}
|
|
||||||
if re.search(r'\bP25p2\b.*\b4V\b', line, re.IGNORECASE):
|
|
||||||
return {
|
|
||||||
'type': 'frame_ok',
|
|
||||||
'kind': 'p25p2',
|
|
||||||
'timestamp': ts,
|
|
||||||
}
|
|
||||||
|
|
||||||
# If dsd-fme is emitting JSON (via -J), parse it first.
|
|
||||||
if line.startswith('{') and line.endswith('}'):
|
|
||||||
try:
|
|
||||||
payload = json.loads(line)
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
payload = None
|
|
||||||
if isinstance(payload, dict):
|
|
||||||
parsed = _parse_dsd_json(payload, ts)
|
|
||||||
if parsed:
|
|
||||||
return parsed
|
|
||||||
return {
|
|
||||||
'type': 'raw',
|
|
||||||
'text': line[:200],
|
|
||||||
'timestamp': ts,
|
|
||||||
}
|
|
||||||
|
|
||||||
# Skip DSD/dsd-fme startup banner lines (ASCII art, version info, etc.)
|
# Skip DSD/dsd-fme startup banner lines (ASCII art, version info, etc.)
|
||||||
# Only filter lines that are purely decorative — dsd-fme uses box-drawing
|
# These contain box-drawing characters or are pure decoration.
|
||||||
# characters (│, ─) as column separators in DATA lines, so we must not
|
if re.search(r'[╔╗╚╝║═██▀▄╗╝╩╦╠╣╬│┤├┘└┐┌─┼█▓▒░]', line):
|
||||||
# discard lines that also contain alphanumeric content.
|
|
||||||
stripped_of_box = re.sub(r'[╔╗╚╝║═██▀▄╗╝╩╦╠╣╬│┤├┘└┐┌─┼█▓▒░\s]', '', line)
|
|
||||||
if not stripped_of_box:
|
|
||||||
return None
|
return None
|
||||||
if re.match(r'^\s*(Build Version|MBElib|CODEC2|Audio (Out|In)|Decoding )', line):
|
if re.match(r'^\s*(Build Version|MBElib|CODEC2|Audio (Out|In)|Decoding )', line):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
ts = datetime.now().strftime('%H:%M:%S')
|
||||||
|
|
||||||
# Sync detection: "Sync: +DMR (data)" or "Sync: +P25 Phase 1"
|
# Sync detection: "Sync: +DMR (data)" or "Sync: +P25 Phase 1"
|
||||||
sync_match = re.match(r'Sync:\s*\+?(\S+.*)', line)
|
sync_match = re.match(r'Sync:\s*\+?(\S+.*)', line)
|
||||||
if sync_match:
|
if sync_match:
|
||||||
@@ -263,9 +120,8 @@ def parse_dsd_output(line: str) -> dict | None:
|
|||||||
# is captured as a call event rather than a bare slot event.
|
# is captured as a call event rather than a bare slot event.
|
||||||
# Classic dsd: "TG: 12345 Src: 67890"
|
# Classic dsd: "TG: 12345 Src: 67890"
|
||||||
# dsd-fme: "TG: 12345, Src: 67890" or "Talkgroup: 12345, Source: 67890"
|
# dsd-fme: "TG: 12345, Src: 67890" or "Talkgroup: 12345, Source: 67890"
|
||||||
# "TGT: 12345 | SRC: 67890" (pipe-delimited variant)
|
|
||||||
tg_match = re.search(
|
tg_match = re.search(
|
||||||
r'(?:TGT?|Talkgroup)[:\s]+(\d+)[,|│\s]+(?:Src|Source|SRC)[:\s]+(\d+)', line, re.IGNORECASE
|
r'(?:TG|Talkgroup)[:\s]+(\d+)[,\s]+(?:Src|Source)[:\s]+(\d+)', line, re.IGNORECASE
|
||||||
)
|
)
|
||||||
if tg_match:
|
if tg_match:
|
||||||
result = {
|
result = {
|
||||||
@@ -324,45 +180,6 @@ def parse_dsd_output(line: str) -> dict | None:
|
|||||||
|
|
||||||
_HEARTBEAT_INTERVAL = 3.0 # seconds between heartbeats when decoder is idle
|
_HEARTBEAT_INTERVAL = 3.0 # seconds between heartbeats when decoder is idle
|
||||||
|
|
||||||
# 100ms of silence at 8kHz 16-bit mono = 1600 bytes
|
|
||||||
_SILENCE_CHUNK = b'\x00' * 1600
|
|
||||||
|
|
||||||
|
|
||||||
def _dsd_audio_mux(dsd_stdout):
|
|
||||||
"""Mux thread: sole reader of dsd-fme stdout.
|
|
||||||
|
|
||||||
Always drains dsd-fme's audio output to prevent the process from
|
|
||||||
blocking on stdout writes (which would also freeze stderr / text
|
|
||||||
data). When an audio streaming client is connected, forwards audio
|
|
||||||
to its ffmpeg stdin with silence fill during voice gaps. When no
|
|
||||||
client is connected, simply discards the data.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
while dmr_running:
|
|
||||||
ready, _, _ = select.select([dsd_stdout], [], [], 0.1)
|
|
||||||
if ready:
|
|
||||||
data = os.read(dsd_stdout.fileno(), 4096)
|
|
||||||
if not data:
|
|
||||||
break
|
|
||||||
sink = _active_ffmpeg_stdin
|
|
||||||
if sink:
|
|
||||||
try:
|
|
||||||
sink.write(data)
|
|
||||||
sink.flush()
|
|
||||||
except (BrokenPipeError, OSError, ValueError):
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
# No audio from decoder — feed silence if client connected
|
|
||||||
sink = _active_ffmpeg_stdin
|
|
||||||
if sink:
|
|
||||||
try:
|
|
||||||
sink.write(_SILENCE_CHUNK)
|
|
||||||
sink.flush()
|
|
||||||
except (BrokenPipeError, OSError, ValueError):
|
|
||||||
pass
|
|
||||||
except (OSError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def _queue_put(event: dict):
|
def _queue_put(event: dict):
|
||||||
"""Put an event on the DMR queue, dropping oldest if full."""
|
"""Put an event on the DMR queue, dropping oldest if full."""
|
||||||
@@ -410,7 +227,6 @@ def stream_dsd_output(rtl_process: subprocess.Popen, dsd_process: subprocess.Pop
|
|||||||
if not text:
|
if not text:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
logger.debug("DSD raw: %s", text)
|
|
||||||
parsed = parse_dsd_output(text)
|
parsed = parse_dsd_output(text)
|
||||||
if parsed:
|
if parsed:
|
||||||
_queue_put(parsed)
|
_queue_put(parsed)
|
||||||
@@ -444,7 +260,7 @@ def stream_dsd_output(rtl_process: subprocess.Popen, dsd_process: subprocess.Pop
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
logger.warning(f"DSD process exited with code {rc}: {detail}")
|
logger.warning(f"DSD process exited with code {rc}: {detail}")
|
||||||
# Cleanup decoder + demod processes
|
# Cleanup both processes
|
||||||
for proc in [dsd_process, rtl_process]:
|
for proc in [dsd_process, rtl_process]:
|
||||||
if proc and proc.poll() is None:
|
if proc and proc.poll() is None:
|
||||||
try:
|
try:
|
||||||
@@ -476,11 +292,9 @@ def check_tools() -> Response:
|
|||||||
"""Check for required tools."""
|
"""Check for required tools."""
|
||||||
dsd_path, _ = find_dsd()
|
dsd_path, _ = find_dsd()
|
||||||
rtl_fm = find_rtl_fm()
|
rtl_fm = find_rtl_fm()
|
||||||
ffmpeg = find_ffmpeg()
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'dsd': dsd_path is not None,
|
'dsd': dsd_path is not None,
|
||||||
'rtl_fm': rtl_fm is not None,
|
'rtl_fm': rtl_fm is not None,
|
||||||
'ffmpeg': ffmpeg is not None,
|
|
||||||
'available': dsd_path is not None and rtl_fm is not None,
|
'available': dsd_path is not None and rtl_fm is not None,
|
||||||
'protocols': VALID_PROTOCOLS,
|
'protocols': VALID_PROTOCOLS,
|
||||||
})
|
})
|
||||||
@@ -489,8 +303,7 @@ def check_tools() -> Response:
|
|||||||
@dmr_bp.route('/start', methods=['POST'])
|
@dmr_bp.route('/start', methods=['POST'])
|
||||||
def start_dmr() -> Response:
|
def start_dmr() -> Response:
|
||||||
"""Start digital voice decoding."""
|
"""Start digital voice decoding."""
|
||||||
global dmr_rtl_process, dmr_dsd_process, dmr_thread
|
global dmr_rtl_process, dmr_dsd_process, dmr_thread, dmr_running, dmr_active_device
|
||||||
global dmr_running, dmr_has_audio, dmr_active_device
|
|
||||||
|
|
||||||
with dmr_lock:
|
with dmr_lock:
|
||||||
if dmr_running:
|
if dmr_running:
|
||||||
@@ -507,24 +320,18 @@ def start_dmr() -> Response:
|
|||||||
data = request.json or {}
|
data = request.json or {}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
frequency = validate_frequency(data.get('frequency', 462.5625))
|
frequency = float(data.get('frequency', 462.5625))
|
||||||
gain = int(validate_gain(data.get('gain', 40)))
|
gain = int(data.get('gain', 40))
|
||||||
device = validate_device_index(data.get('device', 0))
|
device = int(data.get('device', 0))
|
||||||
protocol = str(data.get('protocol', 'auto')).lower()
|
protocol = str(data.get('protocol', 'auto')).lower()
|
||||||
ppm = validate_ppm(data.get('ppm', 0))
|
|
||||||
fine_tune = int(data.get('fineTune', 0) or 0)
|
|
||||||
demod = str(data.get('demod', 'nfm')).lower()
|
|
||||||
except (ValueError, TypeError) as e:
|
except (ValueError, TypeError) as e:
|
||||||
return jsonify({'status': 'error', 'message': f'Invalid parameter: {e}'}), 400
|
return jsonify({'status': 'error', 'message': f'Invalid parameter: {e}'}), 400
|
||||||
|
|
||||||
|
if frequency <= 0:
|
||||||
|
return jsonify({'status': 'error', 'message': 'Frequency must be positive'}), 400
|
||||||
|
|
||||||
if protocol not in VALID_PROTOCOLS:
|
if protocol not in VALID_PROTOCOLS:
|
||||||
return jsonify({'status': 'error', 'message': f'Invalid protocol. Use: {", ".join(VALID_PROTOCOLS)}'}), 400
|
return jsonify({'status': 'error', 'message': f'Invalid protocol. Use: {", ".join(VALID_PROTOCOLS)}'}), 400
|
||||||
if demod not in VALID_DEMODS:
|
|
||||||
return jsonify({'status': 'error', 'message': f'Invalid demod. Use: {", ".join(VALID_DEMODS)}'}), 400
|
|
||||||
if protocol == 'p25p2' and not is_fme:
|
|
||||||
return jsonify({'status': 'error', 'message': 'P25 Phase 2 requires dsd-fme.'}), 400
|
|
||||||
if abs(fine_tune) > 20000:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Fine tune offset too large (max +/- 20000 Hz).'}), 400
|
|
||||||
|
|
||||||
# Clear stale queue
|
# Clear stale queue
|
||||||
try:
|
try:
|
||||||
@@ -533,54 +340,32 @@ def start_dmr() -> Response:
|
|||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Claim SDR device — use protocol name so the device panel shows
|
# Claim SDR device
|
||||||
# "D-STAR", "P25", etc. instead of always "DMR"
|
error = app_module.claim_sdr_device(device, 'dmr')
|
||||||
mode_label = protocol.upper() if protocol != 'auto' else 'DMR'
|
|
||||||
error = app_module.claim_sdr_device(device, mode_label)
|
|
||||||
if error:
|
if error:
|
||||||
return jsonify({'status': 'error', 'error_type': 'DEVICE_BUSY', 'message': error}), 409
|
return jsonify({'status': 'error', 'error_type': 'DEVICE_BUSY', 'message': error}), 409
|
||||||
|
|
||||||
dmr_active_device = device
|
dmr_active_device = device
|
||||||
|
|
||||||
freq_hz = int((frequency * 1e6) + fine_tune)
|
freq_hz = int(frequency * 1e6)
|
||||||
|
|
||||||
# Build rtl_fm command (48kHz sample rate for DSD).
|
# Build rtl_fm command (48kHz sample rate for DSD)
|
||||||
# Squelch disabled (-l 0): rtl_fm's squelch chops the bitstream
|
|
||||||
# mid-frame, destroying DSD sync. The decoder handles silence
|
|
||||||
# internally via its own frame-sync detection.
|
|
||||||
rtl_cmd = [
|
rtl_cmd = [
|
||||||
rtl_fm_path,
|
rtl_fm_path,
|
||||||
'-M', demod,
|
'-M', 'fm',
|
||||||
'-f', str(freq_hz),
|
'-f', str(freq_hz),
|
||||||
'-s', '48000',
|
'-s', '48000',
|
||||||
'-g', str(gain),
|
'-g', str(gain),
|
||||||
'-d', str(device),
|
'-d', str(device),
|
||||||
'-l', '0',
|
'-l', '1', # squelch level
|
||||||
]
|
]
|
||||||
if ppm != 0:
|
|
||||||
rtl_cmd.extend(['-p', str(ppm)])
|
|
||||||
|
|
||||||
# Build DSD command
|
# Build DSD command
|
||||||
# Audio output: pipe decoded audio (8kHz s16le PCM) to stdout for
|
# Use -o - to send decoded audio to stdout (piped to DEVNULL)
|
||||||
# ffmpeg transcoding. Both dsd-fme and classic dsd support '-o -'.
|
# instead of PulseAudio which may not be available under sudo
|
||||||
# If ffmpeg is unavailable, fall back to discarding audio.
|
dsd_cmd = [dsd_path, '-i', '-', '-o', '-']
|
||||||
ffmpeg_path = find_ffmpeg()
|
|
||||||
if ffmpeg_path:
|
|
||||||
audio_out = '-'
|
|
||||||
else:
|
|
||||||
audio_out = 'null' if is_fme else '-'
|
|
||||||
logger.warning("ffmpeg not found — audio streaming disabled, data-only mode")
|
|
||||||
dsd_cmd = [dsd_path, '-i', '-', '-o', audio_out]
|
|
||||||
if is_fme:
|
if is_fme:
|
||||||
dsd_cmd.extend(_DSD_FME_PROTOCOL_FLAGS.get(protocol, []))
|
dsd_cmd.extend(_DSD_FME_PROTOCOL_FLAGS.get(protocol, []))
|
||||||
dsd_cmd.extend(_DSD_FME_MODULATION.get(protocol, []))
|
|
||||||
# Event log to stderr so we capture TG/Source/Voice data that
|
|
||||||
# dsd-fme may not output on stderr by default.
|
|
||||||
dsd_cmd.extend(['-J', '/dev/stderr'])
|
|
||||||
# Relax CRC checks for marginal signals — lets more frames
|
|
||||||
# through at the cost of occasional decode errors.
|
|
||||||
if data.get('relaxCrc', False):
|
|
||||||
dsd_cmd.append('-F')
|
|
||||||
else:
|
else:
|
||||||
dsd_cmd.extend(_DSD_PROTOCOL_FLAGS.get(protocol, []))
|
dsd_cmd.extend(_DSD_PROTOCOL_FLAGS.get(protocol, []))
|
||||||
|
|
||||||
@@ -592,13 +377,10 @@ def start_dmr() -> Response:
|
|||||||
)
|
)
|
||||||
register_process(dmr_rtl_process)
|
register_process(dmr_rtl_process)
|
||||||
|
|
||||||
# DSD stdout → PIPE when ffmpeg available (audio pipeline),
|
|
||||||
# otherwise DEVNULL (data-only mode)
|
|
||||||
dsd_stdout = subprocess.PIPE if ffmpeg_path else subprocess.DEVNULL
|
|
||||||
dmr_dsd_process = subprocess.Popen(
|
dmr_dsd_process = subprocess.Popen(
|
||||||
dsd_cmd,
|
dsd_cmd,
|
||||||
stdin=dmr_rtl_process.stdout,
|
stdin=dmr_rtl_process.stdout,
|
||||||
stdout=dsd_stdout,
|
stdout=subprocess.DEVNULL,
|
||||||
stderr=subprocess.PIPE,
|
stderr=subprocess.PIPE,
|
||||||
)
|
)
|
||||||
register_process(dmr_dsd_process)
|
register_process(dmr_dsd_process)
|
||||||
@@ -606,20 +388,6 @@ def start_dmr() -> Response:
|
|||||||
# Allow rtl_fm to send directly to dsd
|
# Allow rtl_fm to send directly to dsd
|
||||||
dmr_rtl_process.stdout.close()
|
dmr_rtl_process.stdout.close()
|
||||||
|
|
||||||
# Mark running before starting mux so it doesn't exit immediately.
|
|
||||||
dmr_running = True
|
|
||||||
|
|
||||||
# Start mux thread: always drains dsd-fme stdout to prevent the
|
|
||||||
# process from blocking (which would freeze stderr / text data).
|
|
||||||
# ffmpeg is started lazily per-client in /dmr/audio/stream.
|
|
||||||
if ffmpeg_path and dmr_dsd_process.stdout:
|
|
||||||
dmr_has_audio = True
|
|
||||||
threading.Thread(
|
|
||||||
target=_dsd_audio_mux,
|
|
||||||
args=(dmr_dsd_process.stdout,),
|
|
||||||
daemon=True,
|
|
||||||
).start()
|
|
||||||
|
|
||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
|
|
||||||
rtl_rc = dmr_rtl_process.poll()
|
rtl_rc = dmr_rtl_process.poll()
|
||||||
@@ -633,23 +401,6 @@ def start_dmr() -> Response:
|
|||||||
if dmr_dsd_process.stderr:
|
if dmr_dsd_process.stderr:
|
||||||
dsd_err = dmr_dsd_process.stderr.read().decode('utf-8', errors='replace')[:500]
|
dsd_err = dmr_dsd_process.stderr.read().decode('utf-8', errors='replace')[:500]
|
||||||
logger.error(f"DSD pipeline died: rtl_fm rc={rtl_rc} err={rtl_err!r}, dsd rc={dsd_rc} err={dsd_err!r}")
|
logger.error(f"DSD pipeline died: rtl_fm rc={rtl_rc} err={rtl_err!r}, dsd rc={dsd_rc} err={dsd_err!r}")
|
||||||
# Terminate surviving processes and unregister all
|
|
||||||
dmr_running = False
|
|
||||||
dmr_has_audio = False
|
|
||||||
for proc in [dmr_dsd_process, dmr_rtl_process]:
|
|
||||||
if proc and proc.poll() is None:
|
|
||||||
try:
|
|
||||||
proc.terminate()
|
|
||||||
proc.wait(timeout=2)
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
proc.kill()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if proc:
|
|
||||||
unregister_process(proc)
|
|
||||||
dmr_rtl_process = None
|
|
||||||
dmr_dsd_process = None
|
|
||||||
if dmr_active_device is not None:
|
if dmr_active_device is not None:
|
||||||
app_module.release_sdr_device(dmr_active_device)
|
app_module.release_sdr_device(dmr_active_device)
|
||||||
dmr_active_device = None
|
dmr_active_device = None
|
||||||
@@ -673,6 +424,7 @@ def start_dmr() -> Response:
|
|||||||
|
|
||||||
threading.Thread(target=_drain_rtl_stderr, args=(dmr_rtl_process,), daemon=True).start()
|
threading.Thread(target=_drain_rtl_stderr, args=(dmr_rtl_process,), daemon=True).start()
|
||||||
|
|
||||||
|
dmr_running = True
|
||||||
dmr_thread = threading.Thread(
|
dmr_thread = threading.Thread(
|
||||||
target=stream_dsd_output,
|
target=stream_dsd_output,
|
||||||
args=(dmr_rtl_process, dmr_dsd_process),
|
args=(dmr_rtl_process, dmr_dsd_process),
|
||||||
@@ -684,13 +436,10 @@ def start_dmr() -> Response:
|
|||||||
'status': 'started',
|
'status': 'started',
|
||||||
'frequency': frequency,
|
'frequency': frequency,
|
||||||
'protocol': protocol,
|
'protocol': protocol,
|
||||||
'has_audio': dmr_has_audio,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to start DMR: {e}")
|
logger.error(f"Failed to start DMR: {e}")
|
||||||
dmr_running = False
|
|
||||||
dmr_has_audio = False
|
|
||||||
if dmr_active_device is not None:
|
if dmr_active_device is not None:
|
||||||
app_module.release_sdr_device(dmr_active_device)
|
app_module.release_sdr_device(dmr_active_device)
|
||||||
dmr_active_device = None
|
dmr_active_device = None
|
||||||
@@ -700,12 +449,10 @@ def start_dmr() -> Response:
|
|||||||
@dmr_bp.route('/stop', methods=['POST'])
|
@dmr_bp.route('/stop', methods=['POST'])
|
||||||
def stop_dmr() -> Response:
|
def stop_dmr() -> Response:
|
||||||
"""Stop digital voice decoding."""
|
"""Stop digital voice decoding."""
|
||||||
global dmr_rtl_process, dmr_dsd_process
|
global dmr_rtl_process, dmr_dsd_process, dmr_running, dmr_active_device
|
||||||
global dmr_running, dmr_has_audio, dmr_active_device
|
|
||||||
|
|
||||||
with dmr_lock:
|
with dmr_lock:
|
||||||
dmr_running = False
|
dmr_running = False
|
||||||
dmr_has_audio = False
|
|
||||||
|
|
||||||
for proc in [dmr_dsd_process, dmr_rtl_process]:
|
for proc in [dmr_dsd_process, dmr_rtl_process]:
|
||||||
if proc and proc.poll() is None:
|
if proc and proc.poll() is None:
|
||||||
@@ -736,99 +483,9 @@ def dmr_status() -> Response:
|
|||||||
return jsonify({
|
return jsonify({
|
||||||
'running': dmr_running,
|
'running': dmr_running,
|
||||||
'device': dmr_active_device,
|
'device': dmr_active_device,
|
||||||
'has_audio': dmr_has_audio,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@dmr_bp.route('/audio/stream')
|
|
||||||
def stream_dmr_audio() -> Response:
|
|
||||||
"""Stream decoded digital voice audio as WAV.
|
|
||||||
|
|
||||||
Starts a per-client ffmpeg encoder. The global mux thread
|
|
||||||
(_dsd_audio_mux) forwards DSD audio to this ffmpeg's stdin while
|
|
||||||
the client is connected, and discards audio otherwise. This avoids
|
|
||||||
the pipe-buffer deadlock that occurs when ffmpeg is started at
|
|
||||||
decoder launch (its stdout fills up before any HTTP client reads
|
|
||||||
it, back-pressuring the entire pipeline and freezing stderr/text
|
|
||||||
data output).
|
|
||||||
"""
|
|
||||||
global _active_ffmpeg_stdin
|
|
||||||
|
|
||||||
if not dmr_running or not dmr_has_audio:
|
|
||||||
return Response(b'', mimetype='audio/wav', status=204)
|
|
||||||
|
|
||||||
ffmpeg_path = find_ffmpeg()
|
|
||||||
if not ffmpeg_path:
|
|
||||||
return Response(b'', mimetype='audio/wav', status=503)
|
|
||||||
|
|
||||||
encoder_cmd = [
|
|
||||||
ffmpeg_path, '-hide_banner', '-loglevel', 'error',
|
|
||||||
'-fflags', 'nobuffer', '-flags', 'low_delay',
|
|
||||||
'-probesize', '32', '-analyzeduration', '0',
|
|
||||||
'-f', 's16le', '-ar', '8000', '-ac', '1', '-i', 'pipe:0',
|
|
||||||
'-acodec', 'pcm_s16le', '-ar', '44100', '-f', 'wav', 'pipe:1',
|
|
||||||
]
|
|
||||||
audio_proc = subprocess.Popen(
|
|
||||||
encoder_cmd,
|
|
||||||
stdin=subprocess.PIPE,
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.PIPE,
|
|
||||||
)
|
|
||||||
# Drain ffmpeg stderr to prevent blocking
|
|
||||||
threading.Thread(
|
|
||||||
target=lambda p: [None for _ in p.stderr],
|
|
||||||
args=(audio_proc,), daemon=True,
|
|
||||||
).start()
|
|
||||||
|
|
||||||
# Tell the mux thread to start writing to this ffmpeg
|
|
||||||
_active_ffmpeg_stdin = audio_proc.stdin
|
|
||||||
|
|
||||||
def generate():
|
|
||||||
global _active_ffmpeg_stdin
|
|
||||||
try:
|
|
||||||
while dmr_running and audio_proc.poll() is None:
|
|
||||||
ready, _, _ = select.select([audio_proc.stdout], [], [], 2.0)
|
|
||||||
if ready:
|
|
||||||
chunk = audio_proc.stdout.read(4096)
|
|
||||||
if chunk:
|
|
||||||
yield chunk
|
|
||||||
else:
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
if audio_proc.poll() is not None:
|
|
||||||
break
|
|
||||||
except GeneratorExit:
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"DMR audio stream error: {e}")
|
|
||||||
finally:
|
|
||||||
# Disconnect mux → ffmpeg, then clean up
|
|
||||||
_active_ffmpeg_stdin = None
|
|
||||||
try:
|
|
||||||
audio_proc.stdin.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
audio_proc.terminate()
|
|
||||||
audio_proc.wait(timeout=2)
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
audio_proc.kill()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return Response(
|
|
||||||
generate(),
|
|
||||||
mimetype='audio/wav',
|
|
||||||
headers={
|
|
||||||
'Content-Type': 'audio/wav',
|
|
||||||
'Cache-Control': 'no-cache, no-store',
|
|
||||||
'X-Accel-Buffering': 'no',
|
|
||||||
'Transfer-Encoding': 'chunked',
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@dmr_bp.route('/stream')
|
@dmr_bp.route('/stream')
|
||||||
def stream_dmr() -> Response:
|
def stream_dmr() -> Response:
|
||||||
"""SSE stream for DMR decoder events."""
|
"""SSE stream for DMR decoder events."""
|
||||||
@@ -838,10 +495,6 @@ def stream_dmr() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = dmr_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
msg = dmr_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('dmr', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ from utils.database import (
|
|||||||
)
|
)
|
||||||
from utils.dsc.parser import parse_dsc_message
|
from utils.dsc.parser import parse_dsc_message
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.validation import validate_device_index, validate_gain
|
from utils.validation import validate_device_index, validate_gain
|
||||||
from utils.sdr import SDRFactory, SDRType
|
from utils.sdr import SDRFactory, SDRType
|
||||||
from utils.dependencies import get_tool_path
|
from utils.dependencies import get_tool_path
|
||||||
@@ -526,10 +525,6 @@ def stream() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = app_module.dsc_queue.get(timeout=1)
|
msg = app_module.dsc_queue.get(timeout=1)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('dsc', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
+105
-245
@@ -20,7 +20,6 @@ from flask import Blueprint, jsonify, request, Response
|
|||||||
import app as app_module
|
import app as app_module
|
||||||
from utils.logging import get_logger
|
from utils.logging import get_logger
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.constants import (
|
from utils.constants import (
|
||||||
SSE_QUEUE_TIMEOUT,
|
SSE_QUEUE_TIMEOUT,
|
||||||
SSE_KEEPALIVE_INTERVAL,
|
SSE_KEEPALIVE_INTERVAL,
|
||||||
@@ -51,9 +50,7 @@ scanner_lock = threading.Lock()
|
|||||||
scanner_paused = False
|
scanner_paused = False
|
||||||
scanner_current_freq = 0.0
|
scanner_current_freq = 0.0
|
||||||
scanner_active_device: Optional[int] = None
|
scanner_active_device: Optional[int] = None
|
||||||
scanner_active_sdr_type: Optional[str] = None
|
|
||||||
listening_active_device: Optional[int] = None
|
listening_active_device: Optional[int] = None
|
||||||
listening_active_sdr_type: Optional[str] = None
|
|
||||||
scanner_power_process: Optional[subprocess.Popen] = None
|
scanner_power_process: Optional[subprocess.Popen] = None
|
||||||
scanner_config = {
|
scanner_config = {
|
||||||
'start_freq': 88.0,
|
'start_freq': 88.0,
|
||||||
@@ -842,13 +839,9 @@ def _start_audio_stream(frequency: float, modulation: str):
|
|||||||
try:
|
try:
|
||||||
ready, _, _ = select.select([audio_process.stdout], [], [], 4.0)
|
ready, _, _ = select.select([audio_process.stdout], [], [], 4.0)
|
||||||
if not ready:
|
if not ready:
|
||||||
logger.warning("Audio pipeline produced no data in startup window — killing stalled pipeline")
|
logger.warning("Audio pipeline produced no data in startup window")
|
||||||
_stop_audio_stream_internal()
|
|
||||||
return
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Audio startup check failed: {e}")
|
logger.warning(f"Audio startup check failed: {e}")
|
||||||
_stop_audio_stream_internal()
|
|
||||||
return
|
|
||||||
|
|
||||||
audio_running = True
|
audio_running = True
|
||||||
audio_frequency = frequency
|
audio_frequency = frequency
|
||||||
@@ -873,8 +866,6 @@ def _stop_audio_stream_internal():
|
|||||||
audio_running = False
|
audio_running = False
|
||||||
audio_frequency = 0.0
|
audio_frequency = 0.0
|
||||||
|
|
||||||
had_processes = audio_process is not None or audio_rtl_process is not None
|
|
||||||
|
|
||||||
# Kill the pipeline processes and their groups
|
# Kill the pipeline processes and their groups
|
||||||
if audio_process:
|
if audio_process:
|
||||||
try:
|
try:
|
||||||
@@ -901,8 +892,7 @@ def _stop_audio_stream_internal():
|
|||||||
audio_rtl_process = None
|
audio_rtl_process = None
|
||||||
|
|
||||||
# Pause for SDR device USB interface to be released by kernel
|
# Pause for SDR device USB interface to be released by kernel
|
||||||
if had_processes:
|
time.sleep(1.0)
|
||||||
time.sleep(1.0)
|
|
||||||
|
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
@@ -939,7 +929,6 @@ def check_tools() -> Response:
|
|||||||
def start_scanner() -> Response:
|
def start_scanner() -> Response:
|
||||||
"""Start the frequency scanner."""
|
"""Start the frequency scanner."""
|
||||||
global scanner_thread, scanner_running, scanner_config, scanner_active_device, listening_active_device
|
global scanner_thread, scanner_running, scanner_config, scanner_active_device, listening_active_device
|
||||||
global scanner_active_sdr_type, listening_active_sdr_type
|
|
||||||
|
|
||||||
with scanner_lock:
|
with scanner_lock:
|
||||||
if scanner_running:
|
if scanner_running:
|
||||||
@@ -1006,11 +995,10 @@ def start_scanner() -> Response:
|
|||||||
}), 503
|
}), 503
|
||||||
# Release listening device if active
|
# Release listening device if active
|
||||||
if listening_active_device is not None:
|
if listening_active_device is not None:
|
||||||
app_module.release_sdr_device(listening_active_device, listening_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(listening_active_device)
|
||||||
listening_active_device = None
|
listening_active_device = None
|
||||||
listening_active_sdr_type = None
|
|
||||||
# Claim device for scanner
|
# Claim device for scanner
|
||||||
error = app_module.claim_sdr_device(scanner_config['device'], 'scanner', sdr_type)
|
error = app_module.claim_sdr_device(scanner_config['device'], 'scanner')
|
||||||
if error:
|
if error:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'error',
|
'status': 'error',
|
||||||
@@ -1018,7 +1006,6 @@ def start_scanner() -> Response:
|
|||||||
'message': error
|
'message': error
|
||||||
}), 409
|
}), 409
|
||||||
scanner_active_device = scanner_config['device']
|
scanner_active_device = scanner_config['device']
|
||||||
scanner_active_sdr_type = sdr_type
|
|
||||||
scanner_running = True
|
scanner_running = True
|
||||||
scanner_thread = threading.Thread(target=scanner_loop_power, daemon=True)
|
scanner_thread = threading.Thread(target=scanner_loop_power, daemon=True)
|
||||||
scanner_thread.start()
|
scanner_thread.start()
|
||||||
@@ -1036,10 +1023,9 @@ def start_scanner() -> Response:
|
|||||||
'message': f'rx_fm not found. Install SoapySDR utilities for {sdr_type}.'
|
'message': f'rx_fm not found. Install SoapySDR utilities for {sdr_type}.'
|
||||||
}), 503
|
}), 503
|
||||||
if listening_active_device is not None:
|
if listening_active_device is not None:
|
||||||
app_module.release_sdr_device(listening_active_device, listening_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(listening_active_device)
|
||||||
listening_active_device = None
|
listening_active_device = None
|
||||||
listening_active_sdr_type = None
|
error = app_module.claim_sdr_device(scanner_config['device'], 'scanner')
|
||||||
error = app_module.claim_sdr_device(scanner_config['device'], 'scanner', sdr_type)
|
|
||||||
if error:
|
if error:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'error',
|
'status': 'error',
|
||||||
@@ -1047,7 +1033,6 @@ def start_scanner() -> Response:
|
|||||||
'message': error
|
'message': error
|
||||||
}), 409
|
}), 409
|
||||||
scanner_active_device = scanner_config['device']
|
scanner_active_device = scanner_config['device']
|
||||||
scanner_active_sdr_type = sdr_type
|
|
||||||
|
|
||||||
scanner_running = True
|
scanner_running = True
|
||||||
scanner_thread = threading.Thread(target=scanner_loop, daemon=True)
|
scanner_thread = threading.Thread(target=scanner_loop, daemon=True)
|
||||||
@@ -1062,7 +1047,7 @@ def start_scanner() -> Response:
|
|||||||
@listening_post_bp.route('/scanner/stop', methods=['POST'])
|
@listening_post_bp.route('/scanner/stop', methods=['POST'])
|
||||||
def stop_scanner() -> Response:
|
def stop_scanner() -> Response:
|
||||||
"""Stop the frequency scanner."""
|
"""Stop the frequency scanner."""
|
||||||
global scanner_running, scanner_active_device, scanner_power_process, scanner_active_sdr_type
|
global scanner_running, scanner_active_device, scanner_power_process
|
||||||
|
|
||||||
scanner_running = False
|
scanner_running = False
|
||||||
_stop_audio_stream()
|
_stop_audio_stream()
|
||||||
@@ -1077,9 +1062,8 @@ def stop_scanner() -> Response:
|
|||||||
pass
|
pass
|
||||||
scanner_power_process = None
|
scanner_power_process = None
|
||||||
if scanner_active_device is not None:
|
if scanner_active_device is not None:
|
||||||
app_module.release_sdr_device(scanner_active_device, scanner_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(scanner_active_device)
|
||||||
scanner_active_device = None
|
scanner_active_device = None
|
||||||
scanner_active_sdr_type = None
|
|
||||||
|
|
||||||
return jsonify({'status': 'stopped'})
|
return jsonify({'status': 'stopped'})
|
||||||
|
|
||||||
@@ -1191,10 +1175,6 @@ def stream_scanner_events() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = scanner_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
msg = scanner_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('listening_scanner', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
@@ -1251,15 +1231,13 @@ def get_presets() -> Response:
|
|||||||
def start_audio() -> Response:
|
def start_audio() -> Response:
|
||||||
"""Start audio at specific frequency (manual mode)."""
|
"""Start audio at specific frequency (manual mode)."""
|
||||||
global scanner_running, scanner_active_device, listening_active_device, scanner_power_process, scanner_thread
|
global scanner_running, scanner_active_device, listening_active_device, scanner_power_process, scanner_thread
|
||||||
global scanner_active_sdr_type, listening_active_sdr_type, waterfall_active_sdr_type
|
|
||||||
|
|
||||||
# Stop scanner if running
|
# Stop scanner if running
|
||||||
if scanner_running:
|
if scanner_running:
|
||||||
scanner_running = False
|
scanner_running = False
|
||||||
if scanner_active_device is not None:
|
if scanner_active_device is not None:
|
||||||
app_module.release_sdr_device(scanner_active_device, scanner_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(scanner_active_device)
|
||||||
scanner_active_device = None
|
scanner_active_device = None
|
||||||
scanner_active_sdr_type = None
|
|
||||||
if scanner_thread and scanner_thread.is_alive():
|
if scanner_thread and scanner_thread.is_alive():
|
||||||
try:
|
try:
|
||||||
scanner_thread.join(timeout=2.0)
|
scanner_thread.join(timeout=2.0)
|
||||||
@@ -1315,41 +1293,11 @@ def start_audio() -> Response:
|
|||||||
scanner_config['device'] = device
|
scanner_config['device'] = device
|
||||||
scanner_config['sdr_type'] = sdr_type
|
scanner_config['sdr_type'] = sdr_type
|
||||||
|
|
||||||
# Stop waterfall if it's using the same SDR (SSE path)
|
# Claim device for listening audio
|
||||||
if waterfall_running and waterfall_active_device == device and waterfall_active_sdr_type == sdr_type:
|
|
||||||
_stop_waterfall_internal()
|
|
||||||
time.sleep(0.2)
|
|
||||||
|
|
||||||
# Claim device for listening audio. The WebSocket waterfall handler
|
|
||||||
# may still be tearing down its IQ capture process (thread join +
|
|
||||||
# safe_terminate can take several seconds), so we retry with back-off
|
|
||||||
# to give the USB device time to be fully released.
|
|
||||||
if listening_active_device is None or listening_active_device != device:
|
if listening_active_device is None or listening_active_device != device:
|
||||||
if listening_active_device is not None:
|
if listening_active_device is not None:
|
||||||
app_module.release_sdr_device(listening_active_device, listening_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(listening_active_device)
|
||||||
listening_active_device = None
|
error = app_module.claim_sdr_device(device, 'listening')
|
||||||
listening_active_sdr_type = None
|
|
||||||
|
|
||||||
error = None
|
|
||||||
max_claim_attempts = 6
|
|
||||||
for attempt in range(max_claim_attempts):
|
|
||||||
# Force-release a stale waterfall registry entry on each
|
|
||||||
# attempt — the WebSocket handler may not have finished
|
|
||||||
# cleanup yet.
|
|
||||||
device_status = app_module.get_sdr_device_status()
|
|
||||||
if device_status.get(device, {}).get(sdr_type) == 'waterfall':
|
|
||||||
app_module.release_sdr_device(device, sdr_type)
|
|
||||||
|
|
||||||
error = app_module.claim_sdr_device(device, 'listening', sdr_type)
|
|
||||||
if not error:
|
|
||||||
break
|
|
||||||
if attempt < max_claim_attempts - 1:
|
|
||||||
logger.debug(
|
|
||||||
f"Device claim attempt {attempt + 1}/{max_claim_attempts} "
|
|
||||||
f"failed, retrying in 0.5s: {error}"
|
|
||||||
)
|
|
||||||
time.sleep(0.5)
|
|
||||||
|
|
||||||
if error:
|
if error:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'error',
|
'status': 'error',
|
||||||
@@ -1357,7 +1305,6 @@ def start_audio() -> Response:
|
|||||||
'message': error
|
'message': error
|
||||||
}), 409
|
}), 409
|
||||||
listening_active_device = device
|
listening_active_device = device
|
||||||
listening_active_sdr_type = sdr_type
|
|
||||||
|
|
||||||
_start_audio_stream(frequency, modulation)
|
_start_audio_stream(frequency, modulation)
|
||||||
|
|
||||||
@@ -1377,12 +1324,11 @@ def start_audio() -> Response:
|
|||||||
@listening_post_bp.route('/audio/stop', methods=['POST'])
|
@listening_post_bp.route('/audio/stop', methods=['POST'])
|
||||||
def stop_audio() -> Response:
|
def stop_audio() -> Response:
|
||||||
"""Stop audio."""
|
"""Stop audio."""
|
||||||
global listening_active_device, listening_active_sdr_type
|
global listening_active_device
|
||||||
_stop_audio_stream()
|
_stop_audio_stream()
|
||||||
if listening_active_device is not None:
|
if listening_active_device is not None:
|
||||||
app_module.release_sdr_device(listening_active_device, listening_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(listening_active_device)
|
||||||
listening_active_device = None
|
listening_active_device = None
|
||||||
listening_active_sdr_type = None
|
|
||||||
return jsonify({'status': 'stopped'})
|
return jsonify({'status': 'stopped'})
|
||||||
|
|
||||||
|
|
||||||
@@ -1454,6 +1400,13 @@ def audio_probe() -> Response:
|
|||||||
@listening_post_bp.route('/audio/stream')
|
@listening_post_bp.route('/audio/stream')
|
||||||
def stream_audio() -> Response:
|
def stream_audio() -> Response:
|
||||||
"""Stream WAV audio."""
|
"""Stream WAV audio."""
|
||||||
|
# Optionally restart pipeline so the stream starts with a fresh header
|
||||||
|
if request.args.get('fresh') == '1' and audio_running:
|
||||||
|
try:
|
||||||
|
_start_audio_stream(audio_frequency or 0.0, audio_modulation or 'fm')
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Audio stream restart failed: {e}")
|
||||||
|
|
||||||
# Wait for audio to be ready (up to 2 seconds for modulation/squelch changes)
|
# Wait for audio to be ready (up to 2 seconds for modulation/squelch changes)
|
||||||
for _ in range(40):
|
for _ in range(40):
|
||||||
if audio_running and audio_process:
|
if audio_running and audio_process:
|
||||||
@@ -1562,58 +1515,15 @@ waterfall_running = False
|
|||||||
waterfall_lock = threading.Lock()
|
waterfall_lock = threading.Lock()
|
||||||
waterfall_queue: queue.Queue = queue.Queue(maxsize=200)
|
waterfall_queue: queue.Queue = queue.Queue(maxsize=200)
|
||||||
waterfall_active_device: Optional[int] = None
|
waterfall_active_device: Optional[int] = None
|
||||||
waterfall_active_sdr_type: Optional[str] = None
|
|
||||||
waterfall_config = {
|
waterfall_config = {
|
||||||
'start_freq': 88.0,
|
'start_freq': 88.0,
|
||||||
'end_freq': 108.0,
|
'end_freq': 108.0,
|
||||||
'bin_size': 10000,
|
'bin_size': 10000,
|
||||||
'gain': 40,
|
'gain': 40,
|
||||||
'device': 0,
|
'device': 0,
|
||||||
'max_bins': 1024,
|
|
||||||
'interval': 0.4,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _parse_rtl_power_line(line: str) -> tuple[str | None, float | None, float | None, list[float]]:
|
|
||||||
"""Parse a single rtl_power CSV line into bins."""
|
|
||||||
if not line or line.startswith('#'):
|
|
||||||
return None, None, None, []
|
|
||||||
|
|
||||||
parts = [p.strip() for p in line.split(',')]
|
|
||||||
if len(parts) < 6:
|
|
||||||
return None, None, None, []
|
|
||||||
|
|
||||||
# Timestamp in first two fields (YYYY-MM-DD, HH:MM:SS)
|
|
||||||
timestamp = f"{parts[0]} {parts[1]}" if len(parts) >= 2 else parts[0]
|
|
||||||
|
|
||||||
start_idx = None
|
|
||||||
for i, tok in enumerate(parts):
|
|
||||||
try:
|
|
||||||
val = float(tok)
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
if val > 1e5:
|
|
||||||
start_idx = i
|
|
||||||
break
|
|
||||||
if start_idx is None or len(parts) < start_idx + 4:
|
|
||||||
return timestamp, None, None, []
|
|
||||||
|
|
||||||
try:
|
|
||||||
seg_start = float(parts[start_idx])
|
|
||||||
seg_end = float(parts[start_idx + 1])
|
|
||||||
raw_values = []
|
|
||||||
for v in parts[start_idx + 3:]:
|
|
||||||
try:
|
|
||||||
raw_values.append(float(v))
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
if raw_values and raw_values[0] >= 0 and any(val < 0 for val in raw_values[1:]):
|
|
||||||
raw_values = raw_values[1:]
|
|
||||||
return timestamp, seg_start, seg_end, raw_values
|
|
||||||
except ValueError:
|
|
||||||
return timestamp, None, None, []
|
|
||||||
|
|
||||||
|
|
||||||
def _waterfall_loop():
|
def _waterfall_loop():
|
||||||
"""Continuous rtl_power sweep loop emitting waterfall data."""
|
"""Continuous rtl_power sweep loop emitting waterfall data."""
|
||||||
global waterfall_running, waterfall_process
|
global waterfall_running, waterfall_process
|
||||||
@@ -1624,59 +1534,84 @@ def _waterfall_loop():
|
|||||||
waterfall_running = False
|
waterfall_running = False
|
||||||
return
|
return
|
||||||
|
|
||||||
start_hz = int(waterfall_config['start_freq'] * 1e6)
|
|
||||||
end_hz = int(waterfall_config['end_freq'] * 1e6)
|
|
||||||
bin_hz = int(waterfall_config['bin_size'])
|
|
||||||
gain = waterfall_config['gain']
|
|
||||||
device = waterfall_config['device']
|
|
||||||
interval = float(waterfall_config.get('interval', 0.4))
|
|
||||||
|
|
||||||
cmd = [
|
|
||||||
rtl_power_path,
|
|
||||||
'-f', f'{start_hz}:{end_hz}:{bin_hz}',
|
|
||||||
'-i', str(interval),
|
|
||||||
'-g', str(gain),
|
|
||||||
'-d', str(device),
|
|
||||||
]
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
waterfall_process = subprocess.Popen(
|
while waterfall_running:
|
||||||
cmd,
|
start_hz = int(waterfall_config['start_freq'] * 1e6)
|
||||||
stdout=subprocess.PIPE,
|
end_hz = int(waterfall_config['end_freq'] * 1e6)
|
||||||
stderr=subprocess.DEVNULL,
|
bin_hz = int(waterfall_config['bin_size'])
|
||||||
bufsize=1,
|
gain = waterfall_config['gain']
|
||||||
text=True,
|
device = waterfall_config['device']
|
||||||
)
|
|
||||||
|
|
||||||
current_ts = None
|
cmd = [
|
||||||
all_bins: list[float] = []
|
rtl_power_path,
|
||||||
sweep_start_hz = start_hz
|
'-f', f'{start_hz}:{end_hz}:{bin_hz}',
|
||||||
sweep_end_hz = end_hz
|
'-i', '0.5',
|
||||||
|
'-1',
|
||||||
|
'-g', str(gain),
|
||||||
|
'-d', str(device),
|
||||||
|
]
|
||||||
|
|
||||||
if not waterfall_process.stdout:
|
try:
|
||||||
return
|
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
||||||
|
waterfall_process = proc
|
||||||
|
stdout, _ = proc.communicate(timeout=15)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
proc.kill()
|
||||||
|
stdout = b''
|
||||||
|
finally:
|
||||||
|
waterfall_process = None
|
||||||
|
|
||||||
for line in waterfall_process.stdout:
|
|
||||||
if not waterfall_running:
|
if not waterfall_running:
|
||||||
break
|
break
|
||||||
|
|
||||||
ts, seg_start, seg_end, bins = _parse_rtl_power_line(line)
|
if not stdout:
|
||||||
if ts is None or not bins:
|
time.sleep(0.2)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if current_ts is None:
|
# Parse rtl_power CSV output
|
||||||
current_ts = ts
|
all_bins = []
|
||||||
|
sweep_start_hz = start_hz
|
||||||
|
sweep_end_hz = end_hz
|
||||||
|
|
||||||
if ts != current_ts and all_bins:
|
for line in stdout.decode(errors='ignore').splitlines():
|
||||||
max_bins = int(waterfall_config.get('max_bins') or 0)
|
if not line or line.startswith('#'):
|
||||||
bins_to_send = all_bins
|
continue
|
||||||
if max_bins > 0 and len(bins_to_send) > max_bins:
|
parts = [p.strip() for p in line.split(',')]
|
||||||
bins_to_send = _downsample_bins(bins_to_send, max_bins)
|
start_idx = None
|
||||||
|
for i, tok in enumerate(parts):
|
||||||
|
try:
|
||||||
|
val = float(tok)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if val > 1e5:
|
||||||
|
start_idx = i
|
||||||
|
break
|
||||||
|
if start_idx is None or len(parts) < start_idx + 4:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
seg_start = float(parts[start_idx])
|
||||||
|
seg_end = float(parts[start_idx + 1])
|
||||||
|
seg_bin = float(parts[start_idx + 2])
|
||||||
|
raw_values = []
|
||||||
|
for v in parts[start_idx + 3:]:
|
||||||
|
try:
|
||||||
|
raw_values.append(float(v))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if raw_values and raw_values[0] >= 0 and any(val < 0 for val in raw_values[1:]):
|
||||||
|
raw_values = raw_values[1:]
|
||||||
|
all_bins.extend(raw_values)
|
||||||
|
sweep_start_hz = min(sweep_start_hz, seg_start)
|
||||||
|
sweep_end_hz = max(sweep_end_hz, seg_end)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if all_bins:
|
||||||
msg = {
|
msg = {
|
||||||
'type': 'waterfall_sweep',
|
'type': 'waterfall_sweep',
|
||||||
'start_freq': sweep_start_hz / 1e6,
|
'start_freq': sweep_start_hz / 1e6,
|
||||||
'end_freq': sweep_end_hz / 1e6,
|
'end_freq': sweep_end_hz / 1e6,
|
||||||
'bins': bins_to_send,
|
'bins': all_bins,
|
||||||
'timestamp': datetime.now().isoformat(),
|
'timestamp': datetime.now().isoformat(),
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
@@ -1691,78 +1626,19 @@ def _waterfall_loop():
|
|||||||
except queue.Full:
|
except queue.Full:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
all_bins = []
|
time.sleep(0.1)
|
||||||
sweep_start_hz = start_hz
|
|
||||||
sweep_end_hz = end_hz
|
|
||||||
current_ts = ts
|
|
||||||
|
|
||||||
all_bins.extend(bins)
|
|
||||||
if seg_start is not None:
|
|
||||||
sweep_start_hz = min(sweep_start_hz, seg_start)
|
|
||||||
if seg_end is not None:
|
|
||||||
sweep_end_hz = max(sweep_end_hz, seg_end)
|
|
||||||
|
|
||||||
# Flush any remaining bins
|
|
||||||
if all_bins and waterfall_running:
|
|
||||||
max_bins = int(waterfall_config.get('max_bins') or 0)
|
|
||||||
bins_to_send = all_bins
|
|
||||||
if max_bins > 0 and len(bins_to_send) > max_bins:
|
|
||||||
bins_to_send = _downsample_bins(bins_to_send, max_bins)
|
|
||||||
msg = {
|
|
||||||
'type': 'waterfall_sweep',
|
|
||||||
'start_freq': sweep_start_hz / 1e6,
|
|
||||||
'end_freq': sweep_end_hz / 1e6,
|
|
||||||
'bins': bins_to_send,
|
|
||||||
'timestamp': datetime.now().isoformat(),
|
|
||||||
}
|
|
||||||
try:
|
|
||||||
waterfall_queue.put_nowait(msg)
|
|
||||||
except queue.Full:
|
|
||||||
pass
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Waterfall loop error: {e}")
|
logger.error(f"Waterfall loop error: {e}")
|
||||||
finally:
|
finally:
|
||||||
waterfall_running = False
|
waterfall_running = False
|
||||||
if waterfall_process and waterfall_process.poll() is None:
|
|
||||||
try:
|
|
||||||
waterfall_process.terminate()
|
|
||||||
waterfall_process.wait(timeout=1)
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
waterfall_process.kill()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
waterfall_process = None
|
|
||||||
logger.info("Waterfall loop stopped")
|
logger.info("Waterfall loop stopped")
|
||||||
|
|
||||||
|
|
||||||
def _stop_waterfall_internal() -> None:
|
|
||||||
"""Stop the waterfall display and release resources."""
|
|
||||||
global waterfall_running, waterfall_process, waterfall_active_device, waterfall_active_sdr_type
|
|
||||||
|
|
||||||
waterfall_running = False
|
|
||||||
if waterfall_process and waterfall_process.poll() is None:
|
|
||||||
try:
|
|
||||||
waterfall_process.terminate()
|
|
||||||
waterfall_process.wait(timeout=1)
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
waterfall_process.kill()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
waterfall_process = None
|
|
||||||
|
|
||||||
if waterfall_active_device is not None:
|
|
||||||
app_module.release_sdr_device(waterfall_active_device, waterfall_active_sdr_type or 'rtlsdr')
|
|
||||||
waterfall_active_device = None
|
|
||||||
waterfall_active_sdr_type = None
|
|
||||||
|
|
||||||
|
|
||||||
@listening_post_bp.route('/waterfall/start', methods=['POST'])
|
@listening_post_bp.route('/waterfall/start', methods=['POST'])
|
||||||
def start_waterfall() -> Response:
|
def start_waterfall() -> Response:
|
||||||
"""Start the waterfall/spectrogram display."""
|
"""Start the waterfall/spectrogram display."""
|
||||||
global waterfall_thread, waterfall_running, waterfall_config, waterfall_active_device, waterfall_active_sdr_type
|
global waterfall_thread, waterfall_running, waterfall_config, waterfall_active_device
|
||||||
|
|
||||||
with waterfall_lock:
|
with waterfall_lock:
|
||||||
if waterfall_running:
|
if waterfall_running:
|
||||||
@@ -1779,16 +1655,6 @@ def start_waterfall() -> Response:
|
|||||||
waterfall_config['bin_size'] = int(data.get('bin_size', 10000))
|
waterfall_config['bin_size'] = int(data.get('bin_size', 10000))
|
||||||
waterfall_config['gain'] = int(data.get('gain', 40))
|
waterfall_config['gain'] = int(data.get('gain', 40))
|
||||||
waterfall_config['device'] = int(data.get('device', 0))
|
waterfall_config['device'] = int(data.get('device', 0))
|
||||||
if data.get('interval') is not None:
|
|
||||||
interval = float(data.get('interval', waterfall_config['interval']))
|
|
||||||
if interval < 0.1 or interval > 5:
|
|
||||||
return jsonify({'status': 'error', 'message': 'interval must be between 0.1 and 5 seconds'}), 400
|
|
||||||
waterfall_config['interval'] = interval
|
|
||||||
if data.get('max_bins') is not None:
|
|
||||||
max_bins = int(data.get('max_bins', waterfall_config['max_bins']))
|
|
||||||
if max_bins < 64 or max_bins > 4096:
|
|
||||||
return jsonify({'status': 'error', 'message': 'max_bins must be between 64 and 4096'}), 400
|
|
||||||
waterfall_config['max_bins'] = max_bins
|
|
||||||
except (ValueError, TypeError) as e:
|
except (ValueError, TypeError) as e:
|
||||||
return jsonify({'status': 'error', 'message': f'Invalid parameter: {e}'}), 400
|
return jsonify({'status': 'error', 'message': f'Invalid parameter: {e}'}), 400
|
||||||
|
|
||||||
@@ -1803,12 +1669,11 @@ def start_waterfall() -> Response:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
# Claim SDR device
|
# Claim SDR device
|
||||||
error = app_module.claim_sdr_device(waterfall_config['device'], 'waterfall', 'rtlsdr')
|
error = app_module.claim_sdr_device(waterfall_config['device'], 'waterfall')
|
||||||
if error:
|
if error:
|
||||||
return jsonify({'status': 'error', 'error_type': 'DEVICE_BUSY', 'message': error}), 409
|
return jsonify({'status': 'error', 'error_type': 'DEVICE_BUSY', 'message': error}), 409
|
||||||
|
|
||||||
waterfall_active_device = waterfall_config['device']
|
waterfall_active_device = waterfall_config['device']
|
||||||
waterfall_active_sdr_type = 'rtlsdr'
|
|
||||||
waterfall_running = True
|
waterfall_running = True
|
||||||
waterfall_thread = threading.Thread(target=_waterfall_loop, daemon=True)
|
waterfall_thread = threading.Thread(target=_waterfall_loop, daemon=True)
|
||||||
waterfall_thread.start()
|
waterfall_thread.start()
|
||||||
@@ -1819,7 +1684,23 @@ def start_waterfall() -> Response:
|
|||||||
@listening_post_bp.route('/waterfall/stop', methods=['POST'])
|
@listening_post_bp.route('/waterfall/stop', methods=['POST'])
|
||||||
def stop_waterfall() -> Response:
|
def stop_waterfall() -> Response:
|
||||||
"""Stop the waterfall display."""
|
"""Stop the waterfall display."""
|
||||||
_stop_waterfall_internal()
|
global waterfall_running, waterfall_process, waterfall_active_device
|
||||||
|
|
||||||
|
waterfall_running = False
|
||||||
|
if waterfall_process and waterfall_process.poll() is None:
|
||||||
|
try:
|
||||||
|
waterfall_process.terminate()
|
||||||
|
waterfall_process.wait(timeout=1)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
waterfall_process.kill()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
waterfall_process = None
|
||||||
|
|
||||||
|
if waterfall_active_device is not None:
|
||||||
|
app_module.release_sdr_device(waterfall_active_device)
|
||||||
|
waterfall_active_device = None
|
||||||
|
|
||||||
return jsonify({'status': 'stopped'})
|
return jsonify({'status': 'stopped'})
|
||||||
|
|
||||||
@@ -1833,10 +1714,6 @@ def stream_waterfall() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = waterfall_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
msg = waterfall_queue.get(timeout=SSE_QUEUE_TIMEOUT)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('waterfall', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
@@ -1848,20 +1725,3 @@ def stream_waterfall() -> Response:
|
|||||||
response.headers['Cache-Control'] = 'no-cache'
|
response.headers['Cache-Control'] = 'no-cache'
|
||||||
response.headers['X-Accel-Buffering'] = 'no'
|
response.headers['X-Accel-Buffering'] = 'no'
|
||||||
return response
|
return response
|
||||||
def _downsample_bins(values: list[float], target: int) -> list[float]:
|
|
||||||
"""Downsample bins to a target length using simple averaging."""
|
|
||||||
if target <= 0 or len(values) <= target:
|
|
||||||
return values
|
|
||||||
|
|
||||||
out: list[float] = []
|
|
||||||
step = len(values) / target
|
|
||||||
for i in range(target):
|
|
||||||
start = int(i * step)
|
|
||||||
end = int((i + 1) * step)
|
|
||||||
if end <= start:
|
|
||||||
end = min(start + 1, len(values))
|
|
||||||
chunk = values[start:end]
|
|
||||||
if not chunk:
|
|
||||||
continue
|
|
||||||
out.append(sum(chunk) / len(chunk))
|
|
||||||
return out
|
|
||||||
|
|||||||
@@ -44,9 +44,6 @@ ASSET_PATHS = {
|
|||||||
'static/vendor/leaflet/images/marker-shadow.png',
|
'static/vendor/leaflet/images/marker-shadow.png',
|
||||||
'static/vendor/leaflet/images/layers.png',
|
'static/vendor/leaflet/images/layers.png',
|
||||||
'static/vendor/leaflet/images/layers-2x.png'
|
'static/vendor/leaflet/images/layers-2x.png'
|
||||||
],
|
|
||||||
'leaflet_heat': [
|
|
||||||
'static/vendor/leaflet-heat/leaflet-heat.js'
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+18
-108
@@ -2,14 +2,12 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
|
||||||
import os
|
import os
|
||||||
import pathlib
|
import pathlib
|
||||||
import re
|
import re
|
||||||
import pty
|
import pty
|
||||||
import queue
|
import queue
|
||||||
import select
|
import select
|
||||||
import struct
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
@@ -25,7 +23,6 @@ from utils.validation import (
|
|||||||
validate_rtl_tcp_host, validate_rtl_tcp_port
|
validate_rtl_tcp_host, validate_rtl_tcp_port
|
||||||
)
|
)
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.process import safe_terminate, register_process, unregister_process
|
from utils.process import safe_terminate, register_process, unregister_process
|
||||||
from utils.sdr import SDRFactory, SDRType, SDRValidationError
|
from utils.sdr import SDRFactory, SDRType, SDRValidationError
|
||||||
from utils.dependencies import get_tool_path
|
from utils.dependencies import get_tool_path
|
||||||
@@ -34,7 +31,6 @@ pager_bp = Blueprint('pager', __name__)
|
|||||||
|
|
||||||
# Track which device is being used
|
# Track which device is being used
|
||||||
pager_active_device: int | None = None
|
pager_active_device: int | None = None
|
||||||
pager_active_sdr_type: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
def parse_multimon_output(line: str) -> dict[str, str] | None:
|
def parse_multimon_output(line: str) -> dict[str, str] | None:
|
||||||
@@ -109,62 +105,6 @@ def log_message(msg: dict[str, Any]) -> None:
|
|||||||
logger.error(f"Failed to log message: {e}")
|
logger.error(f"Failed to log message: {e}")
|
||||||
|
|
||||||
|
|
||||||
def audio_relay_thread(
|
|
||||||
rtl_stdout,
|
|
||||||
multimon_stdin,
|
|
||||||
output_queue: queue.Queue,
|
|
||||||
stop_event: threading.Event,
|
|
||||||
) -> None:
|
|
||||||
"""Relay audio from rtl_fm to multimon-ng while computing signal levels.
|
|
||||||
|
|
||||||
Reads raw 16-bit LE PCM from *rtl_stdout*, writes every chunk straight
|
|
||||||
through to *multimon_stdin*, and every ~100 ms pushes an RMS / peak scope
|
|
||||||
event onto *output_queue*.
|
|
||||||
"""
|
|
||||||
CHUNK = 4096 # bytes – 2048 samples at 16-bit mono
|
|
||||||
INTERVAL = 0.1 # seconds between scope updates
|
|
||||||
last_scope = time.monotonic()
|
|
||||||
|
|
||||||
try:
|
|
||||||
while not stop_event.is_set():
|
|
||||||
data = rtl_stdout.read(CHUNK)
|
|
||||||
if not data:
|
|
||||||
break
|
|
||||||
|
|
||||||
# Forward audio untouched
|
|
||||||
try:
|
|
||||||
multimon_stdin.write(data)
|
|
||||||
multimon_stdin.flush()
|
|
||||||
except (BrokenPipeError, OSError):
|
|
||||||
break
|
|
||||||
|
|
||||||
# Compute scope levels every ~100 ms
|
|
||||||
now = time.monotonic()
|
|
||||||
if now - last_scope >= INTERVAL:
|
|
||||||
last_scope = now
|
|
||||||
try:
|
|
||||||
n_samples = len(data) // 2
|
|
||||||
if n_samples == 0:
|
|
||||||
continue
|
|
||||||
samples = struct.unpack(f'<{n_samples}h', data[:n_samples * 2])
|
|
||||||
peak = max(abs(s) for s in samples)
|
|
||||||
rms = int(math.sqrt(sum(s * s for s in samples) / n_samples))
|
|
||||||
output_queue.put_nowait({
|
|
||||||
'type': 'scope',
|
|
||||||
'rms': rms,
|
|
||||||
'peak': peak,
|
|
||||||
})
|
|
||||||
except (struct.error, ValueError, queue.Full):
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"Audio relay error: {e}")
|
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
multimon_stdin.close()
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def stream_decoder(master_fd: int, process: subprocess.Popen[bytes]) -> None:
|
def stream_decoder(master_fd: int, process: subprocess.Popen[bytes]) -> None:
|
||||||
"""Stream decoder output to queue using PTY for unbuffered output."""
|
"""Stream decoder output to queue using PTY for unbuffered output."""
|
||||||
try:
|
try:
|
||||||
@@ -206,16 +146,11 @@ def stream_decoder(master_fd: int, process: subprocess.Popen[bytes]) -> None:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
app_module.output_queue.put({'type': 'error', 'text': str(e)})
|
app_module.output_queue.put({'type': 'error', 'text': str(e)})
|
||||||
finally:
|
finally:
|
||||||
global pager_active_device, pager_active_sdr_type
|
global pager_active_device
|
||||||
try:
|
try:
|
||||||
os.close(master_fd)
|
os.close(master_fd)
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
# Signal relay thread to stop
|
|
||||||
with app_module.process_lock:
|
|
||||||
stop_relay = getattr(app_module.current_process, '_stop_relay', None)
|
|
||||||
if stop_relay:
|
|
||||||
stop_relay.set()
|
|
||||||
# Cleanup companion rtl_fm process and decoder
|
# Cleanup companion rtl_fm process and decoder
|
||||||
with app_module.process_lock:
|
with app_module.process_lock:
|
||||||
rtl_proc = getattr(app_module.current_process, '_rtl_process', None)
|
rtl_proc = getattr(app_module.current_process, '_rtl_process', None)
|
||||||
@@ -235,14 +170,13 @@ def stream_decoder(master_fd: int, process: subprocess.Popen[bytes]) -> None:
|
|||||||
app_module.current_process = None
|
app_module.current_process = None
|
||||||
# Release SDR device
|
# Release SDR device
|
||||||
if pager_active_device is not None:
|
if pager_active_device is not None:
|
||||||
app_module.release_sdr_device(pager_active_device, pager_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(pager_active_device)
|
||||||
pager_active_device = None
|
pager_active_device = None
|
||||||
pager_active_sdr_type = None
|
|
||||||
|
|
||||||
|
|
||||||
@pager_bp.route('/start', methods=['POST'])
|
@pager_bp.route('/start', methods=['POST'])
|
||||||
def start_decoding() -> Response:
|
def start_decoding() -> Response:
|
||||||
global pager_active_device, pager_active_sdr_type
|
global pager_active_device
|
||||||
|
|
||||||
with app_module.process_lock:
|
with app_module.process_lock:
|
||||||
if app_module.current_process:
|
if app_module.current_process:
|
||||||
@@ -267,13 +201,6 @@ def start_decoding() -> Response:
|
|||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
return jsonify({'status': 'error', 'message': 'Invalid squelch value'}), 400
|
return jsonify({'status': 'error', 'message': 'Invalid squelch value'}), 400
|
||||||
|
|
||||||
# Get SDR type and build command via abstraction layer
|
|
||||||
sdr_type_str = data.get('sdr_type', 'rtlsdr')
|
|
||||||
try:
|
|
||||||
sdr_type = SDRType(sdr_type_str)
|
|
||||||
except ValueError:
|
|
||||||
sdr_type = SDRType.RTL_SDR
|
|
||||||
|
|
||||||
# Check for rtl_tcp (remote SDR) connection
|
# Check for rtl_tcp (remote SDR) connection
|
||||||
rtl_tcp_host = data.get('rtl_tcp_host')
|
rtl_tcp_host = data.get('rtl_tcp_host')
|
||||||
rtl_tcp_port = data.get('rtl_tcp_port', 1234)
|
rtl_tcp_port = data.get('rtl_tcp_port', 1234)
|
||||||
@@ -281,7 +208,7 @@ def start_decoding() -> Response:
|
|||||||
# Claim local device if not using remote rtl_tcp
|
# Claim local device if not using remote rtl_tcp
|
||||||
if not rtl_tcp_host:
|
if not rtl_tcp_host:
|
||||||
device_int = int(device)
|
device_int = int(device)
|
||||||
error = app_module.claim_sdr_device(device_int, 'pager', sdr_type.value)
|
error = app_module.claim_sdr_device(device_int, 'pager')
|
||||||
if error:
|
if error:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'error',
|
'status': 'error',
|
||||||
@@ -289,16 +216,14 @@ def start_decoding() -> Response:
|
|||||||
'message': error
|
'message': error
|
||||||
}), 409
|
}), 409
|
||||||
pager_active_device = device_int
|
pager_active_device = device_int
|
||||||
pager_active_sdr_type = sdr_type.value
|
|
||||||
|
|
||||||
# Validate protocols
|
# Validate protocols
|
||||||
valid_protocols = ['POCSAG512', 'POCSAG1200', 'POCSAG2400', 'FLEX']
|
valid_protocols = ['POCSAG512', 'POCSAG1200', 'POCSAG2400', 'FLEX']
|
||||||
protocols = data.get('protocols', valid_protocols)
|
protocols = data.get('protocols', valid_protocols)
|
||||||
if not isinstance(protocols, list):
|
if not isinstance(protocols, list):
|
||||||
if pager_active_device is not None:
|
if pager_active_device is not None:
|
||||||
app_module.release_sdr_device(pager_active_device, pager_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(pager_active_device)
|
||||||
pager_active_device = None
|
pager_active_device = None
|
||||||
pager_active_sdr_type = None
|
|
||||||
return jsonify({'status': 'error', 'message': 'Protocols must be a list'}), 400
|
return jsonify({'status': 'error', 'message': 'Protocols must be a list'}), 400
|
||||||
protocols = [p for p in protocols if p in valid_protocols]
|
protocols = [p for p in protocols if p in valid_protocols]
|
||||||
if not protocols:
|
if not protocols:
|
||||||
@@ -323,6 +248,13 @@ def start_decoding() -> Response:
|
|||||||
elif proto == 'FLEX':
|
elif proto == 'FLEX':
|
||||||
decoders.extend(['-a', 'FLEX'])
|
decoders.extend(['-a', 'FLEX'])
|
||||||
|
|
||||||
|
# Get SDR type and build command via abstraction layer
|
||||||
|
sdr_type_str = data.get('sdr_type', 'rtlsdr')
|
||||||
|
try:
|
||||||
|
sdr_type = SDRType(sdr_type_str)
|
||||||
|
except ValueError:
|
||||||
|
sdr_type = SDRType.RTL_SDR
|
||||||
|
|
||||||
if rtl_tcp_host:
|
if rtl_tcp_host:
|
||||||
# Validate and create network device
|
# Validate and create network device
|
||||||
try:
|
try:
|
||||||
@@ -386,7 +318,7 @@ def start_decoding() -> Response:
|
|||||||
|
|
||||||
multimon_process = subprocess.Popen(
|
multimon_process = subprocess.Popen(
|
||||||
multimon_cmd,
|
multimon_cmd,
|
||||||
stdin=subprocess.PIPE,
|
stdin=rtl_process.stdout,
|
||||||
stdout=slave_fd,
|
stdout=slave_fd,
|
||||||
stderr=slave_fd,
|
stderr=slave_fd,
|
||||||
close_fds=True
|
close_fds=True
|
||||||
@@ -394,22 +326,11 @@ def start_decoding() -> Response:
|
|||||||
register_process(multimon_process)
|
register_process(multimon_process)
|
||||||
|
|
||||||
os.close(slave_fd)
|
os.close(slave_fd)
|
||||||
|
rtl_process.stdout.close()
|
||||||
# Spawn audio relay thread between rtl_fm and multimon-ng
|
|
||||||
stop_relay = threading.Event()
|
|
||||||
relay = threading.Thread(
|
|
||||||
target=audio_relay_thread,
|
|
||||||
args=(rtl_process.stdout, multimon_process.stdin,
|
|
||||||
app_module.output_queue, stop_relay),
|
|
||||||
)
|
|
||||||
relay.daemon = True
|
|
||||||
relay.start()
|
|
||||||
|
|
||||||
app_module.current_process = multimon_process
|
app_module.current_process = multimon_process
|
||||||
app_module.current_process._rtl_process = rtl_process
|
app_module.current_process._rtl_process = rtl_process
|
||||||
app_module.current_process._master_fd = master_fd
|
app_module.current_process._master_fd = master_fd
|
||||||
app_module.current_process._stop_relay = stop_relay
|
|
||||||
app_module.current_process._relay_thread = relay
|
|
||||||
|
|
||||||
# Start output thread with PTY master fd
|
# Start output thread with PTY master fd
|
||||||
thread = threading.Thread(target=stream_decoder, args=(master_fd, multimon_process))
|
thread = threading.Thread(target=stream_decoder, args=(master_fd, multimon_process))
|
||||||
@@ -432,9 +353,8 @@ def start_decoding() -> Response:
|
|||||||
pass
|
pass
|
||||||
# Release device on failure
|
# Release device on failure
|
||||||
if pager_active_device is not None:
|
if pager_active_device is not None:
|
||||||
app_module.release_sdr_device(pager_active_device, pager_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(pager_active_device)
|
||||||
pager_active_device = None
|
pager_active_device = None
|
||||||
pager_active_sdr_type = None
|
|
||||||
return jsonify({'status': 'error', 'message': f'Tool not found: {e.filename}'})
|
return jsonify({'status': 'error', 'message': f'Tool not found: {e.filename}'})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Kill orphaned rtl_fm process if it was started
|
# Kill orphaned rtl_fm process if it was started
|
||||||
@@ -448,22 +368,17 @@ def start_decoding() -> Response:
|
|||||||
pass
|
pass
|
||||||
# Release device on failure
|
# Release device on failure
|
||||||
if pager_active_device is not None:
|
if pager_active_device is not None:
|
||||||
app_module.release_sdr_device(pager_active_device, pager_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(pager_active_device)
|
||||||
pager_active_device = None
|
pager_active_device = None
|
||||||
pager_active_sdr_type = None
|
|
||||||
return jsonify({'status': 'error', 'message': str(e)})
|
return jsonify({'status': 'error', 'message': str(e)})
|
||||||
|
|
||||||
|
|
||||||
@pager_bp.route('/stop', methods=['POST'])
|
@pager_bp.route('/stop', methods=['POST'])
|
||||||
def stop_decoding() -> Response:
|
def stop_decoding() -> Response:
|
||||||
global pager_active_device, pager_active_sdr_type
|
global pager_active_device
|
||||||
|
|
||||||
with app_module.process_lock:
|
with app_module.process_lock:
|
||||||
if app_module.current_process:
|
if app_module.current_process:
|
||||||
# Signal audio relay thread to stop
|
|
||||||
if hasattr(app_module.current_process, '_stop_relay'):
|
|
||||||
app_module.current_process._stop_relay.set()
|
|
||||||
|
|
||||||
# Kill rtl_fm process first
|
# Kill rtl_fm process first
|
||||||
if hasattr(app_module.current_process, '_rtl_process'):
|
if hasattr(app_module.current_process, '_rtl_process'):
|
||||||
try:
|
try:
|
||||||
@@ -493,9 +408,8 @@ def stop_decoding() -> Response:
|
|||||||
|
|
||||||
# Release device from registry
|
# Release device from registry
|
||||||
if pager_active_device is not None:
|
if pager_active_device is not None:
|
||||||
app_module.release_sdr_device(pager_active_device, pager_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(pager_active_device)
|
||||||
pager_active_device = None
|
pager_active_device = None
|
||||||
pager_active_sdr_type = None
|
|
||||||
|
|
||||||
return jsonify({'status': 'stopped'})
|
return jsonify({'status': 'stopped'})
|
||||||
|
|
||||||
@@ -557,10 +471,6 @@ def stream() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = app_module.output_queue.get(timeout=1)
|
msg = app_module.output_queue.get(timeout=1)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('pager', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
@@ -1,109 +0,0 @@
|
|||||||
"""Session recording API endpoints."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request, send_file
|
|
||||||
|
|
||||||
from utils.recording import get_recording_manager, RECORDING_ROOT
|
|
||||||
|
|
||||||
recordings_bp = Blueprint('recordings', __name__, url_prefix='/recordings')
|
|
||||||
|
|
||||||
|
|
||||||
@recordings_bp.route('/start', methods=['POST'])
|
|
||||||
def start_recording():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
mode = (data.get('mode') or '').strip()
|
|
||||||
if not mode:
|
|
||||||
return jsonify({'status': 'error', 'message': 'mode is required'}), 400
|
|
||||||
|
|
||||||
label = data.get('label')
|
|
||||||
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
|
|
||||||
|
|
||||||
manager = get_recording_manager()
|
|
||||||
session = manager.start_recording(mode=mode, label=label, metadata=metadata)
|
|
||||||
|
|
||||||
return jsonify({
|
|
||||||
'status': 'success',
|
|
||||||
'session': {
|
|
||||||
'id': session.id,
|
|
||||||
'mode': session.mode,
|
|
||||||
'label': session.label,
|
|
||||||
'started_at': session.started_at.isoformat(),
|
|
||||||
'file_path': str(session.file_path),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@recordings_bp.route('/stop', methods=['POST'])
|
|
||||||
def stop_recording():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
mode = data.get('mode')
|
|
||||||
session_id = data.get('id')
|
|
||||||
|
|
||||||
manager = get_recording_manager()
|
|
||||||
session = manager.stop_recording(mode=mode, session_id=session_id)
|
|
||||||
if not session:
|
|
||||||
return jsonify({'status': 'error', 'message': 'No active recording found'}), 404
|
|
||||||
|
|
||||||
return jsonify({
|
|
||||||
'status': 'success',
|
|
||||||
'session': {
|
|
||||||
'id': session.id,
|
|
||||||
'mode': session.mode,
|
|
||||||
'label': session.label,
|
|
||||||
'started_at': session.started_at.isoformat(),
|
|
||||||
'stopped_at': session.stopped_at.isoformat() if session.stopped_at else None,
|
|
||||||
'event_count': session.event_count,
|
|
||||||
'size_bytes': session.size_bytes,
|
|
||||||
'file_path': str(session.file_path),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@recordings_bp.route('', methods=['GET'])
|
|
||||||
def list_recordings():
|
|
||||||
manager = get_recording_manager()
|
|
||||||
limit = request.args.get('limit', default=50, type=int)
|
|
||||||
return jsonify({
|
|
||||||
'status': 'success',
|
|
||||||
'recordings': manager.list_recordings(limit=limit),
|
|
||||||
'active': manager.get_active(),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@recordings_bp.route('/<session_id>', methods=['GET'])
|
|
||||||
def get_recording(session_id: str):
|
|
||||||
manager = get_recording_manager()
|
|
||||||
rec = manager.get_recording(session_id)
|
|
||||||
if not rec:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Recording not found'}), 404
|
|
||||||
return jsonify({'status': 'success', 'recording': rec})
|
|
||||||
|
|
||||||
|
|
||||||
@recordings_bp.route('/<session_id>/download', methods=['GET'])
|
|
||||||
def download_recording(session_id: str):
|
|
||||||
manager = get_recording_manager()
|
|
||||||
rec = manager.get_recording(session_id)
|
|
||||||
if not rec:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Recording not found'}), 404
|
|
||||||
|
|
||||||
file_path = Path(rec['file_path'])
|
|
||||||
try:
|
|
||||||
resolved_root = RECORDING_ROOT.resolve()
|
|
||||||
resolved_file = file_path.resolve()
|
|
||||||
if resolved_root not in resolved_file.parents:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Invalid recording path'}), 400
|
|
||||||
except Exception:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Invalid recording path'}), 400
|
|
||||||
|
|
||||||
if not file_path.exists():
|
|
||||||
return jsonify({'status': 'error', 'message': 'Recording file missing'}), 404
|
|
||||||
|
|
||||||
return send_file(
|
|
||||||
file_path,
|
|
||||||
mimetype='application/x-ndjson',
|
|
||||||
as_attachment=True,
|
|
||||||
download_name=file_path.name,
|
|
||||||
)
|
|
||||||
@@ -18,7 +18,6 @@ from utils.validation import (
|
|||||||
validate_frequency, validate_device_index, validate_gain, validate_ppm
|
validate_frequency, validate_device_index, validate_gain, validate_ppm
|
||||||
)
|
)
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.process import safe_terminate, register_process, unregister_process
|
from utils.process import safe_terminate, register_process, unregister_process
|
||||||
|
|
||||||
rtlamr_bp = Blueprint('rtlamr', __name__)
|
rtlamr_bp = Blueprint('rtlamr', __name__)
|
||||||
@@ -296,10 +295,6 @@ def stream_rtlamr() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = app_module.rtlamr_queue.get(timeout=1)
|
msg = app_module.rtlamr_queue.get(timeout=1)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('rtlamr', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
+2
-21
@@ -31,23 +31,6 @@ ALLOWED_TLE_HOSTS = ['celestrak.org', 'celestrak.com', 'www.celestrak.org', 'www
|
|||||||
_tle_cache = dict(TLE_SATELLITES)
|
_tle_cache = dict(TLE_SATELLITES)
|
||||||
|
|
||||||
|
|
||||||
def init_tle_auto_refresh():
|
|
||||||
"""Initialize TLE auto-refresh. Called by app.py after initialization."""
|
|
||||||
import threading
|
|
||||||
|
|
||||||
def _auto_refresh_tle():
|
|
||||||
try:
|
|
||||||
updated = refresh_tle_data()
|
|
||||||
if updated:
|
|
||||||
logger.info(f"Auto-refreshed TLE data for: {', '.join(updated)}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Auto TLE refresh failed: {e}")
|
|
||||||
|
|
||||||
# Start auto-refresh in background
|
|
||||||
threading.Timer(2.0, _auto_refresh_tle).start()
|
|
||||||
logger.info("TLE auto-refresh scheduled")
|
|
||||||
|
|
||||||
|
|
||||||
def _fetch_iss_realtime(observer_lat: Optional[float] = None, observer_lon: Optional[float] = None) -> Optional[dict]:
|
def _fetch_iss_realtime(observer_lat: Optional[float] = None, observer_lon: Optional[float] = None) -> Optional[dict]:
|
||||||
"""
|
"""
|
||||||
Fetch real-time ISS position from external APIs.
|
Fetch real-time ISS position from external APIs.
|
||||||
@@ -498,8 +481,7 @@ def update_tle():
|
|||||||
'updated': updated
|
'updated': updated
|
||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error updating TLE data: {e}")
|
return jsonify({'status': 'error', 'message': str(e)})
|
||||||
return jsonify({'status': 'error', 'message': 'TLE update failed'})
|
|
||||||
|
|
||||||
|
|
||||||
@satellite_bp.route('/celestrak/<category>')
|
@satellite_bp.route('/celestrak/<category>')
|
||||||
@@ -553,5 +535,4 @@ def fetch_celestrak(category):
|
|||||||
})
|
})
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error fetching CelesTrak data: {e}")
|
return jsonify({'status': 'error', 'message': str(e)})
|
||||||
return jsonify({'status': 'error', 'message': 'Failed to fetch satellite data'})
|
|
||||||
|
|||||||
+15
-53
@@ -19,7 +19,6 @@ from utils.validation import (
|
|||||||
validate_rtl_tcp_host, validate_rtl_tcp_port
|
validate_rtl_tcp_host, validate_rtl_tcp_port
|
||||||
)
|
)
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.process import safe_terminate, register_process, unregister_process
|
from utils.process import safe_terminate, register_process, unregister_process
|
||||||
from utils.sdr import SDRFactory, SDRType
|
from utils.sdr import SDRFactory, SDRType
|
||||||
|
|
||||||
@@ -27,7 +26,6 @@ sensor_bp = Blueprint('sensor', __name__)
|
|||||||
|
|
||||||
# Track which device is being used
|
# Track which device is being used
|
||||||
sensor_active_device: int | None = None
|
sensor_active_device: int | None = None
|
||||||
sensor_active_sdr_type: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
def stream_sensor_output(process: subprocess.Popen[bytes]) -> None:
|
def stream_sensor_output(process: subprocess.Popen[bytes]) -> None:
|
||||||
@@ -46,21 +44,6 @@ def stream_sensor_output(process: subprocess.Popen[bytes]) -> None:
|
|||||||
data['type'] = 'sensor'
|
data['type'] = 'sensor'
|
||||||
app_module.sensor_queue.put(data)
|
app_module.sensor_queue.put(data)
|
||||||
|
|
||||||
# Push scope event when signal level data is present
|
|
||||||
rssi = data.get('rssi')
|
|
||||||
snr = data.get('snr')
|
|
||||||
noise = data.get('noise')
|
|
||||||
if rssi is not None or snr is not None:
|
|
||||||
try:
|
|
||||||
app_module.sensor_queue.put_nowait({
|
|
||||||
'type': 'scope',
|
|
||||||
'rssi': rssi if rssi is not None else 0,
|
|
||||||
'snr': snr if snr is not None else 0,
|
|
||||||
'noise': noise if noise is not None else 0,
|
|
||||||
})
|
|
||||||
except queue.Full:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Log if enabled
|
# Log if enabled
|
||||||
if app_module.logging_enabled:
|
if app_module.logging_enabled:
|
||||||
try:
|
try:
|
||||||
@@ -76,7 +59,7 @@ def stream_sensor_output(process: subprocess.Popen[bytes]) -> None:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
app_module.sensor_queue.put({'type': 'error', 'text': str(e)})
|
app_module.sensor_queue.put({'type': 'error', 'text': str(e)})
|
||||||
finally:
|
finally:
|
||||||
global sensor_active_device, sensor_active_sdr_type
|
global sensor_active_device
|
||||||
# Ensure process is terminated
|
# Ensure process is terminated
|
||||||
try:
|
try:
|
||||||
process.terminate()
|
process.terminate()
|
||||||
@@ -92,22 +75,13 @@ def stream_sensor_output(process: subprocess.Popen[bytes]) -> None:
|
|||||||
app_module.sensor_process = None
|
app_module.sensor_process = None
|
||||||
# Release SDR device
|
# Release SDR device
|
||||||
if sensor_active_device is not None:
|
if sensor_active_device is not None:
|
||||||
app_module.release_sdr_device(sensor_active_device, sensor_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(sensor_active_device)
|
||||||
sensor_active_device = None
|
sensor_active_device = None
|
||||||
sensor_active_sdr_type = None
|
|
||||||
|
|
||||||
|
|
||||||
@sensor_bp.route('/sensor/status')
|
|
||||||
def sensor_status() -> Response:
|
|
||||||
"""Check if sensor decoder is currently running."""
|
|
||||||
with app_module.sensor_lock:
|
|
||||||
running = app_module.sensor_process is not None and app_module.sensor_process.poll() is None
|
|
||||||
return jsonify({'running': running})
|
|
||||||
|
|
||||||
|
|
||||||
@sensor_bp.route('/start_sensor', methods=['POST'])
|
@sensor_bp.route('/start_sensor', methods=['POST'])
|
||||||
def start_sensor() -> Response:
|
def start_sensor() -> Response:
|
||||||
global sensor_active_device, sensor_active_sdr_type
|
global sensor_active_device
|
||||||
|
|
||||||
with app_module.sensor_lock:
|
with app_module.sensor_lock:
|
||||||
if app_module.sensor_process:
|
if app_module.sensor_process:
|
||||||
@@ -124,13 +98,6 @@ def start_sensor() -> Response:
|
|||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return jsonify({'status': 'error', 'message': str(e)}), 400
|
return jsonify({'status': 'error', 'message': str(e)}), 400
|
||||||
|
|
||||||
# Get SDR type and build command via abstraction layer
|
|
||||||
sdr_type_str = data.get('sdr_type', 'rtlsdr')
|
|
||||||
try:
|
|
||||||
sdr_type = SDRType(sdr_type_str)
|
|
||||||
except ValueError:
|
|
||||||
sdr_type = SDRType.RTL_SDR
|
|
||||||
|
|
||||||
# Check for rtl_tcp (remote SDR) connection
|
# Check for rtl_tcp (remote SDR) connection
|
||||||
rtl_tcp_host = data.get('rtl_tcp_host')
|
rtl_tcp_host = data.get('rtl_tcp_host')
|
||||||
rtl_tcp_port = data.get('rtl_tcp_port', 1234)
|
rtl_tcp_port = data.get('rtl_tcp_port', 1234)
|
||||||
@@ -138,7 +105,7 @@ def start_sensor() -> Response:
|
|||||||
# Claim local device if not using remote rtl_tcp
|
# Claim local device if not using remote rtl_tcp
|
||||||
if not rtl_tcp_host:
|
if not rtl_tcp_host:
|
||||||
device_int = int(device)
|
device_int = int(device)
|
||||||
error = app_module.claim_sdr_device(device_int, 'sensor', sdr_type.value)
|
error = app_module.claim_sdr_device(device_int, 'sensor')
|
||||||
if error:
|
if error:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'error',
|
'status': 'error',
|
||||||
@@ -146,7 +113,6 @@ def start_sensor() -> Response:
|
|||||||
'message': error
|
'message': error
|
||||||
}), 409
|
}), 409
|
||||||
sensor_active_device = device_int
|
sensor_active_device = device_int
|
||||||
sensor_active_sdr_type = sdr_type.value
|
|
||||||
|
|
||||||
# Clear queue
|
# Clear queue
|
||||||
while not app_module.sensor_queue.empty():
|
while not app_module.sensor_queue.empty():
|
||||||
@@ -155,6 +121,13 @@ def start_sensor() -> Response:
|
|||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
break
|
break
|
||||||
|
|
||||||
|
# Get SDR type and build command via abstraction layer
|
||||||
|
sdr_type_str = data.get('sdr_type', 'rtlsdr')
|
||||||
|
try:
|
||||||
|
sdr_type = SDRType(sdr_type_str)
|
||||||
|
except ValueError:
|
||||||
|
sdr_type = SDRType.RTL_SDR
|
||||||
|
|
||||||
if rtl_tcp_host:
|
if rtl_tcp_host:
|
||||||
# Validate and create network device
|
# Validate and create network device
|
||||||
try:
|
try:
|
||||||
@@ -184,10 +157,6 @@ def start_sensor() -> Response:
|
|||||||
full_cmd = ' '.join(cmd)
|
full_cmd = ' '.join(cmd)
|
||||||
logger.info(f"Running: {full_cmd}")
|
logger.info(f"Running: {full_cmd}")
|
||||||
|
|
||||||
# Add signal level metadata so the frontend scope can display RSSI/SNR
|
|
||||||
# Disable stats reporting to suppress "row count limit 50 reached" warnings
|
|
||||||
cmd.extend(['-M', 'level', '-M', 'stats:0'])
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
app_module.sensor_process = subprocess.Popen(
|
app_module.sensor_process = subprocess.Popen(
|
||||||
cmd,
|
cmd,
|
||||||
@@ -220,22 +189,20 @@ def start_sensor() -> Response:
|
|||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
# Release device on failure
|
# Release device on failure
|
||||||
if sensor_active_device is not None:
|
if sensor_active_device is not None:
|
||||||
app_module.release_sdr_device(sensor_active_device, sensor_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(sensor_active_device)
|
||||||
sensor_active_device = None
|
sensor_active_device = None
|
||||||
sensor_active_sdr_type = None
|
|
||||||
return jsonify({'status': 'error', 'message': 'rtl_433 not found. Install with: brew install rtl_433'})
|
return jsonify({'status': 'error', 'message': 'rtl_433 not found. Install with: brew install rtl_433'})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Release device on failure
|
# Release device on failure
|
||||||
if sensor_active_device is not None:
|
if sensor_active_device is not None:
|
||||||
app_module.release_sdr_device(sensor_active_device, sensor_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(sensor_active_device)
|
||||||
sensor_active_device = None
|
sensor_active_device = None
|
||||||
sensor_active_sdr_type = None
|
|
||||||
return jsonify({'status': 'error', 'message': str(e)})
|
return jsonify({'status': 'error', 'message': str(e)})
|
||||||
|
|
||||||
|
|
||||||
@sensor_bp.route('/stop_sensor', methods=['POST'])
|
@sensor_bp.route('/stop_sensor', methods=['POST'])
|
||||||
def stop_sensor() -> Response:
|
def stop_sensor() -> Response:
|
||||||
global sensor_active_device, sensor_active_sdr_type
|
global sensor_active_device
|
||||||
|
|
||||||
with app_module.sensor_lock:
|
with app_module.sensor_lock:
|
||||||
if app_module.sensor_process:
|
if app_module.sensor_process:
|
||||||
@@ -248,9 +215,8 @@ def stop_sensor() -> Response:
|
|||||||
|
|
||||||
# Release device from registry
|
# Release device from registry
|
||||||
if sensor_active_device is not None:
|
if sensor_active_device is not None:
|
||||||
app_module.release_sdr_device(sensor_active_device, sensor_active_sdr_type or 'rtlsdr')
|
app_module.release_sdr_device(sensor_active_device)
|
||||||
sensor_active_device = None
|
sensor_active_device = None
|
||||||
sensor_active_sdr_type = None
|
|
||||||
|
|
||||||
return jsonify({'status': 'stopped'})
|
return jsonify({'status': 'stopped'})
|
||||||
|
|
||||||
@@ -267,10 +233,6 @@ def stream_sensor() -> Response:
|
|||||||
try:
|
try:
|
||||||
msg = app_module.sensor_queue.get(timeout=1)
|
msg = app_module.sensor_queue.get(timeout=1)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('sensor', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
+6
-9
@@ -16,11 +16,12 @@ from flask import Blueprint, jsonify, request, Response, send_file
|
|||||||
import app as app_module
|
import app as app_module
|
||||||
from utils.logging import get_logger
|
from utils.logging import get_logger
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.sstv import (
|
from utils.sstv import (
|
||||||
get_sstv_decoder,
|
get_sstv_decoder,
|
||||||
is_sstv_available,
|
is_sstv_available,
|
||||||
ISS_SSTV_FREQ,
|
ISS_SSTV_FREQ,
|
||||||
|
DecodeProgress,
|
||||||
|
DopplerInfo,
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = get_logger('intercept.sstv')
|
logger = get_logger('intercept.sstv')
|
||||||
@@ -34,14 +35,14 @@ _sstv_queue: queue.Queue = queue.Queue(maxsize=100)
|
|||||||
sstv_active_device: int | None = None
|
sstv_active_device: int | None = None
|
||||||
|
|
||||||
|
|
||||||
def _progress_callback(data: dict) -> None:
|
def _progress_callback(progress: DecodeProgress) -> None:
|
||||||
"""Callback to queue progress/scope updates for SSE stream."""
|
"""Callback to queue progress updates for SSE stream."""
|
||||||
try:
|
try:
|
||||||
_sstv_queue.put_nowait(data)
|
_sstv_queue.put_nowait(progress.to_dict())
|
||||||
except queue.Full:
|
except queue.Full:
|
||||||
try:
|
try:
|
||||||
_sstv_queue.get_nowait()
|
_sstv_queue.get_nowait()
|
||||||
_sstv_queue.put_nowait(data)
|
_sstv_queue.put_nowait(progress.to_dict())
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -400,10 +401,6 @@ def stream_progress():
|
|||||||
try:
|
try:
|
||||||
progress = _sstv_queue.get(timeout=1)
|
progress = _sstv_queue.get(timeout=1)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('sstv', progress, progress.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(progress)
|
yield format_sse(progress)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ from flask import Blueprint, Response, jsonify, request, send_file
|
|||||||
|
|
||||||
from utils.logging import get_logger
|
from utils.logging import get_logger
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from utils.sstv import (
|
from utils.sstv import (
|
||||||
|
DecodeProgress,
|
||||||
get_general_sstv_decoder,
|
get_general_sstv_decoder,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -48,14 +48,14 @@ SSTV_FREQUENCIES = [
|
|||||||
_FREQ_MODULATION_MAP = {entry['frequency']: entry['modulation'] for entry in SSTV_FREQUENCIES}
|
_FREQ_MODULATION_MAP = {entry['frequency']: entry['modulation'] for entry in SSTV_FREQUENCIES}
|
||||||
|
|
||||||
|
|
||||||
def _progress_callback(data: dict) -> None:
|
def _progress_callback(progress: DecodeProgress) -> None:
|
||||||
"""Callback to queue progress/scope updates for SSE stream."""
|
"""Callback to queue progress updates for SSE stream."""
|
||||||
try:
|
try:
|
||||||
_sstv_general_queue.put_nowait(data)
|
_sstv_general_queue.put_nowait(progress.to_dict())
|
||||||
except queue.Full:
|
except queue.Full:
|
||||||
try:
|
try:
|
||||||
_sstv_general_queue.get_nowait()
|
_sstv_general_queue.get_nowait()
|
||||||
_sstv_general_queue.put_nowait(data)
|
_sstv_general_queue.put_nowait(progress.to_dict())
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -274,10 +274,6 @@ def stream_progress():
|
|||||||
try:
|
try:
|
||||||
progress = _sstv_general_queue.get(timeout=1)
|
progress = _sstv_general_queue.get(timeout=1)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('sstv_general', progress, progress.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(progress)
|
yield format_sse(progress)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
+1
-150
@@ -60,7 +60,6 @@ from utils.tscm.device_identity import (
|
|||||||
ingest_ble_dict,
|
ingest_ble_dict,
|
||||||
ingest_wifi_dict,
|
ingest_wifi_dict,
|
||||||
)
|
)
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
|
|
||||||
# Import unified Bluetooth scanner helper for TSCM integration
|
# Import unified Bluetooth scanner helper for TSCM integration
|
||||||
try:
|
try:
|
||||||
@@ -551,12 +550,6 @@ def _start_sweep_internal(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@tscm_bp.route('/status')
|
|
||||||
def tscm_status():
|
|
||||||
"""Check if any TSCM operation is currently running."""
|
|
||||||
return jsonify({'running': _sweep_running})
|
|
||||||
|
|
||||||
|
|
||||||
@tscm_bp.route('/sweep/start', methods=['POST'])
|
@tscm_bp.route('/sweep/start', methods=['POST'])
|
||||||
def start_sweep():
|
def start_sweep():
|
||||||
"""Start a TSCM sweep."""
|
"""Start a TSCM sweep."""
|
||||||
@@ -634,10 +627,6 @@ def sweep_stream():
|
|||||||
try:
|
try:
|
||||||
if tscm_queue:
|
if tscm_queue:
|
||||||
msg = tscm_queue.get(timeout=1)
|
msg = tscm_queue.get(timeout=1)
|
||||||
try:
|
|
||||||
process_event('tscm', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield f"data: {json.dumps(msg)}\n\n"
|
yield f"data: {json.dumps(msg)}\n\n"
|
||||||
else:
|
else:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
@@ -1083,32 +1072,6 @@ def _scan_wifi_networks(interface: str) -> list[dict]:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
def _scan_wifi_clients(interface: str) -> list[dict]:
|
|
||||||
"""
|
|
||||||
Get WiFi client observations from the unified WiFi scanner.
|
|
||||||
|
|
||||||
Clients are only available when monitor-mode scanning is active.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
from utils.wifi import get_wifi_scanner
|
|
||||||
|
|
||||||
scanner = get_wifi_scanner()
|
|
||||||
if interface:
|
|
||||||
try:
|
|
||||||
if not scanner._is_monitor_mode_interface(interface):
|
|
||||||
return []
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
return [client.to_dict() for client in scanner.clients]
|
|
||||||
except ImportError as e:
|
|
||||||
logger.error(f"Failed to import wifi scanner: {e}")
|
|
||||||
return []
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception(f"WiFi client scan failed: {e}")
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
def _scan_bluetooth_devices(interface: str, duration: int = 10) -> list[dict]:
|
def _scan_bluetooth_devices(interface: str, duration: int = 10) -> list[dict]:
|
||||||
"""
|
"""
|
||||||
Scan for Bluetooth devices with manufacturer data detection.
|
Scan for Bluetooth devices with manufacturer data detection.
|
||||||
@@ -1643,7 +1606,6 @@ def _run_sweep(
|
|||||||
threats_found = 0
|
threats_found = 0
|
||||||
severity_counts = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0}
|
severity_counts = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0}
|
||||||
all_wifi = {} # Use dict for deduplication by BSSID
|
all_wifi = {} # Use dict for deduplication by BSSID
|
||||||
all_wifi_clients = {} # Use dict for deduplication by client MAC
|
|
||||||
all_bt = {} # Use dict for deduplication by MAC
|
all_bt = {} # Use dict for deduplication by MAC
|
||||||
all_rf = []
|
all_rf = []
|
||||||
|
|
||||||
@@ -1740,7 +1702,6 @@ def _run_sweep(
|
|||||||
'channel': network.get('channel', ''),
|
'channel': network.get('channel', ''),
|
||||||
'signal': network.get('power', ''),
|
'signal': network.get('power', ''),
|
||||||
'security': network.get('privacy', ''),
|
'security': network.get('privacy', ''),
|
||||||
'vendor': network.get('vendor'),
|
|
||||||
'is_threat': is_threat,
|
'is_threat': is_threat,
|
||||||
'is_new': not classification.get('in_baseline', False),
|
'is_new': not classification.get('in_baseline', False),
|
||||||
'classification': profile.risk_level.value,
|
'classification': profile.risk_level.value,
|
||||||
@@ -1754,77 +1715,6 @@ def _run_sweep(
|
|||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"WiFi device processing error for {network.get('bssid', '?')}: {e}")
|
logger.error(f"WiFi device processing error for {network.get('bssid', '?')}: {e}")
|
||||||
|
|
||||||
# WiFi clients (monitor mode only)
|
|
||||||
try:
|
|
||||||
wifi_clients = _scan_wifi_clients(wifi_interface)
|
|
||||||
for client in wifi_clients:
|
|
||||||
mac = (client.get('mac') or '').upper()
|
|
||||||
if not mac or mac in all_wifi_clients:
|
|
||||||
continue
|
|
||||||
all_wifi_clients[mac] = client
|
|
||||||
|
|
||||||
rssi_val = client.get('rssi_current')
|
|
||||||
if rssi_val is None:
|
|
||||||
rssi_val = client.get('rssi_median') or client.get('rssi_ema')
|
|
||||||
|
|
||||||
client_device = {
|
|
||||||
'mac': mac,
|
|
||||||
'vendor': client.get('vendor'),
|
|
||||||
'name': client.get('vendor') or 'WiFi Client',
|
|
||||||
'rssi': rssi_val,
|
|
||||||
'associated_bssid': client.get('associated_bssid'),
|
|
||||||
'probed_ssids': client.get('probed_ssids', []),
|
|
||||||
'probe_count': client.get('probe_count', len(client.get('probed_ssids', []))),
|
|
||||||
'is_client': True,
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
|
||||||
timeline_manager.add_observation(
|
|
||||||
identifier=mac,
|
|
||||||
protocol='wifi',
|
|
||||||
rssi=rssi_val,
|
|
||||||
name=client_device.get('vendor') or f'WiFi Client {mac[-5:]}',
|
|
||||||
attributes={'client': True, 'associated_bssid': client_device.get('associated_bssid')}
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"WiFi client timeline observation error: {e}")
|
|
||||||
_maybe_store_timeline(
|
|
||||||
identifier=mac,
|
|
||||||
protocol='wifi',
|
|
||||||
rssi=rssi_val,
|
|
||||||
attributes={'client': True, 'associated_bssid': client_device.get('associated_bssid')}
|
|
||||||
)
|
|
||||||
|
|
||||||
profile = correlation.analyze_wifi_device(client_device)
|
|
||||||
client_device['classification'] = profile.risk_level.value
|
|
||||||
client_device['score'] = profile.total_score
|
|
||||||
client_device['score_modifier'] = profile.score_modifier
|
|
||||||
client_device['known_device'] = profile.known_device
|
|
||||||
client_device['known_device_name'] = profile.known_device_name
|
|
||||||
client_device['indicators'] = [
|
|
||||||
{'type': i.type.value, 'desc': i.description}
|
|
||||||
for i in profile.indicators
|
|
||||||
]
|
|
||||||
client_device['recommended_action'] = profile.recommended_action
|
|
||||||
|
|
||||||
# Feed to identity engine for MAC-randomization resistant clustering
|
|
||||||
try:
|
|
||||||
wifi_obs = {
|
|
||||||
'timestamp': datetime.now().isoformat(),
|
|
||||||
'src_mac': mac,
|
|
||||||
'bssid': client_device.get('associated_bssid'),
|
|
||||||
'rssi': rssi_val,
|
|
||||||
'frame_type': 'probe_request',
|
|
||||||
'probed_ssids': client_device.get('probed_ssids', []),
|
|
||||||
}
|
|
||||||
ingest_wifi_dict(wifi_obs)
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"Identity engine WiFi client ingest error: {e}")
|
|
||||||
|
|
||||||
_emit_event('wifi_client', client_device)
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"WiFi client scan error: {e}")
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
last_wifi_scan = current_time
|
last_wifi_scan = current_time
|
||||||
logger.error(f"WiFi scan error: {e}")
|
logger.error(f"WiFi scan error: {e}")
|
||||||
@@ -1903,9 +1793,6 @@ def _run_sweep(
|
|||||||
'name': device.get('name', 'Unknown'),
|
'name': device.get('name', 'Unknown'),
|
||||||
'device_type': device.get('type', ''),
|
'device_type': device.get('type', ''),
|
||||||
'rssi': device.get('rssi', ''),
|
'rssi': device.get('rssi', ''),
|
||||||
'manufacturer': device.get('manufacturer'),
|
|
||||||
'tracker': device.get('tracker'),
|
|
||||||
'tracker_type': device.get('tracker_type'),
|
|
||||||
'is_threat': is_threat,
|
'is_threat': is_threat,
|
||||||
'is_new': not classification.get('in_baseline', False),
|
'is_new': not classification.get('in_baseline', False),
|
||||||
'classification': profile.risk_level.value,
|
'classification': profile.risk_level.value,
|
||||||
@@ -2034,7 +1921,6 @@ def _run_sweep(
|
|||||||
comparator = BaselineComparator(baseline)
|
comparator = BaselineComparator(baseline)
|
||||||
baseline_comparison = comparator.compare_all(
|
baseline_comparison = comparator.compare_all(
|
||||||
wifi_devices=list(all_wifi.values()),
|
wifi_devices=list(all_wifi.values()),
|
||||||
wifi_clients=list(all_wifi_clients.values()),
|
|
||||||
bt_devices=list(all_bt.values()),
|
bt_devices=list(all_bt.values()),
|
||||||
rf_signals=all_rf
|
rf_signals=all_rf
|
||||||
)
|
)
|
||||||
@@ -2050,7 +1936,6 @@ def _run_sweep(
|
|||||||
|
|
||||||
if verbose_results:
|
if verbose_results:
|
||||||
wifi_payload = list(all_wifi.values())
|
wifi_payload = list(all_wifi.values())
|
||||||
wifi_client_payload = list(all_wifi_clients.values())
|
|
||||||
bt_payload = list(all_bt.values())
|
bt_payload = list(all_bt.values())
|
||||||
rf_payload = list(all_rf)
|
rf_payload = list(all_rf)
|
||||||
else:
|
else:
|
||||||
@@ -2066,28 +1951,6 @@ def _run_sweep(
|
|||||||
}
|
}
|
||||||
for d in all_wifi.values()
|
for d in all_wifi.values()
|
||||||
]
|
]
|
||||||
wifi_client_payload = []
|
|
||||||
for client in all_wifi_clients.values():
|
|
||||||
mac = client.get('mac') or client.get('address')
|
|
||||||
if isinstance(mac, str):
|
|
||||||
mac = mac.upper()
|
|
||||||
probed_ssids = client.get('probed_ssids') or []
|
|
||||||
rssi = client.get('rssi')
|
|
||||||
if rssi is None:
|
|
||||||
rssi = client.get('rssi_current')
|
|
||||||
if rssi is None:
|
|
||||||
rssi = client.get('rssi_median')
|
|
||||||
if rssi is None:
|
|
||||||
rssi = client.get('rssi_ema')
|
|
||||||
wifi_client_payload.append({
|
|
||||||
'mac': mac,
|
|
||||||
'vendor': client.get('vendor'),
|
|
||||||
'rssi': rssi,
|
|
||||||
'associated_bssid': client.get('associated_bssid'),
|
|
||||||
'is_associated': client.get('is_associated'),
|
|
||||||
'probed_ssids': probed_ssids,
|
|
||||||
'probe_count': client.get('probe_count', len(probed_ssids)),
|
|
||||||
})
|
|
||||||
bt_payload = [
|
bt_payload = [
|
||||||
{
|
{
|
||||||
'mac': d.get('mac') or d.get('address'),
|
'mac': d.get('mac') or d.get('address'),
|
||||||
@@ -2112,11 +1975,9 @@ def _run_sweep(
|
|||||||
status='completed',
|
status='completed',
|
||||||
results={
|
results={
|
||||||
'wifi_devices': wifi_payload,
|
'wifi_devices': wifi_payload,
|
||||||
'wifi_clients': wifi_client_payload,
|
|
||||||
'bt_devices': bt_payload,
|
'bt_devices': bt_payload,
|
||||||
'rf_signals': rf_payload,
|
'rf_signals': rf_payload,
|
||||||
'wifi_count': len(all_wifi),
|
'wifi_count': len(all_wifi),
|
||||||
'wifi_client_count': len(all_wifi_clients),
|
|
||||||
'bt_count': len(all_bt),
|
'bt_count': len(all_bt),
|
||||||
'rf_count': len(all_rf),
|
'rf_count': len(all_rf),
|
||||||
'severity_counts': severity_counts,
|
'severity_counts': severity_counts,
|
||||||
@@ -2144,7 +2005,6 @@ def _run_sweep(
|
|||||||
'total_new': baseline_comparison['total_new'],
|
'total_new': baseline_comparison['total_new'],
|
||||||
'total_missing': baseline_comparison['total_missing'],
|
'total_missing': baseline_comparison['total_missing'],
|
||||||
'wifi': baseline_comparison.get('wifi'),
|
'wifi': baseline_comparison.get('wifi'),
|
||||||
'wifi_clients': baseline_comparison.get('wifi_clients'),
|
|
||||||
'bluetooth': baseline_comparison.get('bluetooth'),
|
'bluetooth': baseline_comparison.get('bluetooth'),
|
||||||
'rf': baseline_comparison.get('rf'),
|
'rf': baseline_comparison.get('rf'),
|
||||||
})
|
})
|
||||||
@@ -2162,7 +2022,6 @@ def _run_sweep(
|
|||||||
'sweep_id': _current_sweep_id,
|
'sweep_id': _current_sweep_id,
|
||||||
'threats_found': threats_found,
|
'threats_found': threats_found,
|
||||||
'wifi_count': len(all_wifi),
|
'wifi_count': len(all_wifi),
|
||||||
'wifi_client_count': len(all_wifi_clients),
|
|
||||||
'bt_count': len(all_bt),
|
'bt_count': len(all_bt),
|
||||||
'rf_count': len(all_rf),
|
'rf_count': len(all_rf),
|
||||||
'severity_counts': severity_counts,
|
'severity_counts': severity_counts,
|
||||||
@@ -2310,7 +2169,6 @@ def compare_against_baseline():
|
|||||||
|
|
||||||
Expects JSON body with:
|
Expects JSON body with:
|
||||||
- wifi_devices: list of WiFi devices (optional)
|
- wifi_devices: list of WiFi devices (optional)
|
||||||
- wifi_clients: list of WiFi clients (optional)
|
|
||||||
- bt_devices: list of Bluetooth devices (optional)
|
- bt_devices: list of Bluetooth devices (optional)
|
||||||
- rf_signals: list of RF signals (optional)
|
- rf_signals: list of RF signals (optional)
|
||||||
|
|
||||||
@@ -2319,14 +2177,12 @@ def compare_against_baseline():
|
|||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
|
|
||||||
wifi_devices = data.get('wifi_devices')
|
wifi_devices = data.get('wifi_devices')
|
||||||
wifi_clients = data.get('wifi_clients')
|
|
||||||
bt_devices = data.get('bt_devices')
|
bt_devices = data.get('bt_devices')
|
||||||
rf_signals = data.get('rf_signals')
|
rf_signals = data.get('rf_signals')
|
||||||
|
|
||||||
# Use the convenience function that gets active baseline
|
# Use the convenience function that gets active baseline
|
||||||
comparison = get_comparison_for_active_baseline(
|
comparison = get_comparison_for_active_baseline(
|
||||||
wifi_devices=wifi_devices,
|
wifi_devices=wifi_devices,
|
||||||
wifi_clients=wifi_clients,
|
|
||||||
bt_devices=bt_devices,
|
bt_devices=bt_devices,
|
||||||
rf_signals=rf_signals
|
rf_signals=rf_signals
|
||||||
)
|
)
|
||||||
@@ -2420,10 +2276,7 @@ def feed_wifi():
|
|||||||
"""Feed WiFi device data for baseline recording."""
|
"""Feed WiFi device data for baseline recording."""
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
if data:
|
if data:
|
||||||
if data.get('is_client'):
|
_baseline_recorder.add_wifi_device(data)
|
||||||
_baseline_recorder.add_wifi_client(data)
|
|
||||||
else:
|
|
||||||
_baseline_recorder.add_wifi_device(data)
|
|
||||||
return jsonify({'status': 'success'})
|
return jsonify({'status': 'success'})
|
||||||
|
|
||||||
|
|
||||||
@@ -3075,14 +2928,12 @@ def get_baseline_diff(baseline_id: int, sweep_id: int):
|
|||||||
results = json.loads(results)
|
results = json.loads(results)
|
||||||
|
|
||||||
current_wifi = results.get('wifi_devices', [])
|
current_wifi = results.get('wifi_devices', [])
|
||||||
current_wifi_clients = results.get('wifi_clients', [])
|
|
||||||
current_bt = results.get('bt_devices', [])
|
current_bt = results.get('bt_devices', [])
|
||||||
current_rf = results.get('rf_signals', [])
|
current_rf = results.get('rf_signals', [])
|
||||||
|
|
||||||
diff = calculate_baseline_diff(
|
diff = calculate_baseline_diff(
|
||||||
baseline=baseline,
|
baseline=baseline,
|
||||||
current_wifi=current_wifi,
|
current_wifi=current_wifi,
|
||||||
current_wifi_clients=current_wifi_clients,
|
|
||||||
current_bt=current_bt,
|
current_bt=current_bt,
|
||||||
current_rf=current_rf,
|
current_rf=current_rf,
|
||||||
sweep_id=sweep_id
|
sweep_id=sweep_id
|
||||||
|
|||||||
@@ -1,393 +0,0 @@
|
|||||||
"""WebSocket-based waterfall streaming with I/Q capture and server-side FFT."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import queue
|
|
||||||
import socket
|
|
||||||
import subprocess
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
|
|
||||||
from flask import Flask
|
|
||||||
|
|
||||||
try:
|
|
||||||
from flask_sock import Sock
|
|
||||||
WEBSOCKET_AVAILABLE = True
|
|
||||||
except ImportError:
|
|
||||||
WEBSOCKET_AVAILABLE = False
|
|
||||||
Sock = None
|
|
||||||
|
|
||||||
from utils.logging import get_logger
|
|
||||||
from utils.process import safe_terminate, register_process, unregister_process
|
|
||||||
from utils.waterfall_fft import (
|
|
||||||
build_binary_frame,
|
|
||||||
compute_power_spectrum,
|
|
||||||
cu8_to_complex,
|
|
||||||
quantize_to_uint8,
|
|
||||||
)
|
|
||||||
from utils.sdr import SDRFactory, SDRType
|
|
||||||
from utils.sdr.base import SDRCapabilities, SDRDevice
|
|
||||||
|
|
||||||
logger = get_logger('intercept.waterfall_ws')
|
|
||||||
|
|
||||||
# Maximum bandwidth per SDR type (Hz)
|
|
||||||
MAX_BANDWIDTH = {
|
|
||||||
SDRType.RTL_SDR: 2400000,
|
|
||||||
SDRType.HACKRF: 20000000,
|
|
||||||
SDRType.LIME_SDR: 20000000,
|
|
||||||
SDRType.AIRSPY: 10000000,
|
|
||||||
SDRType.SDRPLAY: 2000000,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve_sdr_type(sdr_type_str: str) -> SDRType:
|
|
||||||
"""Convert client sdr_type string to SDRType enum."""
|
|
||||||
mapping = {
|
|
||||||
'rtlsdr': SDRType.RTL_SDR,
|
|
||||||
'rtl_sdr': SDRType.RTL_SDR,
|
|
||||||
'hackrf': SDRType.HACKRF,
|
|
||||||
'limesdr': SDRType.LIME_SDR,
|
|
||||||
'lime_sdr': SDRType.LIME_SDR,
|
|
||||||
'airspy': SDRType.AIRSPY,
|
|
||||||
'sdrplay': SDRType.SDRPLAY,
|
|
||||||
}
|
|
||||||
return mapping.get(sdr_type_str.lower(), SDRType.RTL_SDR)
|
|
||||||
|
|
||||||
|
|
||||||
def _build_dummy_device(device_index: int, sdr_type: SDRType) -> SDRDevice:
|
|
||||||
"""Build a minimal SDRDevice for command building."""
|
|
||||||
builder = SDRFactory.get_builder(sdr_type)
|
|
||||||
caps = builder.get_capabilities()
|
|
||||||
return SDRDevice(
|
|
||||||
sdr_type=sdr_type,
|
|
||||||
index=device_index,
|
|
||||||
name=f'{sdr_type.value}-{device_index}',
|
|
||||||
serial='N/A',
|
|
||||||
driver=sdr_type.value,
|
|
||||||
capabilities=caps,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def init_waterfall_websocket(app: Flask):
|
|
||||||
"""Initialize WebSocket waterfall streaming."""
|
|
||||||
if not WEBSOCKET_AVAILABLE:
|
|
||||||
logger.warning("flask-sock not installed, WebSocket waterfall disabled")
|
|
||||||
return
|
|
||||||
|
|
||||||
sock = Sock(app)
|
|
||||||
|
|
||||||
@sock.route('/ws/waterfall')
|
|
||||||
def waterfall_stream(ws):
|
|
||||||
"""WebSocket endpoint for real-time waterfall streaming."""
|
|
||||||
logger.info("WebSocket waterfall client connected")
|
|
||||||
|
|
||||||
# Import app module for device claiming
|
|
||||||
import app as app_module
|
|
||||||
|
|
||||||
iq_process = None
|
|
||||||
reader_thread = None
|
|
||||||
stop_event = threading.Event()
|
|
||||||
claimed_device = None
|
|
||||||
claimed_sdr_type = None
|
|
||||||
# Queue for outgoing messages — only the main loop touches ws.send()
|
|
||||||
send_queue = queue.Queue(maxsize=120)
|
|
||||||
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
# Drain send queue first (non-blocking)
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
outgoing = send_queue.get_nowait()
|
|
||||||
except queue.Empty:
|
|
||||||
break
|
|
||||||
try:
|
|
||||||
ws.send(outgoing)
|
|
||||||
except Exception:
|
|
||||||
stop_event.set()
|
|
||||||
break
|
|
||||||
|
|
||||||
try:
|
|
||||||
msg = ws.receive(timeout=0.1)
|
|
||||||
except Exception as e:
|
|
||||||
err = str(e).lower()
|
|
||||||
if "closed" in err:
|
|
||||||
break
|
|
||||||
if "timed out" not in err:
|
|
||||||
logger.error(f"WebSocket receive error: {e}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
if msg is None:
|
|
||||||
# simple-websocket returns None on timeout AND on
|
|
||||||
# close; check ws.connected to tell them apart.
|
|
||||||
if not ws.connected:
|
|
||||||
break
|
|
||||||
if stop_event.is_set():
|
|
||||||
break
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
|
||||||
data = json.loads(msg)
|
|
||||||
except (json.JSONDecodeError, TypeError):
|
|
||||||
continue
|
|
||||||
|
|
||||||
cmd = data.get('cmd')
|
|
||||||
|
|
||||||
if cmd == 'start':
|
|
||||||
# Stop any existing capture
|
|
||||||
was_restarting = iq_process is not None
|
|
||||||
stop_event.set()
|
|
||||||
if reader_thread and reader_thread.is_alive():
|
|
||||||
reader_thread.join(timeout=2)
|
|
||||||
if iq_process:
|
|
||||||
safe_terminate(iq_process)
|
|
||||||
unregister_process(iq_process)
|
|
||||||
iq_process = None
|
|
||||||
if claimed_device is not None:
|
|
||||||
app_module.release_sdr_device(claimed_device, claimed_sdr_type or 'rtlsdr')
|
|
||||||
claimed_device = None
|
|
||||||
claimed_sdr_type = None
|
|
||||||
stop_event.clear()
|
|
||||||
# Flush stale frames from previous capture
|
|
||||||
while not send_queue.empty():
|
|
||||||
try:
|
|
||||||
send_queue.get_nowait()
|
|
||||||
except queue.Empty:
|
|
||||||
break
|
|
||||||
# Allow USB device to be released by the kernel
|
|
||||||
if was_restarting:
|
|
||||||
time.sleep(0.5)
|
|
||||||
|
|
||||||
# Parse config
|
|
||||||
center_freq = float(data.get('center_freq', 100.0))
|
|
||||||
span_mhz = float(data.get('span_mhz', 2.0))
|
|
||||||
gain = data.get('gain')
|
|
||||||
if gain is not None:
|
|
||||||
gain = float(gain)
|
|
||||||
device_index = int(data.get('device', 0))
|
|
||||||
sdr_type_str = data.get('sdr_type', 'rtlsdr')
|
|
||||||
fft_size = int(data.get('fft_size', 1024))
|
|
||||||
fps = int(data.get('fps', 25))
|
|
||||||
avg_count = int(data.get('avg_count', 4))
|
|
||||||
ppm = data.get('ppm')
|
|
||||||
if ppm is not None:
|
|
||||||
ppm = int(ppm)
|
|
||||||
bias_t = bool(data.get('bias_t', False))
|
|
||||||
|
|
||||||
# Clamp FFT size to valid powers of 2
|
|
||||||
fft_size = max(256, min(8192, fft_size))
|
|
||||||
|
|
||||||
# Resolve SDR type and bandwidth
|
|
||||||
sdr_type = _resolve_sdr_type(sdr_type_str)
|
|
||||||
max_bw = MAX_BANDWIDTH.get(sdr_type, 2400000)
|
|
||||||
span_hz = int(span_mhz * 1e6)
|
|
||||||
sample_rate = min(span_hz, max_bw)
|
|
||||||
|
|
||||||
# Compute effective frequency range
|
|
||||||
effective_span_mhz = sample_rate / 1e6
|
|
||||||
start_freq = center_freq - effective_span_mhz / 2
|
|
||||||
end_freq = center_freq + effective_span_mhz / 2
|
|
||||||
|
|
||||||
# Claim the device
|
|
||||||
claim_err = app_module.claim_sdr_device(device_index, 'waterfall', sdr_type.value)
|
|
||||||
if claim_err:
|
|
||||||
ws.send(json.dumps({
|
|
||||||
'status': 'error',
|
|
||||||
'message': claim_err,
|
|
||||||
'error_type': 'DEVICE_BUSY',
|
|
||||||
}))
|
|
||||||
continue
|
|
||||||
claimed_device = device_index
|
|
||||||
claimed_sdr_type = sdr_type.value
|
|
||||||
|
|
||||||
# Build I/Q capture command
|
|
||||||
try:
|
|
||||||
builder = SDRFactory.get_builder(sdr_type)
|
|
||||||
device = _build_dummy_device(device_index, sdr_type)
|
|
||||||
iq_cmd = builder.build_iq_capture_command(
|
|
||||||
device=device,
|
|
||||||
frequency_mhz=center_freq,
|
|
||||||
sample_rate=sample_rate,
|
|
||||||
gain=gain,
|
|
||||||
ppm=ppm,
|
|
||||||
bias_t=bias_t,
|
|
||||||
)
|
|
||||||
except NotImplementedError as e:
|
|
||||||
app_module.release_sdr_device(device_index, sdr_type.value)
|
|
||||||
claimed_device = None
|
|
||||||
claimed_sdr_type = None
|
|
||||||
ws.send(json.dumps({
|
|
||||||
'status': 'error',
|
|
||||||
'message': str(e),
|
|
||||||
}))
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Spawn I/Q capture process (retry to handle USB release lag)
|
|
||||||
max_attempts = 3 if was_restarting else 1
|
|
||||||
try:
|
|
||||||
for attempt in range(max_attempts):
|
|
||||||
logger.info(
|
|
||||||
f"Starting I/Q capture: {center_freq} MHz, "
|
|
||||||
f"span={effective_span_mhz:.1f} MHz, "
|
|
||||||
f"sr={sample_rate}, fft={fft_size}"
|
|
||||||
)
|
|
||||||
iq_process = subprocess.Popen(
|
|
||||||
iq_cmd,
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.DEVNULL,
|
|
||||||
bufsize=0,
|
|
||||||
)
|
|
||||||
register_process(iq_process)
|
|
||||||
|
|
||||||
# Brief check that process started
|
|
||||||
time.sleep(0.3)
|
|
||||||
if iq_process.poll() is not None:
|
|
||||||
unregister_process(iq_process)
|
|
||||||
iq_process = None
|
|
||||||
if attempt < max_attempts - 1:
|
|
||||||
logger.info(
|
|
||||||
f"I/Q process exited immediately, "
|
|
||||||
f"retrying ({attempt + 1}/{max_attempts})..."
|
|
||||||
)
|
|
||||||
time.sleep(0.5)
|
|
||||||
continue
|
|
||||||
raise RuntimeError(
|
|
||||||
"I/Q capture process exited immediately"
|
|
||||||
)
|
|
||||||
break # Process started successfully
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Failed to start I/Q capture: {e}")
|
|
||||||
if iq_process:
|
|
||||||
safe_terminate(iq_process)
|
|
||||||
unregister_process(iq_process)
|
|
||||||
iq_process = None
|
|
||||||
app_module.release_sdr_device(device_index, sdr_type.value)
|
|
||||||
claimed_device = None
|
|
||||||
claimed_sdr_type = None
|
|
||||||
ws.send(json.dumps({
|
|
||||||
'status': 'error',
|
|
||||||
'message': f'Failed to start I/Q capture: {e}',
|
|
||||||
}))
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Send started confirmation
|
|
||||||
ws.send(json.dumps({
|
|
||||||
'status': 'started',
|
|
||||||
'start_freq': start_freq,
|
|
||||||
'end_freq': end_freq,
|
|
||||||
'fft_size': fft_size,
|
|
||||||
'sample_rate': sample_rate,
|
|
||||||
}))
|
|
||||||
|
|
||||||
# Start reader thread — puts frames on queue, never calls ws.send()
|
|
||||||
def fft_reader(
|
|
||||||
proc, _send_q, stop_evt,
|
|
||||||
_fft_size, _avg_count, _fps,
|
|
||||||
_start_freq, _end_freq,
|
|
||||||
):
|
|
||||||
"""Read I/Q from subprocess, compute FFT, enqueue binary frames."""
|
|
||||||
bytes_per_frame = _fft_size * _avg_count * 2
|
|
||||||
frame_interval = 1.0 / _fps
|
|
||||||
|
|
||||||
try:
|
|
||||||
while not stop_evt.is_set():
|
|
||||||
if proc.poll() is not None:
|
|
||||||
break
|
|
||||||
|
|
||||||
frame_start = time.monotonic()
|
|
||||||
|
|
||||||
# Read raw I/Q bytes
|
|
||||||
raw = b''
|
|
||||||
remaining = bytes_per_frame
|
|
||||||
while remaining > 0 and not stop_evt.is_set():
|
|
||||||
chunk = proc.stdout.read(min(remaining, 65536))
|
|
||||||
if not chunk:
|
|
||||||
break
|
|
||||||
raw += chunk
|
|
||||||
remaining -= len(chunk)
|
|
||||||
|
|
||||||
if len(raw) < _fft_size * 2:
|
|
||||||
break
|
|
||||||
|
|
||||||
# Process FFT pipeline
|
|
||||||
samples = cu8_to_complex(raw)
|
|
||||||
power_db = compute_power_spectrum(
|
|
||||||
samples,
|
|
||||||
fft_size=_fft_size,
|
|
||||||
avg_count=_avg_count,
|
|
||||||
)
|
|
||||||
quantized = quantize_to_uint8(power_db)
|
|
||||||
frame = build_binary_frame(
|
|
||||||
_start_freq, _end_freq, quantized,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
_send_q.put_nowait(frame)
|
|
||||||
except queue.Full:
|
|
||||||
# Drop frame if main loop can't keep up
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Pace to target FPS
|
|
||||||
elapsed = time.monotonic() - frame_start
|
|
||||||
sleep_time = frame_interval - elapsed
|
|
||||||
if sleep_time > 0:
|
|
||||||
stop_evt.wait(sleep_time)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"FFT reader stopped: {e}")
|
|
||||||
|
|
||||||
reader_thread = threading.Thread(
|
|
||||||
target=fft_reader,
|
|
||||||
args=(
|
|
||||||
iq_process, send_queue, stop_event,
|
|
||||||
fft_size, avg_count, fps,
|
|
||||||
start_freq, end_freq,
|
|
||||||
),
|
|
||||||
daemon=True,
|
|
||||||
)
|
|
||||||
reader_thread.start()
|
|
||||||
|
|
||||||
elif cmd == 'stop':
|
|
||||||
stop_event.set()
|
|
||||||
if reader_thread and reader_thread.is_alive():
|
|
||||||
reader_thread.join(timeout=2)
|
|
||||||
reader_thread = None
|
|
||||||
if iq_process:
|
|
||||||
safe_terminate(iq_process)
|
|
||||||
unregister_process(iq_process)
|
|
||||||
iq_process = None
|
|
||||||
if claimed_device is not None:
|
|
||||||
app_module.release_sdr_device(claimed_device, claimed_sdr_type or 'rtlsdr')
|
|
||||||
claimed_device = None
|
|
||||||
claimed_sdr_type = None
|
|
||||||
stop_event.clear()
|
|
||||||
ws.send(json.dumps({'status': 'stopped'}))
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.info(f"WebSocket waterfall closed: {e}")
|
|
||||||
finally:
|
|
||||||
# Cleanup
|
|
||||||
stop_event.set()
|
|
||||||
if reader_thread and reader_thread.is_alive():
|
|
||||||
reader_thread.join(timeout=2)
|
|
||||||
if iq_process:
|
|
||||||
safe_terminate(iq_process)
|
|
||||||
unregister_process(iq_process)
|
|
||||||
if claimed_device is not None:
|
|
||||||
app_module.release_sdr_device(claimed_device, claimed_sdr_type or 'rtlsdr')
|
|
||||||
claimed_sdr_type = None
|
|
||||||
# Complete WebSocket close handshake, then shut down the
|
|
||||||
# raw socket so Werkzeug cannot write its HTTP 200 response
|
|
||||||
# on top of the WebSocket stream (which browsers see as
|
|
||||||
# "Invalid frame header").
|
|
||||||
try:
|
|
||||||
ws.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
ws.sock.shutdown(socket.SHUT_RDWR)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
ws.sock.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
logger.info("WebSocket waterfall client disconnected")
|
|
||||||
@@ -1,626 +0,0 @@
|
|||||||
"""Weather Satellite decoder routes.
|
|
||||||
|
|
||||||
Provides endpoints for capturing and decoding weather satellite images
|
|
||||||
from NOAA (APT) and Meteor (LRPT) satellites using SatDump.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import queue
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request, Response, send_file
|
|
||||||
|
|
||||||
from utils.logging import get_logger
|
|
||||||
from utils.sse import sse_stream
|
|
||||||
from utils.validation import validate_device_index, validate_gain, validate_latitude, validate_longitude, validate_elevation
|
|
||||||
from utils.weather_sat import (
|
|
||||||
get_weather_sat_decoder,
|
|
||||||
is_weather_sat_available,
|
|
||||||
CaptureProgress,
|
|
||||||
WEATHER_SATELLITES,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger = get_logger('intercept.weather_sat')
|
|
||||||
|
|
||||||
weather_sat_bp = Blueprint('weather_sat', __name__, url_prefix='/weather-sat')
|
|
||||||
|
|
||||||
# Queue for SSE progress streaming
|
|
||||||
_weather_sat_queue: queue.Queue = queue.Queue(maxsize=100)
|
|
||||||
|
|
||||||
|
|
||||||
def _progress_callback(progress: CaptureProgress) -> None:
|
|
||||||
"""Callback to queue progress updates for SSE stream."""
|
|
||||||
try:
|
|
||||||
_weather_sat_queue.put_nowait(progress.to_dict())
|
|
||||||
except queue.Full:
|
|
||||||
try:
|
|
||||||
_weather_sat_queue.get_nowait()
|
|
||||||
_weather_sat_queue.put_nowait(progress.to_dict())
|
|
||||||
except queue.Empty:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/status')
|
|
||||||
def get_status():
|
|
||||||
"""Get weather satellite decoder status.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON with decoder availability and current status.
|
|
||||||
"""
|
|
||||||
decoder = get_weather_sat_decoder()
|
|
||||||
return jsonify(decoder.get_status())
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/satellites')
|
|
||||||
def list_satellites():
|
|
||||||
"""Get list of supported weather satellites with frequencies.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON with satellite definitions.
|
|
||||||
"""
|
|
||||||
satellites = []
|
|
||||||
for key, info in WEATHER_SATELLITES.items():
|
|
||||||
satellites.append({
|
|
||||||
'key': key,
|
|
||||||
'name': info['name'],
|
|
||||||
'frequency': info['frequency'],
|
|
||||||
'mode': info['mode'],
|
|
||||||
'description': info['description'],
|
|
||||||
'active': info['active'],
|
|
||||||
})
|
|
||||||
|
|
||||||
return jsonify({
|
|
||||||
'status': 'ok',
|
|
||||||
'satellites': satellites,
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/start', methods=['POST'])
|
|
||||||
def start_capture():
|
|
||||||
"""Start weather satellite capture and decode.
|
|
||||||
|
|
||||||
JSON body:
|
|
||||||
{
|
|
||||||
"satellite": "NOAA-18", // Required: satellite key
|
|
||||||
"device": 0, // RTL-SDR device index (default: 0)
|
|
||||||
"gain": 40.0, // SDR gain in dB (default: 40)
|
|
||||||
"bias_t": false // Enable bias-T for LNA (default: false)
|
|
||||||
}
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON with start status.
|
|
||||||
"""
|
|
||||||
if not is_weather_sat_available():
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'SatDump not installed. Build from source: https://github.com/SatDump/SatDump'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
decoder = get_weather_sat_decoder()
|
|
||||||
|
|
||||||
if decoder.is_running:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'already_running',
|
|
||||||
'satellite': decoder.current_satellite,
|
|
||||||
'frequency': decoder.current_frequency,
|
|
||||||
})
|
|
||||||
|
|
||||||
data = request.get_json(silent=True) or {}
|
|
||||||
|
|
||||||
# Validate satellite
|
|
||||||
satellite = data.get('satellite')
|
|
||||||
if not satellite or satellite not in WEATHER_SATELLITES:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': f'Invalid satellite. Must be one of: {", ".join(WEATHER_SATELLITES.keys())}'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
# Validate device index and gain
|
|
||||||
try:
|
|
||||||
device_index = validate_device_index(data.get('device', 0))
|
|
||||||
gain = validate_gain(data.get('gain', 40.0))
|
|
||||||
except ValueError as e:
|
|
||||||
logger.warning('Invalid parameter in start_capture: %s', e)
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'Invalid parameter value'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
bias_t = bool(data.get('bias_t', False))
|
|
||||||
|
|
||||||
# Claim SDR device
|
|
||||||
try:
|
|
||||||
import app as app_module
|
|
||||||
error = app_module.claim_sdr_device(device_index, 'weather_sat')
|
|
||||||
if error:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'error_type': 'DEVICE_BUSY',
|
|
||||||
'message': error,
|
|
||||||
}), 409
|
|
||||||
except ImportError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Clear queue
|
|
||||||
while not _weather_sat_queue.empty():
|
|
||||||
try:
|
|
||||||
_weather_sat_queue.get_nowait()
|
|
||||||
except queue.Empty:
|
|
||||||
break
|
|
||||||
|
|
||||||
# Set callback and on-complete handler for SDR release
|
|
||||||
decoder.set_callback(_progress_callback)
|
|
||||||
|
|
||||||
def _release_device():
|
|
||||||
try:
|
|
||||||
import app as app_module
|
|
||||||
app_module.release_sdr_device(device_index)
|
|
||||||
except ImportError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
decoder.set_on_complete(_release_device)
|
|
||||||
|
|
||||||
success = decoder.start(
|
|
||||||
satellite=satellite,
|
|
||||||
device_index=device_index,
|
|
||||||
gain=gain,
|
|
||||||
bias_t=bias_t,
|
|
||||||
)
|
|
||||||
|
|
||||||
if success:
|
|
||||||
sat_info = WEATHER_SATELLITES[satellite]
|
|
||||||
return jsonify({
|
|
||||||
'status': 'started',
|
|
||||||
'satellite': satellite,
|
|
||||||
'frequency': sat_info['frequency'],
|
|
||||||
'mode': sat_info['mode'],
|
|
||||||
'device': device_index,
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
# Release device on failure
|
|
||||||
_release_device()
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'Failed to start capture'
|
|
||||||
}), 500
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/test-decode', methods=['POST'])
|
|
||||||
def test_decode():
|
|
||||||
"""Start weather satellite decode from a pre-recorded file.
|
|
||||||
|
|
||||||
No SDR hardware is required — decodes an IQ baseband or WAV file
|
|
||||||
using SatDump offline mode.
|
|
||||||
|
|
||||||
JSON body:
|
|
||||||
{
|
|
||||||
"satellite": "NOAA-18", // Required: satellite key
|
|
||||||
"input_file": "/path/to/file", // Required: server-side file path
|
|
||||||
"sample_rate": 1000000 // Sample rate in Hz (default: 1000000)
|
|
||||||
}
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON with start status.
|
|
||||||
"""
|
|
||||||
if not is_weather_sat_available():
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'SatDump not installed. Build from source: https://github.com/SatDump/SatDump'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
decoder = get_weather_sat_decoder()
|
|
||||||
|
|
||||||
if decoder.is_running:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'already_running',
|
|
||||||
'satellite': decoder.current_satellite,
|
|
||||||
'frequency': decoder.current_frequency,
|
|
||||||
})
|
|
||||||
|
|
||||||
data = request.get_json(silent=True) or {}
|
|
||||||
|
|
||||||
# Validate satellite
|
|
||||||
satellite = data.get('satellite')
|
|
||||||
if not satellite or satellite not in WEATHER_SATELLITES:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': f'Invalid satellite. Must be one of: {", ".join(WEATHER_SATELLITES.keys())}'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
# Validate input file
|
|
||||||
input_file = data.get('input_file')
|
|
||||||
if not input_file:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'input_file is required'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
input_path = Path(input_file)
|
|
||||||
|
|
||||||
# Security: restrict to data directory (anchored to app root, not CWD)
|
|
||||||
allowed_base = Path(__file__).resolve().parent.parent / 'data'
|
|
||||||
try:
|
|
||||||
resolved = input_path.resolve()
|
|
||||||
if not resolved.is_relative_to(allowed_base):
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'input_file must be under the data/ directory'
|
|
||||||
}), 403
|
|
||||||
except (OSError, ValueError):
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'Invalid file path'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
if not input_path.is_file():
|
|
||||||
logger.warning("Test-decode file not found")
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'File not found'
|
|
||||||
}), 404
|
|
||||||
|
|
||||||
# Validate sample rate
|
|
||||||
sample_rate = data.get('sample_rate', 1000000)
|
|
||||||
try:
|
|
||||||
sample_rate = int(sample_rate)
|
|
||||||
if sample_rate < 1000 or sample_rate > 20000000:
|
|
||||||
raise ValueError
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'Invalid sample_rate (1000-20000000)'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
# Clear queue
|
|
||||||
while not _weather_sat_queue.empty():
|
|
||||||
try:
|
|
||||||
_weather_sat_queue.get_nowait()
|
|
||||||
except queue.Empty:
|
|
||||||
break
|
|
||||||
|
|
||||||
# Set callback — no on_complete needed (no SDR to release)
|
|
||||||
decoder.set_callback(_progress_callback)
|
|
||||||
decoder.set_on_complete(None)
|
|
||||||
|
|
||||||
success = decoder.start_from_file(
|
|
||||||
satellite=satellite,
|
|
||||||
input_file=input_file,
|
|
||||||
sample_rate=sample_rate,
|
|
||||||
)
|
|
||||||
|
|
||||||
if success:
|
|
||||||
sat_info = WEATHER_SATELLITES[satellite]
|
|
||||||
return jsonify({
|
|
||||||
'status': 'started',
|
|
||||||
'satellite': satellite,
|
|
||||||
'frequency': sat_info['frequency'],
|
|
||||||
'mode': sat_info['mode'],
|
|
||||||
'source': 'file',
|
|
||||||
'input_file': str(input_file),
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'Failed to start file decode'
|
|
||||||
}), 500
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/stop', methods=['POST'])
|
|
||||||
def stop_capture():
|
|
||||||
"""Stop weather satellite capture.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON confirmation.
|
|
||||||
"""
|
|
||||||
decoder = get_weather_sat_decoder()
|
|
||||||
device_index = decoder.device_index
|
|
||||||
|
|
||||||
decoder.stop()
|
|
||||||
|
|
||||||
# Release SDR device
|
|
||||||
try:
|
|
||||||
import app as app_module
|
|
||||||
app_module.release_sdr_device(device_index)
|
|
||||||
except ImportError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return jsonify({'status': 'stopped'})
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/images')
|
|
||||||
def list_images():
|
|
||||||
"""Get list of decoded weather satellite images.
|
|
||||||
|
|
||||||
Query parameters:
|
|
||||||
limit: Maximum number of images (default: all)
|
|
||||||
satellite: Filter by satellite key (optional)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON with list of decoded images.
|
|
||||||
"""
|
|
||||||
decoder = get_weather_sat_decoder()
|
|
||||||
images = decoder.get_images()
|
|
||||||
|
|
||||||
# Filter by satellite if specified
|
|
||||||
satellite_filter = request.args.get('satellite')
|
|
||||||
if satellite_filter:
|
|
||||||
images = [img for img in images if img.satellite == satellite_filter]
|
|
||||||
|
|
||||||
# Apply limit
|
|
||||||
limit = request.args.get('limit', type=int)
|
|
||||||
if limit and limit > 0:
|
|
||||||
images = images[-limit:]
|
|
||||||
|
|
||||||
return jsonify({
|
|
||||||
'status': 'ok',
|
|
||||||
'images': [img.to_dict() for img in images],
|
|
||||||
'count': len(images),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/images/<filename>')
|
|
||||||
def get_image(filename: str):
|
|
||||||
"""Serve a decoded weather satellite image file.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
filename: Image filename
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Image file or 404.
|
|
||||||
"""
|
|
||||||
decoder = get_weather_sat_decoder()
|
|
||||||
|
|
||||||
# Security: only allow safe filenames
|
|
||||||
if not filename.replace('_', '').replace('-', '').replace('.', '').isalnum():
|
|
||||||
return jsonify({'status': 'error', 'message': 'Invalid filename'}), 400
|
|
||||||
|
|
||||||
if not (filename.endswith('.png') or filename.endswith('.jpg') or filename.endswith('.jpeg')):
|
|
||||||
return jsonify({'status': 'error', 'message': 'Only PNG/JPG files supported'}), 400
|
|
||||||
|
|
||||||
image_path = decoder._output_dir / filename
|
|
||||||
|
|
||||||
if not image_path.exists():
|
|
||||||
return jsonify({'status': 'error', 'message': 'Image not found'}), 404
|
|
||||||
|
|
||||||
mimetype = 'image/png' if filename.endswith('.png') else 'image/jpeg'
|
|
||||||
return send_file(image_path, mimetype=mimetype)
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/images/<filename>', methods=['DELETE'])
|
|
||||||
def delete_image(filename: str):
|
|
||||||
"""Delete a decoded image.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
filename: Image filename
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON confirmation.
|
|
||||||
"""
|
|
||||||
decoder = get_weather_sat_decoder()
|
|
||||||
|
|
||||||
if not filename.replace('_', '').replace('-', '').replace('.', '').isalnum():
|
|
||||||
return jsonify({'status': 'error', 'message': 'Invalid filename'}), 400
|
|
||||||
|
|
||||||
if decoder.delete_image(filename):
|
|
||||||
return jsonify({'status': 'deleted', 'filename': filename})
|
|
||||||
else:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Image not found'}), 404
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/images', methods=['DELETE'])
|
|
||||||
def delete_all_images():
|
|
||||||
"""Delete all decoded weather satellite images.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON with count of deleted images.
|
|
||||||
"""
|
|
||||||
decoder = get_weather_sat_decoder()
|
|
||||||
count = decoder.delete_all_images()
|
|
||||||
return jsonify({'status': 'ok', 'deleted': count})
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/stream')
|
|
||||||
def stream_progress():
|
|
||||||
"""SSE stream of capture/decode progress.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
SSE stream (text/event-stream)
|
|
||||||
"""
|
|
||||||
response = Response(sse_stream(_weather_sat_queue), mimetype='text/event-stream')
|
|
||||||
response.headers['Cache-Control'] = 'no-cache'
|
|
||||||
response.headers['X-Accel-Buffering'] = 'no'
|
|
||||||
response.headers['Connection'] = 'keep-alive'
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/passes')
|
|
||||||
def get_passes():
|
|
||||||
"""Get upcoming weather satellite passes for observer location.
|
|
||||||
|
|
||||||
Query parameters:
|
|
||||||
latitude: Observer latitude (required)
|
|
||||||
longitude: Observer longitude (required)
|
|
||||||
hours: Hours to predict ahead (default: 24, max: 72)
|
|
||||||
min_elevation: Minimum elevation in degrees (default: 15)
|
|
||||||
trajectory: Include az/el trajectory points (default: false)
|
|
||||||
ground_track: Include lat/lon ground track points (default: false)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON with upcoming passes for all weather satellites.
|
|
||||||
"""
|
|
||||||
include_trajectory = request.args.get('trajectory', 'false').lower() in ('true', '1')
|
|
||||||
include_ground_track = request.args.get('ground_track', 'false').lower() in ('true', '1')
|
|
||||||
|
|
||||||
raw_lat = request.args.get('latitude')
|
|
||||||
raw_lon = request.args.get('longitude')
|
|
||||||
|
|
||||||
if raw_lat is None or raw_lon is None:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'latitude and longitude parameters required'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
try:
|
|
||||||
lat = validate_latitude(raw_lat)
|
|
||||||
lon = validate_longitude(raw_lon)
|
|
||||||
except ValueError as e:
|
|
||||||
logger.warning('Invalid coordinates in get_passes: %s', e)
|
|
||||||
return jsonify({'status': 'error', 'message': 'Invalid coordinates'}), 400
|
|
||||||
|
|
||||||
hours = max(1, min(request.args.get('hours', 24, type=int), 72))
|
|
||||||
min_elevation = max(0, min(request.args.get('min_elevation', 15, type=float), 90))
|
|
||||||
|
|
||||||
try:
|
|
||||||
from utils.weather_sat_predict import predict_passes
|
|
||||||
|
|
||||||
all_passes = predict_passes(
|
|
||||||
lat=lat,
|
|
||||||
lon=lon,
|
|
||||||
hours=hours,
|
|
||||||
min_elevation=min_elevation,
|
|
||||||
include_trajectory=include_trajectory,
|
|
||||||
include_ground_track=include_ground_track,
|
|
||||||
)
|
|
||||||
|
|
||||||
return jsonify({
|
|
||||||
'status': 'ok',
|
|
||||||
'passes': all_passes,
|
|
||||||
'count': len(all_passes),
|
|
||||||
'observer': {'latitude': lat, 'longitude': lon},
|
|
||||||
'prediction_hours': hours,
|
|
||||||
'min_elevation': min_elevation,
|
|
||||||
})
|
|
||||||
|
|
||||||
except ImportError:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'skyfield library not installed'
|
|
||||||
}), 503
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error predicting passes: {e}")
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'Pass prediction failed'
|
|
||||||
}), 500
|
|
||||||
|
|
||||||
|
|
||||||
# ========================
|
|
||||||
# Auto-Scheduler Endpoints
|
|
||||||
# ========================
|
|
||||||
|
|
||||||
|
|
||||||
def _scheduler_event_callback(event: dict) -> None:
|
|
||||||
"""Forward scheduler events to the SSE queue."""
|
|
||||||
try:
|
|
||||||
_weather_sat_queue.put_nowait(event)
|
|
||||||
except queue.Full:
|
|
||||||
try:
|
|
||||||
_weather_sat_queue.get_nowait()
|
|
||||||
_weather_sat_queue.put_nowait(event)
|
|
||||||
except queue.Empty:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/schedule/enable', methods=['POST'])
|
|
||||||
def enable_schedule():
|
|
||||||
"""Enable auto-scheduling of weather satellite captures.
|
|
||||||
|
|
||||||
JSON body:
|
|
||||||
{
|
|
||||||
"latitude": 51.5, // Required
|
|
||||||
"longitude": -0.1, // Required
|
|
||||||
"min_elevation": 15, // Minimum pass elevation (default: 15)
|
|
||||||
"device": 0, // RTL-SDR device index (default: 0)
|
|
||||||
"gain": 40.0, // SDR gain (default: 40)
|
|
||||||
"bias_t": false // Enable bias-T (default: false)
|
|
||||||
}
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON with scheduler status.
|
|
||||||
"""
|
|
||||||
from utils.weather_sat_scheduler import get_weather_sat_scheduler
|
|
||||||
|
|
||||||
data = request.get_json(silent=True) or {}
|
|
||||||
|
|
||||||
if data.get('latitude') is None or data.get('longitude') is None:
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'latitude and longitude required'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
try:
|
|
||||||
lat = validate_latitude(data.get('latitude'))
|
|
||||||
lon = validate_longitude(data.get('longitude'))
|
|
||||||
min_elev = validate_elevation(data.get('min_elevation', 15))
|
|
||||||
device = validate_device_index(data.get('device', 0))
|
|
||||||
gain_val = validate_gain(data.get('gain', 40.0))
|
|
||||||
except ValueError as e:
|
|
||||||
logger.warning('Invalid parameter in enable_schedule: %s', e)
|
|
||||||
return jsonify({
|
|
||||||
'status': 'error',
|
|
||||||
'message': 'Invalid parameter value'
|
|
||||||
}), 400
|
|
||||||
|
|
||||||
scheduler = get_weather_sat_scheduler()
|
|
||||||
scheduler.set_callbacks(_progress_callback, _scheduler_event_callback)
|
|
||||||
|
|
||||||
result = scheduler.enable(
|
|
||||||
lat=lat,
|
|
||||||
lon=lon,
|
|
||||||
min_elevation=min_elev,
|
|
||||||
device=device,
|
|
||||||
gain=gain_val,
|
|
||||||
bias_t=bool(data.get('bias_t', False)),
|
|
||||||
)
|
|
||||||
|
|
||||||
return jsonify({'status': 'ok', **result})
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/schedule/disable', methods=['POST'])
|
|
||||||
def disable_schedule():
|
|
||||||
"""Disable auto-scheduling."""
|
|
||||||
from utils.weather_sat_scheduler import get_weather_sat_scheduler
|
|
||||||
|
|
||||||
scheduler = get_weather_sat_scheduler()
|
|
||||||
result = scheduler.disable()
|
|
||||||
return jsonify(result)
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/schedule/status')
|
|
||||||
def schedule_status():
|
|
||||||
"""Get current scheduler state."""
|
|
||||||
from utils.weather_sat_scheduler import get_weather_sat_scheduler
|
|
||||||
|
|
||||||
scheduler = get_weather_sat_scheduler()
|
|
||||||
return jsonify(scheduler.get_status())
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/schedule/passes')
|
|
||||||
def schedule_passes():
|
|
||||||
"""List scheduled passes."""
|
|
||||||
from utils.weather_sat_scheduler import get_weather_sat_scheduler
|
|
||||||
|
|
||||||
scheduler = get_weather_sat_scheduler()
|
|
||||||
passes = scheduler.get_passes()
|
|
||||||
return jsonify({
|
|
||||||
'status': 'ok',
|
|
||||||
'passes': passes,
|
|
||||||
'count': len(passes),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@weather_sat_bp.route('/schedule/skip/<pass_id>', methods=['POST'])
|
|
||||||
def skip_pass(pass_id: str):
|
|
||||||
"""Skip a scheduled pass."""
|
|
||||||
from utils.weather_sat_scheduler import get_weather_sat_scheduler
|
|
||||||
|
|
||||||
if not pass_id.replace('_', '').replace('-', '').isalnum():
|
|
||||||
return jsonify({'status': 'error', 'message': 'Invalid pass ID'}), 400
|
|
||||||
|
|
||||||
scheduler = get_weather_sat_scheduler()
|
|
||||||
if scheduler.skip_pass(pass_id):
|
|
||||||
return jsonify({'status': 'skipped', 'pass_id': pass_id})
|
|
||||||
else:
|
|
||||||
return jsonify({'status': 'error', 'message': 'Pass not found or already processed'}), 404
|
|
||||||
+5
-66
@@ -21,7 +21,6 @@ from utils.logging import wifi_logger as logger
|
|||||||
from utils.process import is_valid_mac, is_valid_channel
|
from utils.process import is_valid_mac, is_valid_channel
|
||||||
from utils.validation import validate_wifi_channel, validate_mac_address, validate_network_interface
|
from utils.validation import validate_wifi_channel, validate_mac_address, validate_network_interface
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
from data.oui import get_manufacturer
|
from data.oui import get_manufacturer
|
||||||
from utils.constants import (
|
from utils.constants import (
|
||||||
WIFI_TERMINATE_TIMEOUT,
|
WIFI_TERMINATE_TIMEOUT,
|
||||||
@@ -51,31 +50,6 @@ pmkid_process = None
|
|||||||
pmkid_lock = threading.Lock()
|
pmkid_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
def _parse_channel_list(raw_channels: Any) -> list[int] | None:
|
|
||||||
"""Parse a channel list from string/list input."""
|
|
||||||
if raw_channels in (None, '', []):
|
|
||||||
return None
|
|
||||||
|
|
||||||
if isinstance(raw_channels, str):
|
|
||||||
parts = [p.strip() for p in re.split(r'[\s,]+', raw_channels) if p.strip()]
|
|
||||||
elif isinstance(raw_channels, (list, tuple, set)):
|
|
||||||
parts = list(raw_channels)
|
|
||||||
else:
|
|
||||||
parts = [raw_channels]
|
|
||||||
|
|
||||||
channels: list[int] = []
|
|
||||||
seen = set()
|
|
||||||
for part in parts:
|
|
||||||
if part in (None, ''):
|
|
||||||
continue
|
|
||||||
ch = validate_wifi_channel(part)
|
|
||||||
if ch not in seen:
|
|
||||||
channels.append(ch)
|
|
||||||
seen.add(ch)
|
|
||||||
|
|
||||||
return channels or None
|
|
||||||
|
|
||||||
|
|
||||||
def detect_wifi_interfaces():
|
def detect_wifi_interfaces():
|
||||||
"""Detect available WiFi interfaces."""
|
"""Detect available WiFi interfaces."""
|
||||||
interfaces = []
|
interfaces = []
|
||||||
@@ -634,7 +608,6 @@ def start_wifi_scan():
|
|||||||
|
|
||||||
data = request.json
|
data = request.json
|
||||||
channel = data.get('channel')
|
channel = data.get('channel')
|
||||||
channels = data.get('channels')
|
|
||||||
band = data.get('band', 'abg')
|
band = data.get('band', 'abg')
|
||||||
|
|
||||||
# Use provided interface or fall back to stored monitor interface
|
# Use provided interface or fall back to stored monitor interface
|
||||||
@@ -685,16 +658,7 @@ def start_wifi_scan():
|
|||||||
interface
|
interface
|
||||||
]
|
]
|
||||||
|
|
||||||
channel_list = None
|
if channel:
|
||||||
if channels:
|
|
||||||
try:
|
|
||||||
channel_list = _parse_channel_list(channels)
|
|
||||||
except ValueError as e:
|
|
||||||
return jsonify({'status': 'error', 'message': str(e)}), 400
|
|
||||||
|
|
||||||
if channel_list:
|
|
||||||
cmd.extend(['-c', ','.join(str(c) for c in channel_list)])
|
|
||||||
elif channel:
|
|
||||||
cmd.extend(['-c', str(channel)])
|
cmd.extend(['-c', str(channel)])
|
||||||
|
|
||||||
logger.info(f"Running: {' '.join(cmd)}")
|
logger.info(f"Running: {' '.join(cmd)}")
|
||||||
@@ -888,9 +852,6 @@ def check_handshake_status():
|
|||||||
|
|
||||||
file_size = os.path.getsize(capture_file)
|
file_size = os.path.getsize(capture_file)
|
||||||
handshake_found = False
|
handshake_found = False
|
||||||
handshake_valid: bool | None = None
|
|
||||||
handshake_checked = False
|
|
||||||
handshake_reason: str | None = None
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if target_bssid and is_valid_mac(target_bssid):
|
if target_bssid and is_valid_mac(target_bssid):
|
||||||
@@ -901,38 +862,20 @@ def check_handshake_status():
|
|||||||
capture_output=True, text=True, timeout=10
|
capture_output=True, text=True, timeout=10
|
||||||
)
|
)
|
||||||
output = result.stdout + result.stderr
|
output = result.stdout + result.stderr
|
||||||
output_lower = output.lower()
|
if '1 handshake' in output or ('handshake' in output.lower() and 'wpa' in output.lower()):
|
||||||
handshake_checked = True
|
if '0 handshake' not in output:
|
||||||
|
handshake_found = True
|
||||||
if 'no valid wpa handshakes found' in output_lower:
|
|
||||||
handshake_valid = False
|
|
||||||
handshake_reason = 'No valid WPA handshake found'
|
|
||||||
elif '0 handshake' in output_lower:
|
|
||||||
handshake_valid = False
|
|
||||||
elif '1 handshake' in output_lower or ('handshake' in output_lower and 'wpa' in output_lower):
|
|
||||||
handshake_valid = True
|
|
||||||
else:
|
|
||||||
handshake_valid = False
|
|
||||||
except subprocess.TimeoutExpired:
|
except subprocess.TimeoutExpired:
|
||||||
pass
|
pass
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error checking handshake: {e}")
|
logger.error(f"Error checking handshake: {e}")
|
||||||
|
|
||||||
if handshake_valid:
|
|
||||||
handshake_found = True
|
|
||||||
normalized_bssid = target_bssid.upper() if target_bssid else None
|
|
||||||
if normalized_bssid and normalized_bssid not in app_module.wifi_handshakes:
|
|
||||||
app_module.wifi_handshakes.append(normalized_bssid)
|
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'running' if app_module.wifi_process and app_module.wifi_process.poll() is None else 'stopped',
|
'status': 'running' if app_module.wifi_process and app_module.wifi_process.poll() is None else 'stopped',
|
||||||
'file_exists': True,
|
'file_exists': True,
|
||||||
'file_size': file_size,
|
'file_size': file_size,
|
||||||
'file': capture_file,
|
'file': capture_file,
|
||||||
'handshake_found': handshake_found,
|
'handshake_found': handshake_found
|
||||||
'handshake_valid': handshake_valid,
|
|
||||||
'handshake_checked': handshake_checked,
|
|
||||||
'handshake_reason': handshake_reason
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@@ -1143,10 +1086,6 @@ def stream_wifi():
|
|||||||
try:
|
try:
|
||||||
msg = app_module.wifi_queue.get(timeout=1)
|
msg = app_module.wifi_queue.get(timeout=1)
|
||||||
last_keepalive = time.time()
|
last_keepalive = time.time()
|
||||||
try:
|
|
||||||
process_event('wifi', msg, msg.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(msg)
|
yield format_sse(msg)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|||||||
+1
-23
@@ -24,8 +24,6 @@ from utils.wifi import (
|
|||||||
SCAN_MODE_DEEP,
|
SCAN_MODE_DEEP,
|
||||||
)
|
)
|
||||||
from utils.sse import format_sse
|
from utils.sse import format_sse
|
||||||
from utils.validation import validate_wifi_channel
|
|
||||||
from utils.event_pipeline import process_event
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -91,30 +89,15 @@ def start_deep_scan():
|
|||||||
interface: Monitor mode interface (e.g., 'wlan0mon')
|
interface: Monitor mode interface (e.g., 'wlan0mon')
|
||||||
band: Band to scan ('2.4', '5', 'all')
|
band: Band to scan ('2.4', '5', 'all')
|
||||||
channel: Optional specific channel to monitor
|
channel: Optional specific channel to monitor
|
||||||
channels: Optional list or comma-separated channels to monitor
|
|
||||||
"""
|
"""
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
interface = data.get('interface')
|
interface = data.get('interface')
|
||||||
band = data.get('band', 'all')
|
band = data.get('band', 'all')
|
||||||
channel = data.get('channel')
|
channel = data.get('channel')
|
||||||
channels = data.get('channels')
|
|
||||||
|
|
||||||
channel_list = None
|
|
||||||
if channels:
|
|
||||||
if isinstance(channels, str):
|
|
||||||
channel_list = [c.strip() for c in channels.split(',') if c.strip()]
|
|
||||||
elif isinstance(channels, (list, tuple, set)):
|
|
||||||
channel_list = list(channels)
|
|
||||||
else:
|
|
||||||
channel_list = [channels]
|
|
||||||
try:
|
|
||||||
channel_list = [validate_wifi_channel(c) for c in channel_list]
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return jsonify({'error': 'Invalid channels'}), 400
|
|
||||||
|
|
||||||
if channel:
|
if channel:
|
||||||
try:
|
try:
|
||||||
channel = validate_wifi_channel(channel)
|
channel = int(channel)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return jsonify({'error': 'Invalid channel'}), 400
|
return jsonify({'error': 'Invalid channel'}), 400
|
||||||
|
|
||||||
@@ -123,7 +106,6 @@ def start_deep_scan():
|
|||||||
interface=interface,
|
interface=interface,
|
||||||
band=band,
|
band=band,
|
||||||
channel=channel,
|
channel=channel,
|
||||||
channels=channel_list,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
@@ -409,10 +391,6 @@ def event_stream():
|
|||||||
scanner = get_wifi_scanner()
|
scanner = get_wifi_scanner()
|
||||||
|
|
||||||
for event in scanner.get_event_stream():
|
for event in scanner.get_event_stream():
|
||||||
try:
|
|
||||||
process_event('wifi', event, event.get('type'))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
yield format_sse(event)
|
yield format_sse(event)
|
||||||
|
|
||||||
response = Response(generate(), mimetype='text/event-stream')
|
response = Response(generate(), mimetype='text/event-stream')
|
||||||
|
|||||||
@@ -165,7 +165,6 @@ detect_dragonos() {
|
|||||||
# Required tool checks (with alternates)
|
# Required tool checks (with alternates)
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
missing_required=()
|
missing_required=()
|
||||||
missing_recommended=()
|
|
||||||
|
|
||||||
check_required() {
|
check_required() {
|
||||||
local label="$1"; shift
|
local label="$1"; shift
|
||||||
@@ -179,18 +178,6 @@ check_required() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
check_recommended() {
|
|
||||||
local label="$1"; shift
|
|
||||||
local desc="$1"; shift
|
|
||||||
|
|
||||||
if have_any "$@"; then
|
|
||||||
ok "${label} - ${desc}"
|
|
||||||
else
|
|
||||||
warn "${label} - ${desc} (missing, recommended)"
|
|
||||||
missing_recommended+=("$label")
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
check_optional() {
|
check_optional() {
|
||||||
local label="$1"; shift
|
local label="$1"; shift
|
||||||
local desc="$1"; shift
|
local desc="$1"; shift
|
||||||
@@ -217,7 +204,6 @@ check_tools() {
|
|||||||
check_required "dump1090" "ADS-B decoder" dump1090
|
check_required "dump1090" "ADS-B decoder" dump1090
|
||||||
check_required "acarsdec" "ACARS decoder" acarsdec
|
check_required "acarsdec" "ACARS decoder" acarsdec
|
||||||
check_required "AIS-catcher" "AIS vessel decoder" AIS-catcher aiscatcher
|
check_required "AIS-catcher" "AIS vessel decoder" AIS-catcher aiscatcher
|
||||||
check_optional "satdump" "Weather satellite decoder (NOAA/Meteor)" satdump
|
|
||||||
echo
|
echo
|
||||||
info "GPS:"
|
info "GPS:"
|
||||||
check_required "gpsd" "GPS daemon" gpsd
|
check_required "gpsd" "GPS daemon" gpsd
|
||||||
@@ -618,93 +604,8 @@ install_aiscatcher_from_source_macos() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
install_satdump_from_source_debian() {
|
|
||||||
info "Building SatDump v1.2.2 from source (weather satellite decoder)..."
|
|
||||||
|
|
||||||
apt_install build-essential git cmake pkg-config \
|
|
||||||
libpng-dev libtiff-dev libjemalloc-dev libvolk-dev libnng-dev \
|
|
||||||
libzstd-dev libsoapysdr-dev libhackrf-dev liblimesuite-dev \
|
|
||||||
libsqlite3-dev libcurl4-openssl-dev zlib1g-dev libzmq3-dev libfftw3-dev
|
|
||||||
|
|
||||||
# Run in subshell to isolate EXIT trap
|
|
||||||
(
|
|
||||||
tmp_dir="$(mktemp -d)"
|
|
||||||
trap 'rm -rf "$tmp_dir"' EXIT
|
|
||||||
|
|
||||||
info "Cloning SatDump v1.2.2..."
|
|
||||||
git clone --depth 1 --branch 1.2.2 https://github.com/SatDump/SatDump.git "$tmp_dir/SatDump" >/dev/null 2>&1 \
|
|
||||||
|| { warn "Failed to clone SatDump"; exit 1; }
|
|
||||||
|
|
||||||
cd "$tmp_dir/SatDump"
|
|
||||||
mkdir -p build && cd build
|
|
||||||
|
|
||||||
info "Compiling SatDump (this may take a while)..."
|
|
||||||
if cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_GUI=OFF -DCMAKE_INSTALL_LIBDIR=lib .. >/dev/null 2>&1 \
|
|
||||||
&& make -j "$(nproc)" >/dev/null 2>&1; then
|
|
||||||
$SUDO make install >/dev/null 2>&1
|
|
||||||
$SUDO ldconfig
|
|
||||||
|
|
||||||
# Ensure plugins are in the expected path (handles multiarch differences)
|
|
||||||
$SUDO mkdir -p /usr/local/lib/satdump/plugins
|
|
||||||
if [ -z "$(ls /usr/local/lib/satdump/plugins/*.so 2>/dev/null)" ]; then
|
|
||||||
for dir in /usr/local/lib/*/satdump/plugins /usr/lib/*/satdump/plugins /usr/lib/satdump/plugins; do
|
|
||||||
if [ -d "$dir" ] && [ -n "$(ls "$dir"/*.so 2>/dev/null)" ]; then
|
|
||||||
$SUDO ln -sf "$dir"/*.so /usr/local/lib/satdump/plugins/
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
|
|
||||||
ok "SatDump installed successfully."
|
|
||||||
else
|
|
||||||
warn "Failed to build SatDump from source. Weather satellite decoding will not be available."
|
|
||||||
fi
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
install_satdump_from_source_macos() {
|
|
||||||
info "Building SatDump v1.2.2 from source (weather satellite decoder)..."
|
|
||||||
|
|
||||||
brew_install cmake
|
|
||||||
brew_install libpng
|
|
||||||
brew_install libtiff
|
|
||||||
brew_install jemalloc
|
|
||||||
brew_install libvolk
|
|
||||||
brew_install nng
|
|
||||||
brew_install zstd
|
|
||||||
brew_install soapysdr
|
|
||||||
brew_install hackrf
|
|
||||||
brew_install fftw
|
|
||||||
|
|
||||||
# Run in subshell to isolate EXIT trap
|
|
||||||
(
|
|
||||||
tmp_dir="$(mktemp -d)"
|
|
||||||
trap 'rm -rf "$tmp_dir"' EXIT
|
|
||||||
|
|
||||||
info "Cloning SatDump v1.2.2..."
|
|
||||||
git clone --depth 1 --branch 1.2.2 https://github.com/SatDump/SatDump.git "$tmp_dir/SatDump" >/dev/null 2>&1 \
|
|
||||||
|| { warn "Failed to clone SatDump"; exit 1; }
|
|
||||||
|
|
||||||
cd "$tmp_dir/SatDump"
|
|
||||||
mkdir -p build && cd build
|
|
||||||
|
|
||||||
info "Compiling SatDump (this may take a while)..."
|
|
||||||
if cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_GUI=OFF .. >/dev/null 2>&1 \
|
|
||||||
&& make -j "$(sysctl -n hw.ncpu)" >/dev/null 2>&1; then
|
|
||||||
if [[ -w /usr/local/bin ]]; then
|
|
||||||
make install >/dev/null 2>&1
|
|
||||||
else
|
|
||||||
sudo make install >/dev/null 2>&1
|
|
||||||
fi
|
|
||||||
ok "SatDump installed successfully."
|
|
||||||
else
|
|
||||||
warn "Failed to build SatDump from source. Weather satellite decoding will not be available."
|
|
||||||
fi
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
install_macos_packages() {
|
install_macos_packages() {
|
||||||
TOTAL_STEPS=19
|
TOTAL_STEPS=17
|
||||||
CURRENT_STEP=0
|
CURRENT_STEP=0
|
||||||
|
|
||||||
progress "Checking Homebrew"
|
progress "Checking Homebrew"
|
||||||
@@ -781,19 +682,6 @@ install_macos_packages() {
|
|||||||
ok "AIS-catcher already installed"
|
ok "AIS-catcher already installed"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
progress "Installing SatDump (optional)"
|
|
||||||
if ! cmd_exists satdump; then
|
|
||||||
echo
|
|
||||||
info "SatDump is used for weather satellite imagery (NOAA APT & Meteor LRPT)."
|
|
||||||
if ask_yes_no "Do you want to install SatDump?"; then
|
|
||||||
install_satdump_from_source_macos || warn "SatDump build failed. Weather satellite decoding will not be available."
|
|
||||||
else
|
|
||||||
warn "Skipping SatDump installation. You can install it later if needed."
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
ok "SatDump already installed"
|
|
||||||
fi
|
|
||||||
|
|
||||||
progress "Installing aircrack-ng"
|
progress "Installing aircrack-ng"
|
||||||
brew_install aircrack-ng
|
brew_install aircrack-ng
|
||||||
|
|
||||||
@@ -1091,7 +979,7 @@ install_debian_packages() {
|
|||||||
export NEEDRESTART_MODE=a
|
export NEEDRESTART_MODE=a
|
||||||
fi
|
fi
|
||||||
|
|
||||||
TOTAL_STEPS=26
|
TOTAL_STEPS=22
|
||||||
CURRENT_STEP=0
|
CURRENT_STEP=0
|
||||||
|
|
||||||
progress "Updating APT package lists"
|
progress "Updating APT package lists"
|
||||||
@@ -1248,19 +1136,6 @@ install_debian_packages() {
|
|||||||
ok "AIS-catcher already installed"
|
ok "AIS-catcher already installed"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
progress "Installing SatDump (optional)"
|
|
||||||
if ! cmd_exists satdump; then
|
|
||||||
echo
|
|
||||||
info "SatDump is used for weather satellite imagery (NOAA APT & Meteor LRPT)."
|
|
||||||
if ask_yes_no "Do you want to install SatDump?"; then
|
|
||||||
install_satdump_from_source_debian || warn "SatDump build failed. Weather satellite decoding will not be available."
|
|
||||||
else
|
|
||||||
warn "Skipping SatDump installation. You can install it later if needed."
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
ok "SatDump already installed"
|
|
||||||
fi
|
|
||||||
|
|
||||||
progress "Configuring udev rules"
|
progress "Configuring udev rules"
|
||||||
setup_udev_rules_debian
|
setup_udev_rules_debian
|
||||||
|
|
||||||
@@ -1310,14 +1185,6 @@ final_summary_and_hard_fail() {
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "${#missing_recommended[@]}" -gt 0 ]]; then
|
|
||||||
echo
|
|
||||||
warn "Missing RECOMMENDED tools (some features will not work):"
|
|
||||||
for t in "${missing_recommended[@]}"; do echo " - $t"; done
|
|
||||||
echo
|
|
||||||
warn "Install these for full functionality"
|
|
||||||
fi
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
@@ -1364,19 +1231,6 @@ main() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
install_python_deps
|
install_python_deps
|
||||||
|
|
||||||
# Download leaflet-heat plugin (offline mode)
|
|
||||||
if [ ! -f "static/vendor/leaflet-heat/leaflet-heat.js" ]; then
|
|
||||||
info "Downloading leaflet-heat plugin..."
|
|
||||||
mkdir -p static/vendor/leaflet-heat
|
|
||||||
if curl -sL "https://unpkg.com/leaflet.heat@0.2.0/dist/leaflet-heat.js" \
|
|
||||||
-o static/vendor/leaflet-heat/leaflet-heat.js; then
|
|
||||||
ok "leaflet-heat plugin downloaded"
|
|
||||||
else
|
|
||||||
warn "Failed to download leaflet-heat plugin. Heatmap will use CDN."
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
final_summary_and_hard_fail
|
final_summary_and_hard_fail
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,17 +19,6 @@
|
|||||||
min-width: max-content;
|
min-width: max-content;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Strip title badge */
|
|
||||||
.function-strip .strip-title {
|
|
||||||
font-size: 9px;
|
|
||||||
font-weight: 700;
|
|
||||||
letter-spacing: 1.5px;
|
|
||||||
text-transform: uppercase;
|
|
||||||
color: var(--text-muted);
|
|
||||||
white-space: nowrap;
|
|
||||||
padding: 4px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Stats */
|
/* Stats */
|
||||||
.function-strip .strip-stat {
|
.function-strip .strip-stat {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -4201,12 +4201,6 @@ header h1 .tagline {
|
|||||||
color: #000;
|
color: #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bt-detail-btn.active {
|
|
||||||
background: rgba(34, 197, 94, 0.2);
|
|
||||||
border-color: rgba(34, 197, 94, 0.6);
|
|
||||||
color: #9fffd1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Selected device highlight */
|
/* Selected device highlight */
|
||||||
.bt-device-row.selected {
|
.bt-device-row.selected {
|
||||||
background: rgba(0, 212, 255, 0.1);
|
background: rgba(0, 212, 255, 0.1);
|
||||||
@@ -4398,17 +4392,6 @@ header h1 .tagline {
|
|||||||
border: 1px solid rgba(139, 92, 246, 0.3);
|
border: 1px solid rgba(139, 92, 246, 0.3);
|
||||||
}
|
}
|
||||||
|
|
||||||
.bt-history-badge {
|
|
||||||
display: inline-block;
|
|
||||||
padding: 1px 4px;
|
|
||||||
border-radius: 3px;
|
|
||||||
font-size: 8px;
|
|
||||||
font-weight: 600;
|
|
||||||
letter-spacing: 0.2px;
|
|
||||||
background: rgba(34, 197, 94, 0.15);
|
|
||||||
color: #22c55e;
|
|
||||||
}
|
|
||||||
|
|
||||||
.bt-device-name {
|
.bt-device-name {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
|||||||
@@ -196,28 +196,6 @@
|
|||||||
margin-left: 6px;
|
margin-left: 6px;
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
}
|
}
|
||||||
.tracker-badge {
|
|
||||||
margin-left: 6px;
|
|
||||||
font-size: 9px;
|
|
||||||
padding: 1px 4px;
|
|
||||||
border-radius: 3px;
|
|
||||||
background: rgba(255, 51, 102, 0.2);
|
|
||||||
color: #ff3366;
|
|
||||||
border: 1px solid rgba(255, 51, 102, 0.4);
|
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.4px;
|
|
||||||
}
|
|
||||||
.client-badge {
|
|
||||||
margin-left: 6px;
|
|
||||||
font-size: 9px;
|
|
||||||
padding: 1px 4px;
|
|
||||||
border-radius: 3px;
|
|
||||||
background: rgba(74, 158, 255, 0.2);
|
|
||||||
color: #4a9eff;
|
|
||||||
border: 1px solid rgba(74, 158, 255, 0.4);
|
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.4px;
|
|
||||||
}
|
|
||||||
.known-badge {
|
.known-badge {
|
||||||
margin-left: 6px;
|
margin-left: 6px;
|
||||||
font-size: 9px;
|
font-size: 9px;
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -26,9 +26,6 @@
|
|||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
max-width: 600px;
|
max-width: 600px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-height: calc(100vh - 80px);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
position: relative;
|
position: relative;
|
||||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||||
}
|
}
|
||||||
@@ -118,9 +115,6 @@
|
|||||||
|
|
||||||
.settings-section.active {
|
.settings-section.active {
|
||||||
display: block;
|
display: block;
|
||||||
overflow-y: auto;
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.settings-group {
|
.settings-group {
|
||||||
@@ -169,47 +163,6 @@
|
|||||||
color: var(--text-muted, #666);
|
color: var(--text-muted, #666);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Settings Feed Lists */
|
|
||||||
.settings-feed {
|
|
||||||
background: var(--bg-tertiary, #12121f);
|
|
||||||
border: 1px solid var(--border-color, #1a1a2e);
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 8px;
|
|
||||||
max-height: 240px;
|
|
||||||
overflow-y: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.settings-feed-item {
|
|
||||||
padding: 8px;
|
|
||||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
|
||||||
font-size: 11px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.settings-feed-item:last-child {
|
|
||||||
border-bottom: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.settings-feed-title {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--text-primary, #e0e0e0);
|
|
||||||
margin-bottom: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.settings-feed-meta {
|
|
||||||
color: var(--text-muted, #666);
|
|
||||||
font-size: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.settings-feed-empty {
|
|
||||||
color: var(--text-dim, #666);
|
|
||||||
text-align: center;
|
|
||||||
padding: 20px 10px;
|
|
||||||
font-size: 11px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Toggle Switch */
|
/* Toggle Switch */
|
||||||
.toggle-switch {
|
.toggle-switch {
|
||||||
position: relative;
|
position: relative;
|
||||||
|
|||||||
@@ -1,194 +0,0 @@
|
|||||||
const AlertCenter = (function() {
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
let alerts = [];
|
|
||||||
let rules = [];
|
|
||||||
let eventSource = null;
|
|
||||||
|
|
||||||
const TRACKER_RULE_NAME = 'Tracker Detected';
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
loadRules();
|
|
||||||
loadFeed();
|
|
||||||
connect();
|
|
||||||
}
|
|
||||||
|
|
||||||
function connect() {
|
|
||||||
if (eventSource) {
|
|
||||||
eventSource.close();
|
|
||||||
}
|
|
||||||
eventSource = new EventSource('/alerts/stream');
|
|
||||||
eventSource.onmessage = function(e) {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(e.data);
|
|
||||||
if (data.type === 'keepalive') return;
|
|
||||||
handleAlert(data);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[Alerts] SSE parse error', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
eventSource.onerror = function() {
|
|
||||||
console.warn('[Alerts] SSE connection error');
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleAlert(alert) {
|
|
||||||
alerts.unshift(alert);
|
|
||||||
alerts = alerts.slice(0, 50);
|
|
||||||
updateFeedUI();
|
|
||||||
|
|
||||||
if (typeof showNotification === 'function') {
|
|
||||||
const severity = (alert.severity || '').toLowerCase();
|
|
||||||
if (['high', 'critical'].includes(severity)) {
|
|
||||||
showNotification(alert.title || 'Alert', alert.message || 'Alert triggered');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateFeedUI() {
|
|
||||||
const list = document.getElementById('alertsFeedList');
|
|
||||||
const countEl = document.getElementById('alertsFeedCount');
|
|
||||||
if (countEl) countEl.textContent = `(${alerts.length})`;
|
|
||||||
if (!list) return;
|
|
||||||
|
|
||||||
if (alerts.length === 0) {
|
|
||||||
list.innerHTML = '<div class="settings-feed-empty">No alerts yet</div>';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
list.innerHTML = alerts.map(alert => {
|
|
||||||
const title = escapeHtml(alert.title || 'Alert');
|
|
||||||
const message = escapeHtml(alert.message || '');
|
|
||||||
const severity = escapeHtml(alert.severity || 'medium');
|
|
||||||
const createdAt = alert.created_at ? new Date(alert.created_at).toLocaleString() : '';
|
|
||||||
return `
|
|
||||||
<div class="settings-feed-item">
|
|
||||||
<div class="settings-feed-title">
|
|
||||||
<span>${title}</span>
|
|
||||||
<span style="color: var(--text-dim);">${severity.toUpperCase()}</span>
|
|
||||||
</div>
|
|
||||||
<div class="settings-feed-meta">${message}</div>
|
|
||||||
<div class="settings-feed-meta" style="margin-top: 4px;">${createdAt}</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
}).join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadFeed() {
|
|
||||||
fetch('/alerts/events?limit=20')
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(data => {
|
|
||||||
if (data.status === 'success') {
|
|
||||||
alerts = data.events || [];
|
|
||||||
updateFeedUI();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(err => console.error('[Alerts] Load feed failed', err));
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadRules() {
|
|
||||||
fetch('/alerts/rules?all=1')
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(data => {
|
|
||||||
if (data.status === 'success') {
|
|
||||||
rules = data.rules || [];
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(err => console.error('[Alerts] Load rules failed', err));
|
|
||||||
}
|
|
||||||
|
|
||||||
function enableTrackerAlerts() {
|
|
||||||
ensureTrackerRule(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
function disableTrackerAlerts() {
|
|
||||||
ensureTrackerRule(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ensureTrackerRule(enabled) {
|
|
||||||
loadRules();
|
|
||||||
setTimeout(() => {
|
|
||||||
const existing = rules.find(r => r.name === TRACKER_RULE_NAME);
|
|
||||||
if (existing) {
|
|
||||||
fetch(`/alerts/rules/${existing.id}`, {
|
|
||||||
method: 'PATCH',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ enabled })
|
|
||||||
}).then(() => loadRules());
|
|
||||||
} else if (enabled) {
|
|
||||||
fetch('/alerts/rules', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({
|
|
||||||
name: TRACKER_RULE_NAME,
|
|
||||||
mode: 'bluetooth',
|
|
||||||
event_type: 'device_update',
|
|
||||||
match: { is_tracker: true },
|
|
||||||
severity: 'high',
|
|
||||||
enabled: true,
|
|
||||||
notify: { webhook: true }
|
|
||||||
})
|
|
||||||
}).then(() => loadRules());
|
|
||||||
}
|
|
||||||
}, 150);
|
|
||||||
}
|
|
||||||
|
|
||||||
function addBluetoothWatchlist(address, name) {
|
|
||||||
if (!address) return;
|
|
||||||
const existing = rules.find(r => r.mode === 'bluetooth' && r.match && r.match.address === address);
|
|
||||||
if (existing) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
fetch('/alerts/rules', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({
|
|
||||||
name: name ? `Watchlist ${name}` : `Watchlist ${address}`,
|
|
||||||
mode: 'bluetooth',
|
|
||||||
event_type: 'device_update',
|
|
||||||
match: { address: address },
|
|
||||||
severity: 'medium',
|
|
||||||
enabled: true,
|
|
||||||
notify: { webhook: true }
|
|
||||||
})
|
|
||||||
}).then(() => loadRules());
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeBluetoothWatchlist(address) {
|
|
||||||
if (!address) return;
|
|
||||||
const existing = rules.find(r => r.mode === 'bluetooth' && r.match && r.match.address === address);
|
|
||||||
if (!existing) return;
|
|
||||||
fetch(`/alerts/rules/${existing.id}`, { method: 'DELETE' })
|
|
||||||
.then(() => loadRules());
|
|
||||||
}
|
|
||||||
|
|
||||||
function isWatchlisted(address) {
|
|
||||||
return rules.some(r => r.mode === 'bluetooth' && r.match && r.match.address === address && r.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
function escapeHtml(str) {
|
|
||||||
if (!str) return '';
|
|
||||||
return String(str)
|
|
||||||
.replace(/&/g, '&')
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
.replace(/"/g, '"')
|
|
||||||
.replace(/'/g, ''');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
init,
|
|
||||||
loadFeed,
|
|
||||||
enableTrackerAlerts,
|
|
||||||
disableTrackerAlerts,
|
|
||||||
addBluetoothWatchlist,
|
|
||||||
removeBluetoothWatchlist,
|
|
||||||
isWatchlisted,
|
|
||||||
};
|
|
||||||
})();
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
|
||||||
if (typeof AlertCenter !== 'undefined') {
|
|
||||||
AlertCenter.init();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,9 +1,7 @@
|
|||||||
// Shared observer location helper for map-based modules.
|
// Shared observer location helper for map-based modules.
|
||||||
// Default: shared location enabled unless explicitly disabled via config.
|
// Default: shared location enabled unless explicitly disabled via config.
|
||||||
window.ObserverLocation = (function() {
|
window.ObserverLocation = (function() {
|
||||||
const DEFAULT_LOCATION = (window.INTERCEPT_DEFAULT_LAT && window.INTERCEPT_DEFAULT_LON)
|
const DEFAULT_LOCATION = { lat: 51.5074, lon: -0.1278 };
|
||||||
? { lat: window.INTERCEPT_DEFAULT_LAT, lon: window.INTERCEPT_DEFAULT_LON }
|
|
||||||
: { lat: 51.5074, lon: -0.1278 };
|
|
||||||
const SHARED_KEY = 'observerLocation';
|
const SHARED_KEY = 'observerLocation';
|
||||||
const AIS_KEY = 'ais_observerLocation';
|
const AIS_KEY = 'ais_observerLocation';
|
||||||
const LEGACY_LAT_KEY = 'observerLat';
|
const LEGACY_LAT_KEY = 'observerLat';
|
||||||
@@ -43,10 +41,6 @@ window.ObserverLocation = (function() {
|
|||||||
return normalize(lat, lon);
|
return normalize(lat, lon);
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasStoredLocation() {
|
|
||||||
return !!(readKey(SHARED_KEY) || readKey(AIS_KEY) || readLegacyLatLon());
|
|
||||||
}
|
|
||||||
|
|
||||||
function getShared() {
|
function getShared() {
|
||||||
const current = readKey(SHARED_KEY);
|
const current = readKey(SHARED_KEY);
|
||||||
if (current) return current;
|
if (current) return current;
|
||||||
@@ -99,7 +93,6 @@ window.ObserverLocation = (function() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
isSharedEnabled,
|
isSharedEnabled,
|
||||||
hasStoredLocation,
|
|
||||||
getShared,
|
getShared,
|
||||||
setShared,
|
setShared,
|
||||||
getForModule,
|
getForModule,
|
||||||
|
|||||||
@@ -1,136 +0,0 @@
|
|||||||
const RecordingUI = (function() {
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
let recordings = [];
|
|
||||||
let active = [];
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
function refresh() {
|
|
||||||
fetch('/recordings')
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(data => {
|
|
||||||
if (data.status !== 'success') return;
|
|
||||||
recordings = data.recordings || [];
|
|
||||||
active = data.active || [];
|
|
||||||
renderActive();
|
|
||||||
renderRecordings();
|
|
||||||
})
|
|
||||||
.catch(err => console.error('[Recording] Load failed', err));
|
|
||||||
}
|
|
||||||
|
|
||||||
function start() {
|
|
||||||
const modeSelect = document.getElementById('recordingModeSelect');
|
|
||||||
const labelInput = document.getElementById('recordingLabelInput');
|
|
||||||
const mode = modeSelect ? modeSelect.value : '';
|
|
||||||
const label = labelInput ? labelInput.value : '';
|
|
||||||
if (!mode) return;
|
|
||||||
|
|
||||||
fetch('/recordings/start', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ mode, label })
|
|
||||||
})
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(() => {
|
|
||||||
refresh();
|
|
||||||
})
|
|
||||||
.catch(err => console.error('[Recording] Start failed', err));
|
|
||||||
}
|
|
||||||
|
|
||||||
function stop() {
|
|
||||||
const modeSelect = document.getElementById('recordingModeSelect');
|
|
||||||
const mode = modeSelect ? modeSelect.value : '';
|
|
||||||
if (!mode) return;
|
|
||||||
|
|
||||||
fetch('/recordings/stop', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ mode })
|
|
||||||
})
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(() => refresh())
|
|
||||||
.catch(err => console.error('[Recording] Stop failed', err));
|
|
||||||
}
|
|
||||||
|
|
||||||
function stopById(sessionId) {
|
|
||||||
fetch('/recordings/stop', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ id: sessionId })
|
|
||||||
}).then(() => refresh());
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderActive() {
|
|
||||||
const container = document.getElementById('recordingActiveList');
|
|
||||||
if (!container) return;
|
|
||||||
if (!active.length) {
|
|
||||||
container.innerHTML = '<div class="settings-feed-empty">No active recordings</div>';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
container.innerHTML = active.map(session => {
|
|
||||||
return `
|
|
||||||
<div class="settings-feed-item">
|
|
||||||
<div class="settings-feed-title">
|
|
||||||
<span>${escapeHtml(session.mode)}</span>
|
|
||||||
<button class="preset-btn" style="font-size: 9px; padding: 2px 6px;" onclick="RecordingUI.stopById('${session.id}')">Stop</button>
|
|
||||||
</div>
|
|
||||||
<div class="settings-feed-meta">Started: ${new Date(session.started_at).toLocaleString()}</div>
|
|
||||||
<div class="settings-feed-meta">Events: ${session.event_count || 0}</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
}).join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderRecordings() {
|
|
||||||
const container = document.getElementById('recordingList');
|
|
||||||
if (!container) return;
|
|
||||||
if (!recordings.length) {
|
|
||||||
container.innerHTML = '<div class="settings-feed-empty">No recordings yet</div>';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
container.innerHTML = recordings.map(rec => {
|
|
||||||
return `
|
|
||||||
<div class="settings-feed-item">
|
|
||||||
<div class="settings-feed-title">
|
|
||||||
<span>${escapeHtml(rec.mode)}${rec.label ? ` • ${escapeHtml(rec.label)}` : ''}</span>
|
|
||||||
<button class="preset-btn" style="font-size: 9px; padding: 2px 6px;" onclick="RecordingUI.download('${rec.id}')">Download</button>
|
|
||||||
</div>
|
|
||||||
<div class="settings-feed-meta">${new Date(rec.started_at).toLocaleString()}${rec.stopped_at ? ` → ${new Date(rec.stopped_at).toLocaleString()}` : ''}</div>
|
|
||||||
<div class="settings-feed-meta">Events: ${rec.event_count || 0} • ${(rec.size_bytes || 0) / 1024.0 > 0 ? (rec.size_bytes / 1024).toFixed(1) + ' KB' : '0 KB'}</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
}).join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
function download(sessionId) {
|
|
||||||
window.open(`/recordings/${sessionId}/download`, '_blank');
|
|
||||||
}
|
|
||||||
|
|
||||||
function escapeHtml(str) {
|
|
||||||
if (!str) return '';
|
|
||||||
return String(str)
|
|
||||||
.replace(/&/g, '&')
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
.replace(/"/g, '"')
|
|
||||||
.replace(/'/g, ''');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
init,
|
|
||||||
refresh,
|
|
||||||
start,
|
|
||||||
stop,
|
|
||||||
stopById,
|
|
||||||
download,
|
|
||||||
};
|
|
||||||
})();
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
|
||||||
if (typeof RecordingUI !== 'undefined') {
|
|
||||||
RecordingUI.init();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -922,64 +922,5 @@ function switchSettingsTab(tabName) {
|
|||||||
loadUpdateStatus();
|
loadUpdateStatus();
|
||||||
} else if (tabName === 'location') {
|
} else if (tabName === 'location') {
|
||||||
loadObserverLocation();
|
loadObserverLocation();
|
||||||
} else if (tabName === 'alerts') {
|
|
||||||
if (typeof AlertCenter !== 'undefined') {
|
|
||||||
AlertCenter.loadFeed();
|
|
||||||
}
|
|
||||||
} else if (tabName === 'recording') {
|
|
||||||
if (typeof RecordingUI !== 'undefined') {
|
|
||||||
RecordingUI.refresh();
|
|
||||||
}
|
|
||||||
} else if (tabName === 'apikeys') {
|
|
||||||
loadApiKeyStatus();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Load API key status into the API Keys settings tab
|
|
||||||
*/
|
|
||||||
function loadApiKeyStatus() {
|
|
||||||
const badge = document.getElementById('apiKeyStatusBadge');
|
|
||||||
const desc = document.getElementById('apiKeyStatusDesc');
|
|
||||||
const usage = document.getElementById('apiKeyUsageCount');
|
|
||||||
const bar = document.getElementById('apiKeyUsageBar');
|
|
||||||
|
|
||||||
if (!badge) return;
|
|
||||||
|
|
||||||
badge.textContent = 'Not available';
|
|
||||||
badge.className = 'asset-badge missing';
|
|
||||||
desc.textContent = 'GSM feature removed';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Save API key from the settings input
|
|
||||||
*/
|
|
||||||
function saveApiKey() {
|
|
||||||
const input = document.getElementById('apiKeyInput');
|
|
||||||
const result = document.getElementById('apiKeySaveResult');
|
|
||||||
if (!input || !result) return;
|
|
||||||
|
|
||||||
const key = input.value.trim();
|
|
||||||
if (!key) {
|
|
||||||
result.style.display = 'block';
|
|
||||||
result.style.color = 'var(--accent-red)';
|
|
||||||
result.textContent = 'Please enter an API key.';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
result.style.display = 'block';
|
|
||||||
result.style.color = 'var(--text-dim)';
|
|
||||||
result.textContent = 'Saving...';
|
|
||||||
|
|
||||||
result.style.color = 'var(--accent-red)';
|
|
||||||
result.textContent = 'GSM feature has been removed.';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Toggle API key input visibility
|
|
||||||
*/
|
|
||||||
function toggleApiKeyVisibility() {
|
|
||||||
const input = document.getElementById('apiKeyInput');
|
|
||||||
if (!input) return;
|
|
||||||
input.type = input.type === 'password' ? 'text' : 'password';
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -367,9 +367,6 @@ const BluetoothMode = (function() {
|
|||||||
const badgesEl = document.getElementById('btDetailBadges');
|
const badgesEl = document.getElementById('btDetailBadges');
|
||||||
let badgesHtml = `<span class="bt-detail-badge ${protocol}">${protocol.toUpperCase()}</span>`;
|
let badgesHtml = `<span class="bt-detail-badge ${protocol}">${protocol.toUpperCase()}</span>`;
|
||||||
badgesHtml += `<span class="bt-detail-badge ${device.in_baseline ? 'baseline' : 'new'}">${device.in_baseline ? '✓ KNOWN' : '● NEW'}</span>`;
|
badgesHtml += `<span class="bt-detail-badge ${device.in_baseline ? 'baseline' : 'new'}">${device.in_baseline ? '✓ KNOWN' : '● NEW'}</span>`;
|
||||||
if (device.seen_before) {
|
|
||||||
badgesHtml += `<span class="bt-detail-badge flag">SEEN BEFORE</span>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tracker badge
|
// Tracker badge
|
||||||
if (device.is_tracker) {
|
if (device.is_tracker) {
|
||||||
@@ -458,8 +455,6 @@ const BluetoothMode = (function() {
|
|||||||
? new Date(device.last_seen).toLocaleTimeString()
|
? new Date(device.last_seen).toLocaleTimeString()
|
||||||
: '--';
|
: '--';
|
||||||
|
|
||||||
updateWatchlistButton(device);
|
|
||||||
|
|
||||||
// Services
|
// Services
|
||||||
const servicesContainer = document.getElementById('btDetailServices');
|
const servicesContainer = document.getElementById('btDetailServices');
|
||||||
const servicesList = document.getElementById('btDetailServicesList');
|
const servicesList = document.getElementById('btDetailServicesList');
|
||||||
@@ -478,22 +473,6 @@ const BluetoothMode = (function() {
|
|||||||
highlightSelectedDevice(deviceId);
|
highlightSelectedDevice(deviceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Update watchlist button state
|
|
||||||
*/
|
|
||||||
function updateWatchlistButton(device) {
|
|
||||||
const btn = document.getElementById('btDetailWatchBtn');
|
|
||||||
if (!btn) return;
|
|
||||||
if (typeof AlertCenter === 'undefined') {
|
|
||||||
btn.style.display = 'none';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
btn.style.display = '';
|
|
||||||
const watchlisted = AlertCenter.isWatchlisted(device.address);
|
|
||||||
btn.textContent = watchlisted ? 'Watching' : 'Watchlist';
|
|
||||||
btn.classList.toggle('active', watchlisted);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear device selection
|
* Clear device selection
|
||||||
*/
|
*/
|
||||||
@@ -552,7 +531,7 @@ const BluetoothMode = (function() {
|
|||||||
if (!device) return;
|
if (!device) return;
|
||||||
|
|
||||||
navigator.clipboard.writeText(device.address).then(() => {
|
navigator.clipboard.writeText(device.address).then(() => {
|
||||||
const btn = document.getElementById('btDetailCopyBtn');
|
const btn = document.querySelector('.bt-detail-btn');
|
||||||
if (btn) {
|
if (btn) {
|
||||||
const originalText = btn.textContent;
|
const originalText = btn.textContent;
|
||||||
btn.textContent = 'Copied!';
|
btn.textContent = 'Copied!';
|
||||||
@@ -565,25 +544,6 @@ const BluetoothMode = (function() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Toggle Bluetooth watchlist for selected device
|
|
||||||
*/
|
|
||||||
function toggleWatchlist() {
|
|
||||||
if (!selectedDeviceId) return;
|
|
||||||
const device = devices.get(selectedDeviceId);
|
|
||||||
if (!device || typeof AlertCenter === 'undefined') return;
|
|
||||||
|
|
||||||
if (AlertCenter.isWatchlisted(device.address)) {
|
|
||||||
AlertCenter.removeBluetoothWatchlist(device.address);
|
|
||||||
showInfo('Removed from watchlist');
|
|
||||||
} else {
|
|
||||||
AlertCenter.addBluetoothWatchlist(device.address, device.name || device.address);
|
|
||||||
showInfo('Added to watchlist');
|
|
||||||
}
|
|
||||||
|
|
||||||
setTimeout(() => updateWatchlistButton(device), 200);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select a device - opens modal with details
|
* Select a device - opens modal with details
|
||||||
*/
|
*/
|
||||||
@@ -1134,7 +1094,6 @@ const BluetoothMode = (function() {
|
|||||||
const trackerConfidence = device.tracker_confidence;
|
const trackerConfidence = device.tracker_confidence;
|
||||||
const riskScore = device.risk_score || 0;
|
const riskScore = device.risk_score || 0;
|
||||||
const agentName = device._agent || 'Local';
|
const agentName = device._agent || 'Local';
|
||||||
const seenBefore = device.seen_before === true;
|
|
||||||
|
|
||||||
// Calculate RSSI bar width (0-100%)
|
// Calculate RSSI bar width (0-100%)
|
||||||
// RSSI typically ranges from -100 (weak) to -30 (very strong)
|
// RSSI typically ranges from -100 (weak) to -30 (very strong)
|
||||||
@@ -1188,7 +1147,6 @@ const BluetoothMode = (function() {
|
|||||||
let secondaryParts = [addr];
|
let secondaryParts = [addr];
|
||||||
if (mfr) secondaryParts.push(mfr);
|
if (mfr) secondaryParts.push(mfr);
|
||||||
secondaryParts.push('Seen ' + seenCount + '×');
|
secondaryParts.push('Seen ' + seenCount + '×');
|
||||||
if (seenBefore) secondaryParts.push('<span class="bt-history-badge">SEEN BEFORE</span>');
|
|
||||||
// Add agent name if not Local
|
// Add agent name if not Local
|
||||||
if (agentName !== 'Local') {
|
if (agentName !== 'Local') {
|
||||||
secondaryParts.push('<span class="agent-badge agent-remote" style="font-size:8px;padding:1px 4px;">' + escapeHtml(agentName) + '</span>');
|
secondaryParts.push('<span class="agent-badge agent-remote" style="font-size:8px;padding:1px 4px;">' + escapeHtml(agentName) + '</span>');
|
||||||
@@ -1403,7 +1361,6 @@ const BluetoothMode = (function() {
|
|||||||
selectDevice,
|
selectDevice,
|
||||||
clearSelection,
|
clearSelection,
|
||||||
copyAddress,
|
copyAddress,
|
||||||
toggleWatchlist,
|
|
||||||
|
|
||||||
// Agent handling
|
// Agent handling
|
||||||
handleAgentChange,
|
handleAgentChange,
|
||||||
|
|||||||
+12
-408
@@ -10,16 +10,6 @@ let dmrCallCount = 0;
|
|||||||
let dmrSyncCount = 0;
|
let dmrSyncCount = 0;
|
||||||
let dmrCallHistory = [];
|
let dmrCallHistory = [];
|
||||||
let dmrCurrentProtocol = '--';
|
let dmrCurrentProtocol = '--';
|
||||||
let dmrModeLabel = 'dmr'; // Protocol label for device reservation
|
|
||||||
let dmrHasAudio = false;
|
|
||||||
let dmrQualitySamples = [];
|
|
||||||
let dmrQualityScore = null;
|
|
||||||
let dmrSweepInProgress = false;
|
|
||||||
|
|
||||||
// ============== BOOKMARKS ==============
|
|
||||||
let dmrBookmarks = [];
|
|
||||||
const DMR_BOOKMARKS_KEY = 'dmrBookmarks';
|
|
||||||
const DMR_SETTINGS_KEY = 'dmrSettings';
|
|
||||||
|
|
||||||
// ============== SYNTHESIZER STATE ==============
|
// ============== SYNTHESIZER STATE ==============
|
||||||
let dmrSynthCanvas = null;
|
let dmrSynthCanvas = null;
|
||||||
@@ -50,7 +40,6 @@ function checkDmrTools() {
|
|||||||
const missing = [];
|
const missing = [];
|
||||||
if (!data.dsd) missing.push('dsd (Digital Speech Decoder)');
|
if (!data.dsd) missing.push('dsd (Digital Speech Decoder)');
|
||||||
if (!data.rtl_fm) missing.push('rtl_fm (RTL-SDR)');
|
if (!data.rtl_fm) missing.push('rtl_fm (RTL-SDR)');
|
||||||
if (!data.ffmpeg) missing.push('ffmpeg (audio output — optional)');
|
|
||||||
|
|
||||||
if (missing.length > 0) {
|
if (missing.length > 0) {
|
||||||
warning.style.display = 'block';
|
warning.style.display = 'block';
|
||||||
@@ -58,9 +47,6 @@ function checkDmrTools() {
|
|||||||
} else {
|
} else {
|
||||||
warning.style.display = 'none';
|
warning.style.display = 'none';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update audio panel availability
|
|
||||||
updateDmrAudioStatus(data.ffmpeg ? 'OFF' : 'UNAVAILABLE');
|
|
||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -71,39 +57,22 @@ function startDmr() {
|
|||||||
const frequency = parseFloat(document.getElementById('dmrFrequency')?.value || 462.5625);
|
const frequency = parseFloat(document.getElementById('dmrFrequency')?.value || 462.5625);
|
||||||
const protocol = document.getElementById('dmrProtocol')?.value || 'auto';
|
const protocol = document.getElementById('dmrProtocol')?.value || 'auto';
|
||||||
const gain = parseInt(document.getElementById('dmrGain')?.value || 40);
|
const gain = parseInt(document.getElementById('dmrGain')?.value || 40);
|
||||||
const ppm = parseInt(document.getElementById('dmrPPM')?.value || 0);
|
|
||||||
const fineTune = parseInt(document.getElementById('dmrFineTune')?.value || 0);
|
|
||||||
const relaxCrc = document.getElementById('dmrRelaxCrc')?.checked || false;
|
|
||||||
const demod = document.getElementById('dmrDemod')?.value || 'nfm';
|
|
||||||
const device = typeof getSelectedDevice === 'function' ? getSelectedDevice() : 0;
|
const device = typeof getSelectedDevice === 'function' ? getSelectedDevice() : 0;
|
||||||
|
|
||||||
// Use protocol name for device reservation so panel shows "D-STAR", "P25", etc.
|
|
||||||
dmrModeLabel = protocol !== 'auto' ? protocol : 'dmr';
|
|
||||||
|
|
||||||
// Check device availability before starting
|
// Check device availability before starting
|
||||||
if (typeof checkDeviceAvailability === 'function' && !checkDeviceAvailability(dmrModeLabel)) {
|
if (typeof checkDeviceAvailability === 'function' && !checkDeviceAvailability('dmr')) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save settings to localStorage for persistence
|
fetch('/dmr/start', {
|
||||||
try {
|
|
||||||
localStorage.setItem(DMR_SETTINGS_KEY, JSON.stringify({
|
|
||||||
frequency, protocol, gain, ppm, fineTune, relaxCrc, demod
|
|
||||||
}));
|
|
||||||
} catch (e) { /* localStorage unavailable */ }
|
|
||||||
|
|
||||||
return fetch('/dmr/start', {
|
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ frequency, protocol, gain, device, ppm, fineTune, relaxCrc, demod })
|
body: JSON.stringify({ frequency, protocol, gain, device })
|
||||||
})
|
})
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (data.status === 'started') {
|
if (data.status === 'started') {
|
||||||
isDmrRunning = true;
|
isDmrRunning = true;
|
||||||
dmrQualitySamples = [];
|
|
||||||
dmrQualityScore = null;
|
|
||||||
updateDmrQualityUI();
|
|
||||||
dmrCallCount = 0;
|
dmrCallCount = 0;
|
||||||
dmrSyncCount = 0;
|
dmrSyncCount = 0;
|
||||||
dmrCallHistory = [];
|
dmrCallHistory = [];
|
||||||
@@ -117,29 +86,10 @@ function startDmr() {
|
|||||||
const statusEl = document.getElementById('dmrStatus');
|
const statusEl = document.getElementById('dmrStatus');
|
||||||
if (statusEl) statusEl.textContent = 'DECODING';
|
if (statusEl) statusEl.textContent = 'DECODING';
|
||||||
if (typeof reserveDevice === 'function') {
|
if (typeof reserveDevice === 'function') {
|
||||||
reserveDevice(parseInt(device), dmrModeLabel);
|
reserveDevice(parseInt(device), 'dmr');
|
||||||
}
|
}
|
||||||
// Start audio if available
|
|
||||||
dmrHasAudio = !!data.has_audio;
|
|
||||||
if (dmrHasAudio) startDmrAudio();
|
|
||||||
updateDmrAudioStatus(dmrHasAudio ? 'STREAMING' : 'UNAVAILABLE');
|
|
||||||
if (typeof showNotification === 'function') {
|
if (typeof showNotification === 'function') {
|
||||||
showNotification('Digital Voice', `Decoding ${frequency} MHz (${protocol.toUpperCase()})`);
|
showNotification('DMR', `Decoding ${frequency} MHz (${protocol.toUpperCase()})`);
|
||||||
}
|
|
||||||
} else if (data.status === 'error' && data.message === 'Already running') {
|
|
||||||
// Backend has an active session the frontend lost track of — resync
|
|
||||||
isDmrRunning = true;
|
|
||||||
updateDmrUI();
|
|
||||||
connectDmrSSE();
|
|
||||||
if (!dmrSynthInitialized) initDmrSynthesizer();
|
|
||||||
dmrEventType = 'idle';
|
|
||||||
dmrActivityTarget = 0.1;
|
|
||||||
dmrLastEventTime = Date.now();
|
|
||||||
updateDmrSynthStatus();
|
|
||||||
const statusEl = document.getElementById('dmrStatus');
|
|
||||||
if (statusEl) statusEl.textContent = 'DECODING';
|
|
||||||
if (typeof showNotification === 'function') {
|
|
||||||
showNotification('DMR', 'Reconnected to active session');
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (typeof showNotification === 'function') {
|
if (typeof showNotification === 'function') {
|
||||||
@@ -151,24 +101,19 @@ function startDmr() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function stopDmr() {
|
function stopDmr() {
|
||||||
stopDmrAudio();
|
fetch('/dmr/stop', { method: 'POST' })
|
||||||
return fetch('/dmr/stop', { method: 'POST' })
|
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.then(() => {
|
.then(() => {
|
||||||
isDmrRunning = false;
|
isDmrRunning = false;
|
||||||
if (dmrEventSource) { dmrEventSource.close(); dmrEventSource = null; }
|
if (dmrEventSource) { dmrEventSource.close(); dmrEventSource = null; }
|
||||||
dmrQualitySamples = [];
|
|
||||||
dmrQualityScore = null;
|
|
||||||
updateDmrQualityUI();
|
|
||||||
updateDmrUI();
|
updateDmrUI();
|
||||||
dmrEventType = 'stopped';
|
dmrEventType = 'stopped';
|
||||||
dmrActivityTarget = 0;
|
dmrActivityTarget = 0;
|
||||||
updateDmrSynthStatus();
|
updateDmrSynthStatus();
|
||||||
updateDmrAudioStatus('OFF');
|
|
||||||
const statusEl = document.getElementById('dmrStatus');
|
const statusEl = document.getElementById('dmrStatus');
|
||||||
if (statusEl) statusEl.textContent = 'STOPPED';
|
if (statusEl) statusEl.textContent = 'STOPPED';
|
||||||
if (typeof releaseDevice === 'function') {
|
if (typeof releaseDevice === 'function') {
|
||||||
releaseDevice(dmrModeLabel);
|
releaseDevice('dmr');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(err => console.error('[DMR] Stop error:', err));
|
.catch(err => console.error('[DMR] Stop error:', err));
|
||||||
@@ -205,7 +150,6 @@ function handleDmrMessage(msg) {
|
|||||||
const syncCountEl = document.getElementById('dmrSyncCount');
|
const syncCountEl = document.getElementById('dmrSyncCount');
|
||||||
if (syncCountEl) syncCountEl.textContent = dmrSyncCount;
|
if (syncCountEl) syncCountEl.textContent = dmrSyncCount;
|
||||||
} else if (msg.type === 'call') {
|
} else if (msg.type === 'call') {
|
||||||
recordDmrQuality(true);
|
|
||||||
dmrCallCount++;
|
dmrCallCount++;
|
||||||
const countEl = document.getElementById('dmrCallCount');
|
const countEl = document.getElementById('dmrCallCount');
|
||||||
if (countEl) countEl.textContent = dmrCallCount;
|
if (countEl) countEl.textContent = dmrCallCount;
|
||||||
@@ -248,14 +192,8 @@ function handleDmrMessage(msg) {
|
|||||||
|
|
||||||
} else if (msg.type === 'slot') {
|
} else if (msg.type === 'slot') {
|
||||||
// Update slot info in current call
|
// Update slot info in current call
|
||||||
} else if (msg.type === 'frame_ok') {
|
|
||||||
recordDmrQuality(true);
|
|
||||||
} else if (msg.type === 'frame_error') {
|
|
||||||
recordDmrQuality(false);
|
|
||||||
} else if (msg.type === 'raw') {
|
} else if (msg.type === 'raw') {
|
||||||
// Raw DSD output — triggers synthesizer activity via dmrSynthPulse
|
// Raw DSD output — triggers synthesizer activity via dmrSynthPulse
|
||||||
} else if (msg.type === 'voice') {
|
|
||||||
recordDmrQuality(true);
|
|
||||||
} else if (msg.type === 'heartbeat') {
|
} else if (msg.type === 'heartbeat') {
|
||||||
// Decoder is alive and listening — keep synthesizer in listening state
|
// Decoder is alive and listening — keep synthesizer in listening state
|
||||||
if (isDmrRunning && dmrSynthInitialized) {
|
if (isDmrRunning && dmrSynthInitialized) {
|
||||||
@@ -272,137 +210,28 @@ function handleDmrMessage(msg) {
|
|||||||
if (statusEl) statusEl.textContent = 'DECODING';
|
if (statusEl) statusEl.textContent = 'DECODING';
|
||||||
} else if (msg.text === 'crashed') {
|
} else if (msg.text === 'crashed') {
|
||||||
isDmrRunning = false;
|
isDmrRunning = false;
|
||||||
stopDmrAudio();
|
|
||||||
updateDmrUI();
|
updateDmrUI();
|
||||||
dmrEventType = 'stopped';
|
dmrEventType = 'stopped';
|
||||||
dmrActivityTarget = 0;
|
dmrActivityTarget = 0;
|
||||||
updateDmrSynthStatus();
|
updateDmrSynthStatus();
|
||||||
updateDmrAudioStatus('OFF');
|
|
||||||
if (statusEl) statusEl.textContent = 'CRASHED';
|
if (statusEl) statusEl.textContent = 'CRASHED';
|
||||||
if (typeof releaseDevice === 'function') releaseDevice(dmrModeLabel);
|
if (typeof releaseDevice === 'function') releaseDevice('dmr');
|
||||||
const detail = msg.detail || `Decoder exited (code ${msg.exit_code})`;
|
const detail = msg.detail || `Decoder exited (code ${msg.exit_code})`;
|
||||||
if (typeof showNotification === 'function') {
|
if (typeof showNotification === 'function') {
|
||||||
showNotification('DMR Error', detail);
|
showNotification('DMR Error', detail);
|
||||||
}
|
}
|
||||||
} else if (msg.text === 'stopped') {
|
} else if (msg.text === 'stopped') {
|
||||||
isDmrRunning = false;
|
isDmrRunning = false;
|
||||||
stopDmrAudio();
|
|
||||||
updateDmrUI();
|
updateDmrUI();
|
||||||
dmrEventType = 'stopped';
|
dmrEventType = 'stopped';
|
||||||
dmrActivityTarget = 0;
|
dmrActivityTarget = 0;
|
||||||
updateDmrSynthStatus();
|
updateDmrSynthStatus();
|
||||||
updateDmrAudioStatus('OFF');
|
|
||||||
if (statusEl) statusEl.textContent = 'STOPPED';
|
if (statusEl) statusEl.textContent = 'STOPPED';
|
||||||
if (typeof releaseDevice === 'function') releaseDevice(dmrModeLabel);
|
if (typeof releaseDevice === 'function') releaseDevice('dmr');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============== QUALITY METER ==============
|
|
||||||
|
|
||||||
function recordDmrQuality(ok) {
|
|
||||||
dmrQualitySamples.push(!!ok);
|
|
||||||
if (dmrQualitySamples.length > 200) dmrQualitySamples.shift();
|
|
||||||
const total = dmrQualitySamples.length;
|
|
||||||
if (total < 5) {
|
|
||||||
dmrQualityScore = null;
|
|
||||||
updateDmrQualityUI();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const errors = dmrQualitySamples.reduce((sum, v) => sum + (v ? 0 : 1), 0);
|
|
||||||
dmrQualityScore = Math.max(0, Math.min(100, Math.round(100 * (1 - (errors / total)))));
|
|
||||||
updateDmrQualityUI();
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateDmrQualityUI() {
|
|
||||||
const textEl = document.getElementById('dmrQualityText');
|
|
||||||
const barEl = document.getElementById('dmrQualityBar');
|
|
||||||
if (!textEl || !barEl) return;
|
|
||||||
if (dmrQualityScore == null) {
|
|
||||||
textEl.textContent = '--';
|
|
||||||
barEl.style.width = '0%';
|
|
||||||
barEl.style.background = 'var(--text-muted)';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
textEl.textContent = `${dmrQualityScore}%`;
|
|
||||||
barEl.style.width = `${dmrQualityScore}%`;
|
|
||||||
if (dmrQualityScore >= 80) {
|
|
||||||
barEl.style.background = 'var(--accent-green)';
|
|
||||||
} else if (dmrQualityScore >= 50) {
|
|
||||||
barEl.style.background = 'var(--accent-amber, #f59e0b)';
|
|
||||||
} else {
|
|
||||||
barEl.style.background = 'var(--accent-red)';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============== FINE TUNE SWEEP ==============
|
|
||||||
|
|
||||||
async function sweepDmrFineTune() {
|
|
||||||
if (!isDmrRunning) {
|
|
||||||
if (typeof showNotification === 'function') {
|
|
||||||
showNotification('Digital Voice', 'Start the decoder before sweeping fine tune.');
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (dmrSweepInProgress) return;
|
|
||||||
dmrSweepInProgress = true;
|
|
||||||
|
|
||||||
const freqEl = document.getElementById('dmrFrequency');
|
|
||||||
const protoEl = document.getElementById('dmrProtocol');
|
|
||||||
const gainEl = document.getElementById('dmrGain');
|
|
||||||
const ppmEl = document.getElementById('dmrPPM');
|
|
||||||
const fineEl = document.getElementById('dmrFineTune');
|
|
||||||
const crcEl = document.getElementById('dmrRelaxCrc');
|
|
||||||
const demodEl = document.getElementById('dmrDemod');
|
|
||||||
const sweepBtn = document.getElementById('dmrFineTuneSweepBtn');
|
|
||||||
|
|
||||||
const original = {
|
|
||||||
frequency: freqEl?.value,
|
|
||||||
protocol: protoEl?.value,
|
|
||||||
gain: gainEl?.value,
|
|
||||||
ppm: ppmEl?.value,
|
|
||||||
fineTune: fineEl?.value,
|
|
||||||
relaxCrc: crcEl?.checked,
|
|
||||||
demod: demodEl?.value,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (sweepBtn) {
|
|
||||||
sweepBtn.disabled = true;
|
|
||||||
sweepBtn.textContent = 'Sweeping...';
|
|
||||||
}
|
|
||||||
|
|
||||||
const offsets = [-2000, -1500, -1000, -500, 0, 500, 1000, 1500, 2000];
|
|
||||||
let best = { offset: parseInt(original.fineTune || 0, 10) || 0, score: -1 };
|
|
||||||
|
|
||||||
for (const offset of offsets) {
|
|
||||||
if (fineEl) fineEl.value = offset;
|
|
||||||
await stopDmr();
|
|
||||||
await new Promise(r => setTimeout(r, 300));
|
|
||||||
await startDmr();
|
|
||||||
dmrQualitySamples = [];
|
|
||||||
dmrQualityScore = null;
|
|
||||||
updateDmrQualityUI();
|
|
||||||
await new Promise(r => setTimeout(r, 700));
|
|
||||||
await new Promise(r => setTimeout(r, 2500));
|
|
||||||
const score = dmrQualityScore == null ? 0 : dmrQualityScore;
|
|
||||||
if (score > best.score) best = { offset, score };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fineEl) fineEl.value = best.offset;
|
|
||||||
await stopDmr();
|
|
||||||
await new Promise(r => setTimeout(r, 300));
|
|
||||||
await startDmr();
|
|
||||||
|
|
||||||
if (sweepBtn) {
|
|
||||||
sweepBtn.disabled = false;
|
|
||||||
sweepBtn.textContent = 'Sweep Fine Tune';
|
|
||||||
}
|
|
||||||
dmrSweepInProgress = false;
|
|
||||||
if (typeof showNotification === 'function') {
|
|
||||||
showNotification('Digital Voice', `Sweep complete: best offset ${best.offset} Hz (${best.score}%)`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============== UI ==============
|
// ============== UI ==============
|
||||||
|
|
||||||
function updateDmrUI() {
|
function updateDmrUI() {
|
||||||
@@ -477,12 +306,10 @@ function drawDmrSynthesizer() {
|
|||||||
dmrSynthCtx.fillStyle = 'rgba(0, 0, 0, 0.3)';
|
dmrSynthCtx.fillStyle = 'rgba(0, 0, 0, 0.3)';
|
||||||
dmrSynthCtx.fillRect(0, 0, width, height);
|
dmrSynthCtx.fillRect(0, 0, width, height);
|
||||||
|
|
||||||
// Decay activity toward target. Window must exceed the backend
|
// Decay activity toward target
|
||||||
// heartbeat interval (3s) so the status doesn't flip-flop between
|
|
||||||
// LISTENING and IDLE on every heartbeat cycle.
|
|
||||||
const timeSinceEvent = now - dmrLastEventTime;
|
const timeSinceEvent = now - dmrLastEventTime;
|
||||||
if (timeSinceEvent > 5000) {
|
if (timeSinceEvent > 2000) {
|
||||||
// No events for 5s — decay target toward idle
|
// No events for 2s — decay target toward idle
|
||||||
dmrActivityTarget = Math.max(0, dmrActivityTarget - DMR_DECAY_RATE);
|
dmrActivityTarget = Math.max(0, dmrActivityTarget - DMR_DECAY_RATE);
|
||||||
if (dmrActivityTarget < 0.1 && dmrEventType !== 'stopped') {
|
if (dmrActivityTarget < 0.1 && dmrEventType !== 'stopped') {
|
||||||
dmrEventType = 'idle';
|
dmrEventType = 'idle';
|
||||||
@@ -669,232 +496,9 @@ function stopDmrSynthesizer() {
|
|||||||
|
|
||||||
window.addEventListener('resize', resizeDmrSynthesizer);
|
window.addEventListener('resize', resizeDmrSynthesizer);
|
||||||
|
|
||||||
// ============== AUDIO ==============
|
|
||||||
|
|
||||||
function startDmrAudio() {
|
|
||||||
const audioPlayer = document.getElementById('dmrAudioPlayer');
|
|
||||||
if (!audioPlayer) return;
|
|
||||||
const streamUrl = `/dmr/audio/stream?t=${Date.now()}`;
|
|
||||||
audioPlayer.src = streamUrl;
|
|
||||||
const volSlider = document.getElementById('dmrAudioVolume');
|
|
||||||
if (volSlider) audioPlayer.volume = volSlider.value / 100;
|
|
||||||
|
|
||||||
audioPlayer.onplaying = () => updateDmrAudioStatus('STREAMING');
|
|
||||||
audioPlayer.onerror = () => {
|
|
||||||
// Retry if decoder is still running (stream may have dropped)
|
|
||||||
if (isDmrRunning && dmrHasAudio) {
|
|
||||||
console.warn('[DMR] Audio stream error, retrying in 2s...');
|
|
||||||
updateDmrAudioStatus('RECONNECTING');
|
|
||||||
setTimeout(() => {
|
|
||||||
if (isDmrRunning && dmrHasAudio) startDmrAudio();
|
|
||||||
}, 2000);
|
|
||||||
} else {
|
|
||||||
updateDmrAudioStatus('OFF');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
audioPlayer.play().catch(e => {
|
|
||||||
console.warn('[DMR] Audio autoplay blocked:', e);
|
|
||||||
if (typeof showNotification === 'function') {
|
|
||||||
showNotification('Audio Ready', 'Click the page or interact to enable audio playback');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function stopDmrAudio() {
|
|
||||||
const audioPlayer = document.getElementById('dmrAudioPlayer');
|
|
||||||
if (audioPlayer) {
|
|
||||||
audioPlayer.pause();
|
|
||||||
audioPlayer.src = '';
|
|
||||||
}
|
|
||||||
dmrHasAudio = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function setDmrAudioVolume(value) {
|
|
||||||
const audioPlayer = document.getElementById('dmrAudioPlayer');
|
|
||||||
if (audioPlayer) audioPlayer.volume = value / 100;
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateDmrAudioStatus(status) {
|
|
||||||
const el = document.getElementById('dmrAudioStatus');
|
|
||||||
if (!el) return;
|
|
||||||
el.textContent = status;
|
|
||||||
const colors = {
|
|
||||||
'OFF': 'var(--text-muted)',
|
|
||||||
'STREAMING': 'var(--accent-green)',
|
|
||||||
'ERROR': 'var(--accent-red)',
|
|
||||||
'UNAVAILABLE': 'var(--text-muted)',
|
|
||||||
};
|
|
||||||
el.style.color = colors[status] || 'var(--text-muted)';
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============== SETTINGS PERSISTENCE ==============
|
|
||||||
|
|
||||||
function restoreDmrSettings() {
|
|
||||||
try {
|
|
||||||
const saved = localStorage.getItem(DMR_SETTINGS_KEY);
|
|
||||||
if (!saved) return;
|
|
||||||
const s = JSON.parse(saved);
|
|
||||||
const freqEl = document.getElementById('dmrFrequency');
|
|
||||||
const protoEl = document.getElementById('dmrProtocol');
|
|
||||||
const gainEl = document.getElementById('dmrGain');
|
|
||||||
const ppmEl = document.getElementById('dmrPPM');
|
|
||||||
const fineTuneEl = document.getElementById('dmrFineTune');
|
|
||||||
const crcEl = document.getElementById('dmrRelaxCrc');
|
|
||||||
const demodEl = document.getElementById('dmrDemod');
|
|
||||||
if (freqEl && s.frequency != null) freqEl.value = s.frequency;
|
|
||||||
if (protoEl && s.protocol) protoEl.value = s.protocol;
|
|
||||||
if (gainEl && s.gain != null) gainEl.value = s.gain;
|
|
||||||
if (ppmEl && s.ppm != null) ppmEl.value = s.ppm;
|
|
||||||
if (fineTuneEl && s.fineTune != null) fineTuneEl.value = s.fineTune;
|
|
||||||
if (crcEl && s.relaxCrc != null) crcEl.checked = s.relaxCrc;
|
|
||||||
if (demodEl && s.demod) demodEl.value = s.demod;
|
|
||||||
} catch (e) { /* localStorage unavailable */ }
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============== BOOKMARKS ==============
|
|
||||||
|
|
||||||
function loadDmrBookmarks() {
|
|
||||||
try {
|
|
||||||
const saved = localStorage.getItem(DMR_BOOKMARKS_KEY);
|
|
||||||
dmrBookmarks = saved ? JSON.parse(saved) : [];
|
|
||||||
} catch (e) {
|
|
||||||
dmrBookmarks = [];
|
|
||||||
}
|
|
||||||
renderDmrBookmarks();
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveDmrBookmarks() {
|
|
||||||
try {
|
|
||||||
localStorage.setItem(DMR_BOOKMARKS_KEY, JSON.stringify(dmrBookmarks));
|
|
||||||
} catch (e) { /* localStorage unavailable */ }
|
|
||||||
}
|
|
||||||
|
|
||||||
function addDmrBookmark() {
|
|
||||||
const freqInput = document.getElementById('dmrBookmarkFreq');
|
|
||||||
const labelInput = document.getElementById('dmrBookmarkLabel');
|
|
||||||
if (!freqInput) return;
|
|
||||||
|
|
||||||
const freq = parseFloat(freqInput.value);
|
|
||||||
if (isNaN(freq) || freq <= 0) {
|
|
||||||
if (typeof showNotification === 'function') {
|
|
||||||
showNotification('Invalid Frequency', 'Enter a valid frequency');
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const protocol = document.getElementById('dmrProtocol')?.value || 'auto';
|
|
||||||
const label = (labelInput?.value || '').trim() || `${freq.toFixed(4)} MHz`;
|
|
||||||
|
|
||||||
// Duplicate check
|
|
||||||
if (dmrBookmarks.some(b => b.freq === freq && b.protocol === protocol)) {
|
|
||||||
if (typeof showNotification === 'function') {
|
|
||||||
showNotification('Duplicate', 'This frequency/protocol is already bookmarked');
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
dmrBookmarks.push({ freq, protocol, label, added: new Date().toISOString() });
|
|
||||||
saveDmrBookmarks();
|
|
||||||
renderDmrBookmarks();
|
|
||||||
freqInput.value = '';
|
|
||||||
if (labelInput) labelInput.value = '';
|
|
||||||
|
|
||||||
if (typeof showNotification === 'function') {
|
|
||||||
showNotification('Bookmark Added', `${freq.toFixed(4)} MHz saved`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addCurrentDmrFreqBookmark() {
|
|
||||||
const freqEl = document.getElementById('dmrFrequency');
|
|
||||||
const freqInput = document.getElementById('dmrBookmarkFreq');
|
|
||||||
if (freqEl && freqInput) {
|
|
||||||
freqInput.value = freqEl.value;
|
|
||||||
}
|
|
||||||
addDmrBookmark();
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeDmrBookmark(index) {
|
|
||||||
dmrBookmarks.splice(index, 1);
|
|
||||||
saveDmrBookmarks();
|
|
||||||
renderDmrBookmarks();
|
|
||||||
}
|
|
||||||
|
|
||||||
function dmrQuickTune(freq, protocol) {
|
|
||||||
const freqEl = document.getElementById('dmrFrequency');
|
|
||||||
const protoEl = document.getElementById('dmrProtocol');
|
|
||||||
if (freqEl) freqEl.value = freq;
|
|
||||||
if (protoEl) protoEl.value = protocol;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderDmrBookmarks() {
|
|
||||||
const container = document.getElementById('dmrBookmarksList');
|
|
||||||
if (!container) return;
|
|
||||||
|
|
||||||
if (dmrBookmarks.length === 0) {
|
|
||||||
container.innerHTML = '<div style="color: var(--text-muted); text-align: center; padding: 10px; font-size: 11px;">No bookmarks saved</div>';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
container.innerHTML = dmrBookmarks.map((b, i) => `
|
|
||||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 4px 6px; background: rgba(0,0,0,0.2); border-radius: 3px; margin-bottom: 3px;">
|
|
||||||
<span style="cursor: pointer; color: var(--accent-cyan); font-size: 11px; flex: 1;" onclick="dmrQuickTune(${b.freq}, '${b.protocol}')" title="${b.freq.toFixed(4)} MHz (${b.protocol.toUpperCase()})">${b.label}</span>
|
|
||||||
<span style="color: var(--text-muted); font-size: 9px; margin: 0 6px;">${b.protocol.toUpperCase()}</span>
|
|
||||||
<button onclick="removeDmrBookmark(${i})" style="background: none; border: none; color: var(--accent-red); cursor: pointer; font-size: 12px; padding: 0 4px;">×</button>
|
|
||||||
</div>
|
|
||||||
`).join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============== STATUS SYNC ==============
|
|
||||||
|
|
||||||
function checkDmrStatus() {
|
|
||||||
fetch('/dmr/status')
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(data => {
|
|
||||||
if (data.running && !isDmrRunning) {
|
|
||||||
// Backend is running but frontend lost track — resync
|
|
||||||
isDmrRunning = true;
|
|
||||||
updateDmrUI();
|
|
||||||
connectDmrSSE();
|
|
||||||
if (!dmrSynthInitialized) initDmrSynthesizer();
|
|
||||||
dmrEventType = 'idle';
|
|
||||||
dmrActivityTarget = 0.1;
|
|
||||||
dmrLastEventTime = Date.now();
|
|
||||||
updateDmrSynthStatus();
|
|
||||||
const statusEl = document.getElementById('dmrStatus');
|
|
||||||
if (statusEl) statusEl.textContent = 'DECODING';
|
|
||||||
} else if (!data.running && isDmrRunning) {
|
|
||||||
// Backend stopped but frontend didn't know
|
|
||||||
isDmrRunning = false;
|
|
||||||
if (dmrEventSource) { dmrEventSource.close(); dmrEventSource = null; }
|
|
||||||
updateDmrUI();
|
|
||||||
dmrEventType = 'stopped';
|
|
||||||
dmrActivityTarget = 0;
|
|
||||||
updateDmrSynthStatus();
|
|
||||||
const statusEl = document.getElementById('dmrStatus');
|
|
||||||
if (statusEl) statusEl.textContent = 'STOPPED';
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============== INIT ==============
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
|
||||||
restoreDmrSettings();
|
|
||||||
loadDmrBookmarks();
|
|
||||||
});
|
|
||||||
|
|
||||||
// ============== EXPORTS ==============
|
// ============== EXPORTS ==============
|
||||||
|
|
||||||
window.startDmr = startDmr;
|
window.startDmr = startDmr;
|
||||||
window.stopDmr = stopDmr;
|
window.stopDmr = stopDmr;
|
||||||
window.checkDmrTools = checkDmrTools;
|
window.checkDmrTools = checkDmrTools;
|
||||||
window.checkDmrStatus = checkDmrStatus;
|
|
||||||
window.initDmrSynthesizer = initDmrSynthesizer;
|
window.initDmrSynthesizer = initDmrSynthesizer;
|
||||||
window.setDmrAudioVolume = setDmrAudioVolume;
|
|
||||||
window.addDmrBookmark = addDmrBookmark;
|
|
||||||
window.addCurrentDmrFreqBookmark = addCurrentDmrFreqBookmark;
|
|
||||||
window.removeDmrBookmark = removeDmrBookmark;
|
|
||||||
window.dmrQuickTune = dmrQuickTune;
|
|
||||||
window.sweepDmrFineTune = sweepDmrFineTune;
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -11,18 +11,6 @@ const SSTVGeneral = (function() {
|
|||||||
let currentMode = null;
|
let currentMode = null;
|
||||||
let progress = 0;
|
let progress = 0;
|
||||||
|
|
||||||
// Signal scope state
|
|
||||||
let sstvGeneralScopeCtx = null;
|
|
||||||
let sstvGeneralScopeAnim = null;
|
|
||||||
let sstvGeneralScopeHistory = [];
|
|
||||||
const SSTV_GENERAL_SCOPE_LEN = 200;
|
|
||||||
let sstvGeneralScopeRms = 0;
|
|
||||||
let sstvGeneralScopePeak = 0;
|
|
||||||
let sstvGeneralScopeTargetRms = 0;
|
|
||||||
let sstvGeneralScopeTargetPeak = 0;
|
|
||||||
let sstvGeneralScopeMsgBurst = 0;
|
|
||||||
let sstvGeneralScopeTone = null;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize the SSTV General mode
|
* Initialize the SSTV General mode
|
||||||
*/
|
*/
|
||||||
@@ -202,136 +190,6 @@ const SSTVGeneral = (function() {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Initialize signal scope canvas
|
|
||||||
*/
|
|
||||||
function initSstvGeneralScope() {
|
|
||||||
const canvas = document.getElementById('sstvGeneralScopeCanvas');
|
|
||||||
if (!canvas) return;
|
|
||||||
const rect = canvas.getBoundingClientRect();
|
|
||||||
canvas.width = rect.width * (window.devicePixelRatio || 1);
|
|
||||||
canvas.height = rect.height * (window.devicePixelRatio || 1);
|
|
||||||
sstvGeneralScopeCtx = canvas.getContext('2d');
|
|
||||||
sstvGeneralScopeHistory = new Array(SSTV_GENERAL_SCOPE_LEN).fill(0);
|
|
||||||
sstvGeneralScopeRms = 0;
|
|
||||||
sstvGeneralScopePeak = 0;
|
|
||||||
sstvGeneralScopeTargetRms = 0;
|
|
||||||
sstvGeneralScopeTargetPeak = 0;
|
|
||||||
sstvGeneralScopeMsgBurst = 0;
|
|
||||||
sstvGeneralScopeTone = null;
|
|
||||||
drawSstvGeneralScope();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Draw signal scope animation frame
|
|
||||||
*/
|
|
||||||
function drawSstvGeneralScope() {
|
|
||||||
const ctx = sstvGeneralScopeCtx;
|
|
||||||
if (!ctx) return;
|
|
||||||
const W = ctx.canvas.width;
|
|
||||||
const H = ctx.canvas.height;
|
|
||||||
const midY = H / 2;
|
|
||||||
|
|
||||||
// Phosphor persistence
|
|
||||||
ctx.fillStyle = 'rgba(5, 5, 16, 0.3)';
|
|
||||||
ctx.fillRect(0, 0, W, H);
|
|
||||||
|
|
||||||
// Smooth towards target
|
|
||||||
sstvGeneralScopeRms += (sstvGeneralScopeTargetRms - sstvGeneralScopeRms) * 0.25;
|
|
||||||
sstvGeneralScopePeak += (sstvGeneralScopeTargetPeak - sstvGeneralScopePeak) * 0.15;
|
|
||||||
|
|
||||||
// Push to history
|
|
||||||
sstvGeneralScopeHistory.push(Math.min(sstvGeneralScopeRms / 32768, 1.0));
|
|
||||||
if (sstvGeneralScopeHistory.length > SSTV_GENERAL_SCOPE_LEN) sstvGeneralScopeHistory.shift();
|
|
||||||
|
|
||||||
// Grid lines
|
|
||||||
ctx.strokeStyle = 'rgba(60, 40, 80, 0.4)';
|
|
||||||
ctx.lineWidth = 0.5;
|
|
||||||
for (let i = 1; i < 4; i++) {
|
|
||||||
const y = (H / 4) * i;
|
|
||||||
ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke();
|
|
||||||
}
|
|
||||||
for (let i = 1; i < 8; i++) {
|
|
||||||
const x = (W / 8) * i;
|
|
||||||
ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H); ctx.stroke();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Waveform
|
|
||||||
const stepX = W / (SSTV_GENERAL_SCOPE_LEN - 1);
|
|
||||||
ctx.strokeStyle = '#c080ff';
|
|
||||||
ctx.lineWidth = 1.5;
|
|
||||||
ctx.shadowColor = '#c080ff';
|
|
||||||
ctx.shadowBlur = 4;
|
|
||||||
|
|
||||||
// Upper half
|
|
||||||
ctx.beginPath();
|
|
||||||
for (let i = 0; i < sstvGeneralScopeHistory.length; i++) {
|
|
||||||
const x = i * stepX;
|
|
||||||
const amp = sstvGeneralScopeHistory[i] * midY * 0.9;
|
|
||||||
const y = midY - amp;
|
|
||||||
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
|
|
||||||
}
|
|
||||||
ctx.stroke();
|
|
||||||
|
|
||||||
// Lower half (mirror)
|
|
||||||
ctx.beginPath();
|
|
||||||
for (let i = 0; i < sstvGeneralScopeHistory.length; i++) {
|
|
||||||
const x = i * stepX;
|
|
||||||
const amp = sstvGeneralScopeHistory[i] * midY * 0.9;
|
|
||||||
const y = midY + amp;
|
|
||||||
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
|
|
||||||
}
|
|
||||||
ctx.stroke();
|
|
||||||
ctx.shadowBlur = 0;
|
|
||||||
|
|
||||||
// Peak indicator
|
|
||||||
const peakNorm = Math.min(sstvGeneralScopePeak / 32768, 1.0);
|
|
||||||
if (peakNorm > 0.01) {
|
|
||||||
const peakY = midY - peakNorm * midY * 0.9;
|
|
||||||
ctx.strokeStyle = 'rgba(255, 68, 68, 0.6)';
|
|
||||||
ctx.lineWidth = 1;
|
|
||||||
ctx.setLineDash([4, 4]);
|
|
||||||
ctx.beginPath(); ctx.moveTo(0, peakY); ctx.lineTo(W, peakY); ctx.stroke();
|
|
||||||
ctx.setLineDash([]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Image decode flash
|
|
||||||
if (sstvGeneralScopeMsgBurst > 0.01) {
|
|
||||||
ctx.fillStyle = `rgba(0, 255, 100, ${sstvGeneralScopeMsgBurst * 0.15})`;
|
|
||||||
ctx.fillRect(0, 0, W, H);
|
|
||||||
sstvGeneralScopeMsgBurst *= 0.88;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update labels
|
|
||||||
const rmsLabel = document.getElementById('sstvGeneralScopeRmsLabel');
|
|
||||||
const peakLabel = document.getElementById('sstvGeneralScopePeakLabel');
|
|
||||||
const toneLabel = document.getElementById('sstvGeneralScopeToneLabel');
|
|
||||||
const statusLabel = document.getElementById('sstvGeneralScopeStatusLabel');
|
|
||||||
if (rmsLabel) rmsLabel.textContent = Math.round(sstvGeneralScopeRms);
|
|
||||||
if (peakLabel) peakLabel.textContent = Math.round(sstvGeneralScopePeak);
|
|
||||||
if (toneLabel) {
|
|
||||||
if (sstvGeneralScopeTone === 'leader') { toneLabel.textContent = 'LEADER'; toneLabel.style.color = '#0f0'; }
|
|
||||||
else if (sstvGeneralScopeTone === 'sync') { toneLabel.textContent = 'SYNC'; toneLabel.style.color = '#0ff'; }
|
|
||||||
else if (sstvGeneralScopeTone === 'decoding') { toneLabel.textContent = 'DECODING'; toneLabel.style.color = '#fa0'; }
|
|
||||||
else if (sstvGeneralScopeTone === 'noise') { toneLabel.textContent = 'NOISE'; toneLabel.style.color = '#555'; }
|
|
||||||
else { toneLabel.textContent = 'QUIET'; toneLabel.style.color = '#444'; }
|
|
||||||
}
|
|
||||||
if (statusLabel) {
|
|
||||||
if (sstvGeneralScopeRms > 500) { statusLabel.textContent = 'SIGNAL'; statusLabel.style.color = '#0f0'; }
|
|
||||||
else { statusLabel.textContent = 'MONITORING'; statusLabel.style.color = '#555'; }
|
|
||||||
}
|
|
||||||
|
|
||||||
sstvGeneralScopeAnim = requestAnimationFrame(drawSstvGeneralScope);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stop signal scope
|
|
||||||
*/
|
|
||||||
function stopSstvGeneralScope() {
|
|
||||||
if (sstvGeneralScopeAnim) { cancelAnimationFrame(sstvGeneralScopeAnim); sstvGeneralScopeAnim = null; }
|
|
||||||
sstvGeneralScopeCtx = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start SSE stream
|
* Start SSE stream
|
||||||
*/
|
*/
|
||||||
@@ -340,11 +198,6 @@ const SSTVGeneral = (function() {
|
|||||||
eventSource.close();
|
eventSource.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show and init scope
|
|
||||||
const scopePanel = document.getElementById('sstvGeneralScopePanel');
|
|
||||||
if (scopePanel) scopePanel.style.display = 'block';
|
|
||||||
initSstvGeneralScope();
|
|
||||||
|
|
||||||
eventSource = new EventSource('/sstv-general/stream');
|
eventSource = new EventSource('/sstv-general/stream');
|
||||||
|
|
||||||
eventSource.onmessage = (e) => {
|
eventSource.onmessage = (e) => {
|
||||||
@@ -352,10 +205,6 @@ const SSTVGeneral = (function() {
|
|||||||
const data = JSON.parse(e.data);
|
const data = JSON.parse(e.data);
|
||||||
if (data.type === 'sstv_progress') {
|
if (data.type === 'sstv_progress') {
|
||||||
handleProgress(data);
|
handleProgress(data);
|
||||||
} else if (data.type === 'sstv_scope') {
|
|
||||||
sstvGeneralScopeTargetRms = data.rms;
|
|
||||||
sstvGeneralScopeTargetPeak = data.peak;
|
|
||||||
if (data.tone !== undefined) sstvGeneralScopeTone = data.tone;
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to parse SSE message:', err);
|
console.error('Failed to parse SSE message:', err);
|
||||||
@@ -378,9 +227,6 @@ const SSTVGeneral = (function() {
|
|||||||
eventSource.close();
|
eventSource.close();
|
||||||
eventSource = null;
|
eventSource = null;
|
||||||
}
|
}
|
||||||
stopSstvGeneralScope();
|
|
||||||
const scopePanel = document.getElementById('sstvGeneralScopePanel');
|
|
||||||
if (scopePanel) scopePanel.style.display = 'none';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -399,7 +245,6 @@ const SSTVGeneral = (function() {
|
|||||||
renderGallery();
|
renderGallery();
|
||||||
showNotification('SSTV', 'New image decoded!');
|
showNotification('SSTV', 'New image decoded!');
|
||||||
updateStatusUI('listening', 'Listening...');
|
updateStatusUI('listening', 'Listening...');
|
||||||
sstvGeneralScopeMsgBurst = 1.0;
|
|
||||||
// Clear decode progress so signal monitor can take over
|
// Clear decode progress so signal monitor can take over
|
||||||
const liveContent = document.getElementById('sstvGeneralLiveContent');
|
const liveContent = document.getElementById('sstvGeneralLiveContent');
|
||||||
if (liveContent) liveContent.innerHTML = '';
|
if (liveContent) liveContent.innerHTML = '';
|
||||||
|
|||||||
@@ -21,18 +21,6 @@ const SSTV = (function() {
|
|||||||
// ISS frequency
|
// ISS frequency
|
||||||
const ISS_FREQ = 145.800;
|
const ISS_FREQ = 145.800;
|
||||||
|
|
||||||
// Signal scope state
|
|
||||||
let sstvScopeCtx = null;
|
|
||||||
let sstvScopeAnim = null;
|
|
||||||
let sstvScopeHistory = [];
|
|
||||||
const SSTV_SCOPE_LEN = 200;
|
|
||||||
let sstvScopeRms = 0;
|
|
||||||
let sstvScopePeak = 0;
|
|
||||||
let sstvScopeTargetRms = 0;
|
|
||||||
let sstvScopeTargetPeak = 0;
|
|
||||||
let sstvScopeMsgBurst = 0;
|
|
||||||
let sstvScopeTone = null;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize the SSTV mode
|
* Initialize the SSTV mode
|
||||||
*/
|
*/
|
||||||
@@ -646,136 +634,6 @@ const SSTV = (function() {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Initialize signal scope canvas
|
|
||||||
*/
|
|
||||||
function initSstvScope() {
|
|
||||||
const canvas = document.getElementById('sstvScopeCanvas');
|
|
||||||
if (!canvas) return;
|
|
||||||
const rect = canvas.getBoundingClientRect();
|
|
||||||
canvas.width = rect.width * (window.devicePixelRatio || 1);
|
|
||||||
canvas.height = rect.height * (window.devicePixelRatio || 1);
|
|
||||||
sstvScopeCtx = canvas.getContext('2d');
|
|
||||||
sstvScopeHistory = new Array(SSTV_SCOPE_LEN).fill(0);
|
|
||||||
sstvScopeRms = 0;
|
|
||||||
sstvScopePeak = 0;
|
|
||||||
sstvScopeTargetRms = 0;
|
|
||||||
sstvScopeTargetPeak = 0;
|
|
||||||
sstvScopeMsgBurst = 0;
|
|
||||||
sstvScopeTone = null;
|
|
||||||
drawSstvScope();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Draw signal scope animation frame
|
|
||||||
*/
|
|
||||||
function drawSstvScope() {
|
|
||||||
const ctx = sstvScopeCtx;
|
|
||||||
if (!ctx) return;
|
|
||||||
const W = ctx.canvas.width;
|
|
||||||
const H = ctx.canvas.height;
|
|
||||||
const midY = H / 2;
|
|
||||||
|
|
||||||
// Phosphor persistence
|
|
||||||
ctx.fillStyle = 'rgba(5, 5, 16, 0.3)';
|
|
||||||
ctx.fillRect(0, 0, W, H);
|
|
||||||
|
|
||||||
// Smooth towards target
|
|
||||||
sstvScopeRms += (sstvScopeTargetRms - sstvScopeRms) * 0.25;
|
|
||||||
sstvScopePeak += (sstvScopeTargetPeak - sstvScopePeak) * 0.15;
|
|
||||||
|
|
||||||
// Push to history
|
|
||||||
sstvScopeHistory.push(Math.min(sstvScopeRms / 32768, 1.0));
|
|
||||||
if (sstvScopeHistory.length > SSTV_SCOPE_LEN) sstvScopeHistory.shift();
|
|
||||||
|
|
||||||
// Grid lines
|
|
||||||
ctx.strokeStyle = 'rgba(60, 40, 80, 0.4)';
|
|
||||||
ctx.lineWidth = 0.5;
|
|
||||||
for (let i = 1; i < 4; i++) {
|
|
||||||
const y = (H / 4) * i;
|
|
||||||
ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke();
|
|
||||||
}
|
|
||||||
for (let i = 1; i < 8; i++) {
|
|
||||||
const x = (W / 8) * i;
|
|
||||||
ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H); ctx.stroke();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Waveform
|
|
||||||
const stepX = W / (SSTV_SCOPE_LEN - 1);
|
|
||||||
ctx.strokeStyle = '#c080ff';
|
|
||||||
ctx.lineWidth = 1.5;
|
|
||||||
ctx.shadowColor = '#c080ff';
|
|
||||||
ctx.shadowBlur = 4;
|
|
||||||
|
|
||||||
// Upper half
|
|
||||||
ctx.beginPath();
|
|
||||||
for (let i = 0; i < sstvScopeHistory.length; i++) {
|
|
||||||
const x = i * stepX;
|
|
||||||
const amp = sstvScopeHistory[i] * midY * 0.9;
|
|
||||||
const y = midY - amp;
|
|
||||||
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
|
|
||||||
}
|
|
||||||
ctx.stroke();
|
|
||||||
|
|
||||||
// Lower half (mirror)
|
|
||||||
ctx.beginPath();
|
|
||||||
for (let i = 0; i < sstvScopeHistory.length; i++) {
|
|
||||||
const x = i * stepX;
|
|
||||||
const amp = sstvScopeHistory[i] * midY * 0.9;
|
|
||||||
const y = midY + amp;
|
|
||||||
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
|
|
||||||
}
|
|
||||||
ctx.stroke();
|
|
||||||
ctx.shadowBlur = 0;
|
|
||||||
|
|
||||||
// Peak indicator
|
|
||||||
const peakNorm = Math.min(sstvScopePeak / 32768, 1.0);
|
|
||||||
if (peakNorm > 0.01) {
|
|
||||||
const peakY = midY - peakNorm * midY * 0.9;
|
|
||||||
ctx.strokeStyle = 'rgba(255, 68, 68, 0.6)';
|
|
||||||
ctx.lineWidth = 1;
|
|
||||||
ctx.setLineDash([4, 4]);
|
|
||||||
ctx.beginPath(); ctx.moveTo(0, peakY); ctx.lineTo(W, peakY); ctx.stroke();
|
|
||||||
ctx.setLineDash([]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Image decode flash
|
|
||||||
if (sstvScopeMsgBurst > 0.01) {
|
|
||||||
ctx.fillStyle = `rgba(0, 255, 100, ${sstvScopeMsgBurst * 0.15})`;
|
|
||||||
ctx.fillRect(0, 0, W, H);
|
|
||||||
sstvScopeMsgBurst *= 0.88;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update labels
|
|
||||||
const rmsLabel = document.getElementById('sstvScopeRmsLabel');
|
|
||||||
const peakLabel = document.getElementById('sstvScopePeakLabel');
|
|
||||||
const toneLabel = document.getElementById('sstvScopeToneLabel');
|
|
||||||
const statusLabel = document.getElementById('sstvScopeStatusLabel');
|
|
||||||
if (rmsLabel) rmsLabel.textContent = Math.round(sstvScopeRms);
|
|
||||||
if (peakLabel) peakLabel.textContent = Math.round(sstvScopePeak);
|
|
||||||
if (toneLabel) {
|
|
||||||
if (sstvScopeTone === 'leader') { toneLabel.textContent = 'LEADER'; toneLabel.style.color = '#0f0'; }
|
|
||||||
else if (sstvScopeTone === 'sync') { toneLabel.textContent = 'SYNC'; toneLabel.style.color = '#0ff'; }
|
|
||||||
else if (sstvScopeTone === 'decoding') { toneLabel.textContent = 'DECODING'; toneLabel.style.color = '#fa0'; }
|
|
||||||
else if (sstvScopeTone === 'noise') { toneLabel.textContent = 'NOISE'; toneLabel.style.color = '#555'; }
|
|
||||||
else { toneLabel.textContent = 'QUIET'; toneLabel.style.color = '#444'; }
|
|
||||||
}
|
|
||||||
if (statusLabel) {
|
|
||||||
if (sstvScopeRms > 500) { statusLabel.textContent = 'SIGNAL'; statusLabel.style.color = '#0f0'; }
|
|
||||||
else { statusLabel.textContent = 'MONITORING'; statusLabel.style.color = '#555'; }
|
|
||||||
}
|
|
||||||
|
|
||||||
sstvScopeAnim = requestAnimationFrame(drawSstvScope);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stop signal scope
|
|
||||||
*/
|
|
||||||
function stopSstvScope() {
|
|
||||||
if (sstvScopeAnim) { cancelAnimationFrame(sstvScopeAnim); sstvScopeAnim = null; }
|
|
||||||
sstvScopeCtx = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start SSE stream
|
* Start SSE stream
|
||||||
*/
|
*/
|
||||||
@@ -784,11 +642,6 @@ const SSTV = (function() {
|
|||||||
eventSource.close();
|
eventSource.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show and init scope
|
|
||||||
const scopePanel = document.getElementById('sstvScopePanel');
|
|
||||||
if (scopePanel) scopePanel.style.display = 'block';
|
|
||||||
initSstvScope();
|
|
||||||
|
|
||||||
eventSource = new EventSource('/sstv/stream');
|
eventSource = new EventSource('/sstv/stream');
|
||||||
|
|
||||||
eventSource.onmessage = (e) => {
|
eventSource.onmessage = (e) => {
|
||||||
@@ -796,10 +649,6 @@ const SSTV = (function() {
|
|||||||
const data = JSON.parse(e.data);
|
const data = JSON.parse(e.data);
|
||||||
if (data.type === 'sstv_progress') {
|
if (data.type === 'sstv_progress') {
|
||||||
handleProgress(data);
|
handleProgress(data);
|
||||||
} else if (data.type === 'sstv_scope') {
|
|
||||||
sstvScopeTargetRms = data.rms;
|
|
||||||
sstvScopeTargetPeak = data.peak;
|
|
||||||
if (data.tone !== undefined) sstvScopeTone = data.tone;
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to parse SSE message:', err);
|
console.error('Failed to parse SSE message:', err);
|
||||||
@@ -822,9 +671,6 @@ const SSTV = (function() {
|
|||||||
eventSource.close();
|
eventSource.close();
|
||||||
eventSource = null;
|
eventSource = null;
|
||||||
}
|
}
|
||||||
stopSstvScope();
|
|
||||||
const scopePanel = document.getElementById('sstvScopePanel');
|
|
||||||
if (scopePanel) scopePanel.style.display = 'none';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -845,7 +691,6 @@ const SSTV = (function() {
|
|||||||
renderGallery();
|
renderGallery();
|
||||||
showNotification('SSTV', 'New image decoded!');
|
showNotification('SSTV', 'New image decoded!');
|
||||||
updateStatusUI('listening', 'Listening...');
|
updateStatusUI('listening', 'Listening...');
|
||||||
sstvScopeMsgBurst = 1.0;
|
|
||||||
// Clear decode progress so signal monitor can take over
|
// Clear decode progress so signal monitor can take over
|
||||||
const liveContent = document.getElementById('sstvLiveContent');
|
const liveContent = document.getElementById('sstvLiveContent');
|
||||||
if (liveContent) liveContent.innerHTML = '';
|
if (liveContent) liveContent.innerHTML = '';
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+3
-39
@@ -69,40 +69,6 @@ const WiFiMode = (function() {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getChannelPresetList(preset) {
|
|
||||||
switch (preset) {
|
|
||||||
case '2.4-common':
|
|
||||||
return '1,6,11';
|
|
||||||
case '2.4-all':
|
|
||||||
return '1,2,3,4,5,6,7,8,9,10,11,12,13';
|
|
||||||
case '5-low':
|
|
||||||
return '36,40,44,48';
|
|
||||||
case '5-mid':
|
|
||||||
return '52,56,60,64';
|
|
||||||
case '5-high':
|
|
||||||
return '149,153,157,161,165';
|
|
||||||
default:
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildChannelConfig() {
|
|
||||||
const preset = document.getElementById('wifiChannelPreset')?.value || '';
|
|
||||||
const listInput = document.getElementById('wifiChannelList')?.value || '';
|
|
||||||
const singleInput = document.getElementById('wifiChannel')?.value || '';
|
|
||||||
|
|
||||||
const listValue = listInput.trim();
|
|
||||||
const presetValue = getChannelPresetList(preset);
|
|
||||||
|
|
||||||
const channels = listValue || presetValue || '';
|
|
||||||
const channel = channels ? null : (singleInput.trim() ? parseInt(singleInput.trim()) : null);
|
|
||||||
|
|
||||||
return {
|
|
||||||
channels: channels || null,
|
|
||||||
channel: Number.isFinite(channel) ? channel : null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==========================================================================
|
// ==========================================================================
|
||||||
// State
|
// State
|
||||||
// ==========================================================================
|
// ==========================================================================
|
||||||
@@ -497,7 +463,7 @@ const WiFiMode = (function() {
|
|||||||
try {
|
try {
|
||||||
const iface = elements.interfaceSelect?.value || null;
|
const iface = elements.interfaceSelect?.value || null;
|
||||||
const band = document.getElementById('wifiBand')?.value || 'all';
|
const band = document.getElementById('wifiBand')?.value || 'all';
|
||||||
const channelConfig = buildChannelConfig();
|
const channel = document.getElementById('wifiChannel')?.value || null;
|
||||||
const isAgentMode = typeof currentAgent !== 'undefined' && currentAgent !== 'local';
|
const isAgentMode = typeof currentAgent !== 'undefined' && currentAgent !== 'local';
|
||||||
|
|
||||||
let response;
|
let response;
|
||||||
@@ -510,8 +476,7 @@ const WiFiMode = (function() {
|
|||||||
interface: iface,
|
interface: iface,
|
||||||
scan_type: 'deep',
|
scan_type: 'deep',
|
||||||
band: band === 'abg' ? 'all' : band === 'bg' ? '2.4' : '5',
|
band: band === 'abg' ? 'all' : band === 'bg' ? '2.4' : '5',
|
||||||
channel: channelConfig.channel,
|
channel: channel ? parseInt(channel) : null,
|
||||||
channels: channelConfig.channels,
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -521,8 +486,7 @@ const WiFiMode = (function() {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
interface: iface,
|
interface: iface,
|
||||||
band: band === 'abg' ? 'all' : band === 'bg' ? '2.4' : '5',
|
band: band === 'abg' ? 'all' : band === 'bg' ? '2.4' : '5',
|
||||||
channel: channelConfig.channel,
|
channel: channel ? parseInt(channel) : null,
|
||||||
channels: channelConfig.channels,
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
-11
@@ -1,11 +0,0 @@
|
|||||||
/*
|
|
||||||
(c) 2014, Vladimir Agafonkin
|
|
||||||
simpleheat, a tiny JavaScript library for drawing heatmaps with Canvas
|
|
||||||
https://github.com/mourner/simpleheat
|
|
||||||
*/
|
|
||||||
!function(){"use strict";function t(i){return this instanceof t?(this._canvas=i="string"==typeof i?document.getElementById(i):i,this._ctx=i.getContext("2d"),this._width=i.width,this._height=i.height,this._max=1,void this.clear()):new t(i)}t.prototype={defaultRadius:25,defaultGradient:{.4:"blue",.6:"cyan",.7:"lime",.8:"yellow",1:"red"},data:function(t,i){return this._data=t,this},max:function(t){return this._max=t,this},add:function(t){return this._data.push(t),this},clear:function(){return this._data=[],this},radius:function(t,i){i=i||15;var a=this._circle=document.createElement("canvas"),s=a.getContext("2d"),e=this._r=t+i;return a.width=a.height=2*e,s.shadowOffsetX=s.shadowOffsetY=200,s.shadowBlur=i,s.shadowColor="black",s.beginPath(),s.arc(e-200,e-200,t,0,2*Math.PI,!0),s.closePath(),s.fill(),this},gradient:function(t){var i=document.createElement("canvas"),a=i.getContext("2d"),s=a.createLinearGradient(0,0,0,256);i.width=1,i.height=256;for(var e in t)s.addColorStop(e,t[e]);return a.fillStyle=s,a.fillRect(0,0,1,256),this._grad=a.getImageData(0,0,1,256).data,this},draw:function(t){this._circle||this.radius(this.defaultRadius),this._grad||this.gradient(this.defaultGradient);var i=this._ctx;i.clearRect(0,0,this._width,this._height);for(var a,s=0,e=this._data.length;e>s;s++)a=this._data[s],i.globalAlpha=Math.max(a[2]/this._max,t||.05),i.drawImage(this._circle,a[0]-this._r,a[1]-this._r);var n=i.getImageData(0,0,this._width,this._height);return this._colorize(n.data,this._grad),i.putImageData(n,0,0),this},_colorize:function(t,i){for(var a,s=3,e=t.length;e>s;s+=4)a=4*t[s],a&&(t[s-3]=i[a],t[s-2]=i[a+1],t[s-1]=i[a+2])}},window.simpleheat=t}(),/*
|
|
||||||
(c) 2014, Vladimir Agafonkin
|
|
||||||
Leaflet.heat, a tiny and fast heatmap plugin for Leaflet.
|
|
||||||
https://github.com/Leaflet/Leaflet.heat
|
|
||||||
*/
|
|
||||||
L.HeatLayer=(L.Layer?L.Layer:L.Class).extend({initialize:function(t,i){this._latlngs=t,L.setOptions(this,i)},setLatLngs:function(t){return this._latlngs=t,this.redraw()},addLatLng:function(t){return this._latlngs.push(t),this.redraw()},setOptions:function(t){return L.setOptions(this,t),this._heat&&this._updateOptions(),this.redraw()},redraw:function(){return!this._heat||this._frame||this._map._animating||(this._frame=L.Util.requestAnimFrame(this._redraw,this)),this},onAdd:function(t){this._map=t,this._canvas||this._initCanvas(),t._panes.overlayPane.appendChild(this._canvas),t.on("moveend",this._reset,this),t.options.zoomAnimation&&L.Browser.any3d&&t.on("zoomanim",this._animateZoom,this),this._reset()},onRemove:function(t){t.getPanes().overlayPane.removeChild(this._canvas),t.off("moveend",this._reset,this),t.options.zoomAnimation&&t.off("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},_initCanvas:function(){var t=this._canvas=L.DomUtil.create("canvas","leaflet-heatmap-layer leaflet-layer"),i=L.DomUtil.testProp(["transformOrigin","WebkitTransformOrigin","msTransformOrigin"]);t.style[i]="50% 50%";var a=this._map.getSize();t.width=a.x,t.height=a.y;var s=this._map.options.zoomAnimation&&L.Browser.any3d;L.DomUtil.addClass(t,"leaflet-zoom-"+(s?"animated":"hide")),this._heat=simpleheat(t),this._updateOptions()},_updateOptions:function(){this._heat.radius(this.options.radius||this._heat.defaultRadius,this.options.blur),this.options.gradient&&this._heat.gradient(this.options.gradient),this.options.max&&this._heat.max(this.options.max)},_reset:function(){var t=this._map.containerPointToLayerPoint([0,0]);L.DomUtil.setPosition(this._canvas,t);var i=this._map.getSize();this._heat._width!==i.x&&(this._canvas.width=this._heat._width=i.x),this._heat._height!==i.y&&(this._canvas.height=this._heat._height=i.y),this._redraw()},_redraw:function(){var t,i,a,s,e,n,h,o,r,d=[],_=this._heat._r,l=this._map.getSize(),m=new L.Bounds(L.point([-_,-_]),l.add([_,_])),c=void 0===this.options.max?1:this.options.max,u=void 0===this.options.maxZoom?this._map.getMaxZoom():this.options.maxZoom,f=1/Math.pow(2,Math.max(0,Math.min(u-this._map.getZoom(),12))),g=_/2,p=[],v=this._map._getMapPanePos(),w=v.x%g,y=v.y%g;for(t=0,i=this._latlngs.length;i>t;t++)if(a=this._map.latLngToContainerPoint(this._latlngs[t]),m.contains(a)){e=Math.floor((a.x-w)/g)+2,n=Math.floor((a.y-y)/g)+2;var x=void 0!==this._latlngs[t].alt?this._latlngs[t].alt:void 0!==this._latlngs[t][2]?+this._latlngs[t][2]:1;r=x*f,p[n]=p[n]||[],s=p[n][e],s?(s[0]=(s[0]*s[2]+a.x*r)/(s[2]+r),s[1]=(s[1]*s[2]+a.y*r)/(s[2]+r),s[2]+=r):p[n][e]=[a.x,a.y,r]}for(t=0,i=p.length;i>t;t++)if(p[t])for(h=0,o=p[t].length;o>h;h++)s=p[t][h],s&&d.push([Math.round(s[0]),Math.round(s[1]),Math.min(s[2],c)]);this._heat.data(d).draw(this.options.minOpacity),this._frame=null},_animateZoom:function(t){var i=this._map.getZoomScale(t.zoom),a=this._map._getCenterOffset(t.center)._multiplyBy(-i).subtract(this._map._getMapPanePos());L.DomUtil.setTransform?L.DomUtil.setTransform(this._canvas,a,i):this._canvas.style[L.DomUtil.TRANSFORM]=L.DomUtil.getTranslateString(a)+" scale("+i+")"}}),L.heatLayer=function(t,i){return new L.HeatLayer(t,i)};
|
|
||||||
@@ -223,88 +223,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Antenna Guide Panel -->
|
|
||||||
<div class="panel" id="antennaGuidePanel">
|
|
||||||
<div class="panel-header" style="cursor: pointer;" onclick="document.getElementById('antennaGuideContent').style.display = document.getElementById('antennaGuideContent').style.display === 'none' ? 'block' : 'none'; this.querySelector('.panel-toggle').textContent = document.getElementById('antennaGuideContent').style.display === 'none' ? '▶' : '▼';">
|
|
||||||
<span>ANTENNA GUIDE</span>
|
|
||||||
<span class="panel-toggle" style="font-size: 10px; color: var(--text-muted);">▶</span>
|
|
||||||
</div>
|
|
||||||
<div id="antennaGuideContent" style="display: none; padding: 10px; font-size: 11px; color: var(--text-secondary); line-height: 1.5;">
|
|
||||||
<p style="margin-bottom: 8px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
1090 MHz — stock SDR antenna can work but is not ideal
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 4px; padding: 8px; margin-bottom: 8px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 11px;">Stock Telescopic Antenna</strong>
|
|
||||||
<ul style="margin: 4px 0 0 14px; padding: 0; font-size: 10px;">
|
|
||||||
<li><strong style="color: var(--text-primary);">1090 MHz:</strong> Collapse to ~6.9 cm (quarter-wave). It works for nearby aircraft</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Range:</strong> Expect ~50 NM (90 km) indoors, ~100 NM outdoors</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 4px; padding: 8px; margin-bottom: 8px;">
|
|
||||||
<strong style="color: #00ff88; font-size: 11px;">Recommended: 1090 MHz Collinear (~$10-20 DIY)</strong>
|
|
||||||
<ul style="margin: 4px 0 0 14px; padding: 0; font-size: 10px;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Design:</strong> 8 coaxial collinear elements from RG-6 coax cable</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Element length:</strong> ~6.9 cm segments soldered alternating center/shield</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Gain:</strong> ~5–7 dBi omnidirectional, ideal for 360° coverage</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Range:</strong> 150–250+ NM depending on height and LOS</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 4px; padding: 8px; margin-bottom: 8px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 11px;">Commercial Options</strong>
|
|
||||||
<ul style="margin: 4px 0 0 14px; padding: 0; font-size: 10px;">
|
|
||||||
<li><strong style="color: var(--text-primary);">FlightAware antenna:</strong> ~$35, 1090 MHz tuned, 66cm fiberglass whip</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">ADSBexchange whip:</strong> ~$40, similar performance</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Jetvision A3:</strong> ~$50, high-gain 1090 MHz collinear</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 4px; padding: 8px; margin-bottom: 8px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 11px;">Placement & LNA</strong>
|
|
||||||
<ul style="margin: 4px 0 0 14px; padding: 0; font-size: 10px;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Location:</strong> OUTDOORS, as high as possible. Roof or mast mount</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Height:</strong> Every 3m higher adds ~10 NM range (line-of-sight)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">LNA:</strong> 1090 MHz filtered LNA at antenna feed (e.g. Uputronics, ~$30)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Filter:</strong> A 1090 MHz bandpass filter removes cell/FM interference</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Coax:</strong> Keep short. At 1090 MHz, RG-58 loses ~10 dB per 10m</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Bias-T:</strong> Enable Bias-T in controls above if LNA is powered via coax</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 4px; padding: 8px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 11px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 4px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-dim);">ADS-B frequency</td>
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-primary); text-align: right;">1090 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-dim);">Quarter-wave length</td>
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-primary); text-align: right;">6.9 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-dim);">Modulation</td>
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-primary); text-align: right;">PPM (pulse)</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-dim);">Polarization</td>
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-primary); text-align: right;">Vertical</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-dim);">Bandwidth</td>
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-primary); text-align: right;">~2 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-dim);">Typical range (outdoor)</td>
|
|
||||||
<td style="padding: 2px 4px; color: var(--text-primary); text-align: right;">100–250 NM</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Controls Bar - Reorganized -->
|
<!-- Controls Bar - Reorganized -->
|
||||||
|
|||||||
@@ -449,10 +449,7 @@
|
|||||||
devices.forEach((d, i) => {
|
devices.forEach((d, i) => {
|
||||||
const opt = document.createElement('option');
|
const opt = document.createElement('option');
|
||||||
opt.value = d.index;
|
opt.value = d.index;
|
||||||
const sdrType = (d.sdr_type || d.type || 'rtlsdr').toLowerCase();
|
opt.textContent = `SDR ${d.index}: ${d.name}`;
|
||||||
const sdrLabel = sdrType.toUpperCase();
|
|
||||||
opt.dataset.sdrType = sdrType;
|
|
||||||
opt.textContent = `SDR ${d.index} (${sdrLabel}): ${d.name}`;
|
|
||||||
aisSelect.appendChild(opt);
|
aisSelect.appendChild(opt);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -460,23 +457,18 @@
|
|||||||
// Populate DSC device selector
|
// Populate DSC device selector
|
||||||
const dscSelect = document.getElementById('dscDeviceSelect');
|
const dscSelect = document.getElementById('dscDeviceSelect');
|
||||||
dscSelect.innerHTML = '';
|
dscSelect.innerHTML = '';
|
||||||
const dscDevices = devices.filter(d => {
|
if (devices.length === 0) {
|
||||||
const sdrType = (d.sdr_type || d.type || 'rtlsdr').toLowerCase();
|
dscSelect.innerHTML = '<option value="0">No devices</option>';
|
||||||
return sdrType === 'rtlsdr';
|
|
||||||
});
|
|
||||||
if (dscDevices.length === 0) {
|
|
||||||
dscSelect.innerHTML = '<option value="0">No RTL-SDR found</option>';
|
|
||||||
} else {
|
} else {
|
||||||
dscDevices.forEach((d, i) => {
|
devices.forEach((d, i) => {
|
||||||
const opt = document.createElement('option');
|
const opt = document.createElement('option');
|
||||||
opt.value = d.index;
|
opt.value = d.index;
|
||||||
opt.dataset.sdrType = 'rtlsdr';
|
opt.textContent = `SDR ${d.index}: ${d.name}`;
|
||||||
opt.textContent = `SDR ${d.index} (RTLSDR): ${d.name}`;
|
|
||||||
dscSelect.appendChild(opt);
|
dscSelect.appendChild(opt);
|
||||||
});
|
});
|
||||||
// Default to second device if available
|
// Default to second device if available
|
||||||
if (dscDevices.length > 1) {
|
if (devices.length > 1) {
|
||||||
dscSelect.value = dscDevices[1].index;
|
dscSelect.value = devices[1].index;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -554,9 +546,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function startTracking() {
|
function startTracking() {
|
||||||
const aisSelect = document.getElementById('aisDeviceSelect');
|
const device = document.getElementById('aisDeviceSelect').value;
|
||||||
const device = aisSelect.value;
|
|
||||||
const sdrType = (aisSelect.selectedOptions[0]?.dataset?.sdrType || 'rtlsdr').toLowerCase();
|
|
||||||
const gain = document.getElementById('aisGain').value;
|
const gain = document.getElementById('aisGain').value;
|
||||||
|
|
||||||
// Check if using agent mode
|
// Check if using agent mode
|
||||||
@@ -571,7 +561,7 @@
|
|||||||
fetch(`/controller/agents/${aisCurrentAgent}/ais/start`, {
|
fetch(`/controller/agents/${aisCurrentAgent}/ais/start`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ device, gain, bias_t: getBiasTEnabled(), sdr_type: sdrType })
|
body: JSON.stringify({ device, gain, bias_t: getBiasTEnabled() })
|
||||||
})
|
})
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.then(result => {
|
.then(result => {
|
||||||
@@ -596,7 +586,7 @@
|
|||||||
fetch('/ais/start', {
|
fetch('/ais/start', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ device, gain, bias_t: getBiasTEnabled(), sdr_type: sdrType })
|
body: JSON.stringify({ device, gain, bias_t: getBiasTEnabled() })
|
||||||
})
|
})
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
@@ -1180,9 +1170,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function startDscTracking() {
|
function startDscTracking() {
|
||||||
const dscSelect = document.getElementById('dscDeviceSelect');
|
const device = document.getElementById('dscDeviceSelect').value;
|
||||||
const device = dscSelect.value;
|
|
||||||
const sdrType = (dscSelect.selectedOptions[0]?.dataset?.sdrType || 'rtlsdr').toLowerCase();
|
|
||||||
const gain = document.getElementById('dscGain').value;
|
const gain = document.getElementById('dscGain').value;
|
||||||
|
|
||||||
// Check if using agent mode
|
// Check if using agent mode
|
||||||
@@ -1197,7 +1185,7 @@
|
|||||||
fetch(endpoint, {
|
fetch(endpoint, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ device, gain, sdr_type: sdrType })
|
body: JSON.stringify({ device, gain })
|
||||||
})
|
})
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
@@ -1629,32 +1617,21 @@
|
|||||||
const aisSelect = document.getElementById('aisDeviceSelect');
|
const aisSelect = document.getElementById('aisDeviceSelect');
|
||||||
const dscSelect = document.getElementById('dscDeviceSelect');
|
const dscSelect = document.getElementById('dscDeviceSelect');
|
||||||
|
|
||||||
const aisDevices = devices || [];
|
[aisSelect, dscSelect].forEach(select => {
|
||||||
const dscDevices = aisDevices.filter(device => {
|
|
||||||
const sdrType = (device.sdr_type || device.type || 'rtlsdr').toLowerCase();
|
|
||||||
return sdrType === 'rtlsdr';
|
|
||||||
});
|
|
||||||
|
|
||||||
const fillSelect = (select, list, emptyLabel) => {
|
|
||||||
if (!select) return;
|
if (!select) return;
|
||||||
select.innerHTML = '';
|
select.innerHTML = '';
|
||||||
if (list.length === 0) {
|
|
||||||
select.innerHTML = `<option value=\"0\">${emptyLabel}</option>`;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
list.forEach(device => {
|
|
||||||
const opt = document.createElement('option');
|
|
||||||
const sdrType = (device.sdr_type || device.type || 'rtlsdr').toLowerCase();
|
|
||||||
const sdrLabel = sdrType.toUpperCase();
|
|
||||||
opt.value = device.index;
|
|
||||||
opt.dataset.sdrType = sdrType;
|
|
||||||
opt.textContent = `Device ${device.index} (${sdrLabel}): ${device.name || device.type || 'SDR'}`;
|
|
||||||
select.appendChild(opt);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
fillSelect(aisSelect, aisDevices, 'No SDR found');
|
if (devices.length === 0) {
|
||||||
fillSelect(dscSelect, dscDevices, 'No RTL-SDR found');
|
select.innerHTML = '<option value="0">No SDR found</option>';
|
||||||
|
} else {
|
||||||
|
devices.forEach(device => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = device.index;
|
||||||
|
opt.textContent = `Device ${device.index}: ${device.name || device.type || 'SDR'}`;
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Override startTracking for agent support
|
// Override startTracking for agent support
|
||||||
@@ -1668,15 +1645,13 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const aisSelect = document.getElementById('aisDeviceSelect');
|
const device = document.getElementById('aisDeviceSelect').value;
|
||||||
const device = aisSelect.value;
|
|
||||||
const sdrType = (aisSelect.selectedOptions[0]?.dataset?.sdrType || 'rtlsdr').toLowerCase();
|
|
||||||
const gain = document.getElementById('aisGain').value;
|
const gain = document.getElementById('aisGain').value;
|
||||||
|
|
||||||
fetch(`/controller/agents/${aisCurrentAgent}/ais/start`, {
|
fetch(`/controller/agents/${aisCurrentAgent}/ais/start`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ device, gain, bias_t: getBiasTEnabled(), sdr_type: sdrType })
|
body: JSON.stringify({ device, gain, bias_t: getBiasTEnabled() })
|
||||||
})
|
})
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
|
|||||||
+49
-885
File diff suppressed because it is too large
Load Diff
@@ -26,75 +26,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Antenna Guide -->
|
|
||||||
<div class="section">
|
|
||||||
<h3>Antenna Guide</h3>
|
|
||||||
<div style="font-size: 11px; color: var(--text-dim); line-height: 1.5;">
|
|
||||||
<p style="margin-bottom: 8px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
Marine VHF band (162 MHz) — stock SDR antenna will NOT work well
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Simple Dipole (Cheapest)</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Element length:</strong> ~46 cm each (quarter-wave at 162 MHz)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Material:</strong> Wire, coat hanger, or copper rod</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Orientation:</strong> Vertical (AIS is vertically polarized)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Placement:</strong> As high as possible with clear view of the water/harbor</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Commercial Options</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Marine VHF whip:</strong> ~$20–50, designed for 156–163 MHz band</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Discone:</strong> ~$30–50, wideband coverage including marine VHF</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Collinear:</strong> Higher gain (~6 dBi), best for coastal monitoring</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Placement Tips</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Height is critical:</strong> AIS is line-of-sight. Roof or mast mount is ideal</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Range:</strong> At 10m height, expect ~25 NM (46 km) range over water</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">LNA:</strong> Nooelec Lana or similar broadband LNA, mount at antenna</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Coax:</strong> Keep cable short. RG-58 loses ~4 dB per 10m at 162 MHz</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 6px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">AIS Channel A</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">161.975 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">AIS Channel B</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">162.025 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Quarter-wave length</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">46 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Modulation</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">GMSK 9600 baud</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Bandwidth</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">25 kHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Polarization</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">Vertical</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button class="run-btn" id="startAisBtn" onclick="startAisTracking()">
|
<button class="run-btn" id="startAisBtn" onclick="startAisTracking()">
|
||||||
Start AIS Tracking
|
Start AIS Tracking
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -13,59 +13,4 @@
|
|||||||
<span style="color: var(--accent-cyan);">Controls in function bar above map</span>
|
<span style="color: var(--accent-cyan);">Controls in function bar above map</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Antenna Guide -->
|
|
||||||
<div class="section">
|
|
||||||
<h3>Antenna Guide</h3>
|
|
||||||
<div style="font-size: 11px; color: var(--text-dim); line-height: 1.5;">
|
|
||||||
<p style="margin-bottom: 8px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
2m band (144–148 MHz) — stock SDR antenna will NOT work
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Simple Dipole (Easiest)</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Element length:</strong> ~51.5 cm each (quarter-wave at 144.39 MHz)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Material:</strong> Wire, coat hanger, or copper rod</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Orientation:</strong> Vertical (APRS is FM, vertically polarized)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Connection:</strong> Center conductor to one element, shield to the other</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Commercial Options</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Mag-mount 2m whip:</strong> ~$15–25, good mobile/portable option</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">2m/70cm dual-band:</strong> ~$20–40, also covers 70cm ham band</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Discone:</strong> ~$30–50, wideband but lower gain on 2m</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 6px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">APRS freq (N. America)</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">144.390 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">APRS freq (Europe)</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">144.800 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Quarter-wave length</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">51.5 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Modulation</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">FM 1200 baud</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Polarization</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">Vertical</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -21,77 +21,17 @@
|
|||||||
<select id="dmrProtocol">
|
<select id="dmrProtocol">
|
||||||
<option value="auto" selected>Auto Detect</option>
|
<option value="auto" selected>Auto Detect</option>
|
||||||
<option value="dmr">DMR</option>
|
<option value="dmr">DMR</option>
|
||||||
<option value="p25">P25 Phase 1</option>
|
<option value="p25">P25</option>
|
||||||
<option value="p25p2">P25 Phase 2</option>
|
|
||||||
<option value="nxdn">NXDN</option>
|
<option value="nxdn">NXDN</option>
|
||||||
<option value="dstar">D-STAR</option>
|
<option value="dstar">D-STAR</option>
|
||||||
<option value="provoice">ProVoice</option>
|
<option value="provoice">ProVoice</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Demodulation</label>
|
|
||||||
<select id="dmrDemod">
|
|
||||||
<option value="nfm" selected>NFM (recommended)</option>
|
|
||||||
<option value="fm">FM (wide)</option>
|
|
||||||
</select>
|
|
||||||
<span style="font-size: 0.75em; color: var(--text-muted); display: block; margin-top: 2px;">
|
|
||||||
Narrow FM often improves digital voice decode on 12.5 kHz channels.
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>Gain</label>
|
<label>Gain</label>
|
||||||
<input type="number" id="dmrGain" value="40" min="0" max="50" style="width: 100%;">
|
<input type="number" id="dmrGain" value="40" min="0" max="50" style="width: 100%;">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-group">
|
|
||||||
<label>PPM Correction</label>
|
|
||||||
<input type="number" id="dmrPPM" value="0" min="-200" max="200" step="1" style="width: 100%;"
|
|
||||||
title="Frequency error correction for your RTL-SDR dongle. Digital voice is very sensitive to frequency offset.">
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Fine Tune (Hz)</label>
|
|
||||||
<input type="number" id="dmrFineTune" value="0" min="-5000" max="5000" step="100" style="width: 100%;"
|
|
||||||
title="Offset the tuned frequency by a small amount without changing PPM.">
|
|
||||||
<span style="font-size: 0.75em; color: var(--text-muted); display: block; margin-top: 2px;">
|
|
||||||
Adjust in 100 Hz steps; small offsets can dramatically improve P25 decode.
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<button class="preset-btn" id="dmrFineTuneSweepBtn" onclick="sweepDmrFineTune()" style="width: 100%; margin-top: 6px;">
|
|
||||||
Sweep Fine Tune
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div class="form-group" style="margin-top: 4px;">
|
|
||||||
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
|
|
||||||
<input type="checkbox" id="dmrRelaxCrc" style="width: auto; accent-color: var(--accent-cyan);">
|
|
||||||
<span>Relax CRC (weak signals)</span>
|
|
||||||
</label>
|
|
||||||
<span style="font-size: 0.75em; color: var(--text-muted); display: block; margin-top: 2px;">
|
|
||||||
Allows more frames through on marginal signals at the cost of occasional errors
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Bookmarks -->
|
|
||||||
<div class="section" style="margin-top: 8px;">
|
|
||||||
<h3>Bookmarks</h3>
|
|
||||||
<div style="display: flex; gap: 4px; margin-bottom: 6px;">
|
|
||||||
<input type="number" id="dmrBookmarkFreq" placeholder="Freq MHz" step="0.0001"
|
|
||||||
style="flex: 1; font-size: 11px; padding: 4px 6px;">
|
|
||||||
<button class="preset-btn" onclick="addDmrBookmark()" style="font-size: 10px; padding: 4px 8px;"
|
|
||||||
title="Add bookmark">+</button>
|
|
||||||
</div>
|
|
||||||
<div style="display: flex; gap: 4px; margin-bottom: 6px;">
|
|
||||||
<input type="text" id="dmrBookmarkLabel" placeholder="Label (optional)"
|
|
||||||
style="flex: 1; font-size: 11px; padding: 4px 6px;">
|
|
||||||
<button class="preset-btn" onclick="addCurrentDmrFreqBookmark()" style="font-size: 9px; padding: 4px 6px;"
|
|
||||||
title="Save current frequency">Save current</button>
|
|
||||||
</div>
|
|
||||||
<div id="dmrBookmarksList" style="max-height: 150px; overflow-y: auto;">
|
|
||||||
<div style="color: var(--text-muted); text-align: center; padding: 10px; font-size: 11px;">No bookmarks saved</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Actions -->
|
<!-- Actions -->
|
||||||
@@ -111,30 +51,21 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Status -->
|
<!-- Status -->
|
||||||
<div class="section" style="margin-top: 12px;">
|
<div class="section" style="margin-top: 12px;">
|
||||||
<h3>Status</h3>
|
<h3>Status</h3>
|
||||||
<div style="background: rgba(0,0,0,0.3); border-radius: 6px; padding: 10px;">
|
<div style="background: rgba(0,0,0,0.3); border-radius: 6px; padding: 10px;">
|
||||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
|
||||||
<span style="font-size: 10px; color: var(--text-muted); text-transform: uppercase;">Status</span>
|
<span style="font-size: 10px; color: var(--text-muted); text-transform: uppercase;">Status</span>
|
||||||
<span id="dmrStatus" style="font-size: 11px; color: var(--accent-cyan);">IDLE</span>
|
<span id="dmrStatus" style="font-size: 11px; color: var(--accent-cyan);">IDLE</span>
|
||||||
</div>
|
</div>
|
||||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
|
||||||
<span style="font-size: 10px; color: var(--text-muted); text-transform: uppercase;">Protocol</span>
|
<span style="font-size: 10px; color: var(--text-muted); text-transform: uppercase;">Protocol</span>
|
||||||
<span id="dmrActiveProtocol" style="font-size: 11px; color: var(--text-primary);">--</span>
|
<span id="dmrActiveProtocol" style="font-size: 11px; color: var(--text-primary);">--</span>
|
||||||
</div>
|
</div>
|
||||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||||
<span style="font-size: 10px; color: var(--text-muted); text-transform: uppercase;">Calls</span>
|
<span style="font-size: 10px; color: var(--text-muted); text-transform: uppercase;">Calls</span>
|
||||||
<span id="dmrCallCount" style="font-size: 14px; font-weight: bold; color: var(--accent-green);">0</span>
|
<span id="dmrCallCount" style="font-size: 14px; font-weight: bold; color: var(--accent-green);">0</span>
|
||||||
</div>
|
|
||||||
<div style="margin-top: 8px;">
|
|
||||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
|
|
||||||
<span style="font-size: 10px; color: var(--text-muted); text-transform: uppercase;">Quality</span>
|
|
||||||
<span id="dmrQualityText" style="font-size: 11px; color: var(--text-primary);">--</span>
|
|
||||||
</div>
|
|
||||||
<div style="height: 6px; background: rgba(255,255,255,0.08); border-radius: 6px; overflow: hidden;">
|
|
||||||
<div id="dmrQualityBar" style="height: 100%; width: 0%; background: var(--text-muted); transition: width 0.2s ease;"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -61,8 +61,35 @@
|
|||||||
<div id="signalGuessExplanation" style="color: var(--text-muted); font-size: 10px; margin-bottom: 6px;"></div>
|
<div id="signalGuessExplanation" style="color: var(--text-muted); font-size: 10px; margin-bottom: 6px;"></div>
|
||||||
<div id="signalGuessTags" style="display: flex; flex-wrap: wrap; gap: 3px;"></div>
|
<div id="signalGuessTags" style="display: flex; flex-wrap: wrap; gap: 3px;"></div>
|
||||||
<div id="signalGuessAlternatives" style="margin-top: 6px; font-size: 10px; color: var(--text-muted);"></div>
|
<div id="signalGuessAlternatives" style="margin-top: 6px; font-size: 10px; color: var(--text-muted);"></div>
|
||||||
<div id="signalGuessSendTo" style="margin-top: 8px; display: none;"></div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Waterfall Controls -->
|
||||||
|
<div class="section">
|
||||||
|
<h3>Waterfall</h3>
|
||||||
|
<div class="form-group" style="margin-bottom: 6px;">
|
||||||
|
<label style="font-size: 10px;">Start (MHz)</label>
|
||||||
|
<input type="number" id="waterfallStartFreq" value="88" step="0.1" style="width: 100%; padding: 5px; background: var(--bg-secondary); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; font-size: 11px;">
|
||||||
|
</div>
|
||||||
|
<div class="form-group" style="margin-bottom: 6px;">
|
||||||
|
<label style="font-size: 10px;">End (MHz)</label>
|
||||||
|
<input type="number" id="waterfallEndFreq" value="108" step="0.1" style="width: 100%; padding: 5px; background: var(--bg-secondary); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; font-size: 11px;">
|
||||||
|
</div>
|
||||||
|
<div class="form-group" style="margin-bottom: 6px;">
|
||||||
|
<label style="font-size: 10px;">Bin Size</label>
|
||||||
|
<select id="waterfallBinSize" style="width: 100%; padding: 5px; background: var(--bg-secondary); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; font-size: 11px;">
|
||||||
|
<option value="5000">5 kHz</option>
|
||||||
|
<option value="10000" selected>10 kHz</option>
|
||||||
|
<option value="25000">25 kHz</option>
|
||||||
|
<option value="100000">100 kHz</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="form-group" style="margin-bottom: 8px;">
|
||||||
|
<label style="font-size: 10px;">Gain</label>
|
||||||
|
<input type="number" id="waterfallGain" value="40" min="0" max="50" style="width: 100%; padding: 5px; background: var(--bg-secondary); border: 1px solid var(--border-color); color: var(--text-primary); border-radius: 4px; font-size: 11px;">
|
||||||
|
</div>
|
||||||
|
<button class="run-btn" id="startWaterfallBtn" onclick="startWaterfall()" style="width: 100%; padding: 8px;">Start Waterfall</button>
|
||||||
|
<button class="stop-btn" id="stopWaterfallBtn" onclick="stopWaterfall()" style="display: none; width: 100%; padding: 8px; margin-top: 4px;">Stop Waterfall</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -55,74 +55,6 @@
|
|||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Antenna Guide -->
|
|
||||||
<div class="section">
|
|
||||||
<h3>Antenna Guide</h3>
|
|
||||||
<div style="font-size: 11px; color: var(--text-dim); line-height: 1.5;">
|
|
||||||
<p style="margin-bottom: 8px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
LoRa ISM band — frequency depends on region
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Stock Device Antenna</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Most devices:</strong> Ship with a small 915/868 MHz stubby antenna</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Works for:</strong> Short range (< 1 km) urban, indoor testing</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Upgrade:</strong> Replace with tuned antenna for 5–20x range improvement</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: #00ff88; font-size: 12px;">Recommended Upgrades</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Whip antenna:</strong> ~$8–15, tuned 915/868 MHz, SMA connector</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Ground plane:</strong> 8.2 cm vertical + 4 radials (915 MHz) on SMA</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Yagi:</strong> ~$15–30, directional, great for point-to-point links</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Collinear:</strong> ~$20–40, omnidirectional with higher gain (~5–8 dBi)</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Placement Tips</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Height wins:</strong> Elevating antenna 10m can double or triple range</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Line of sight:</strong> LoRa works best with clear LOS to other nodes</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Connector:</strong> Most devices use SMA or RP-SMA — check before buying</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 6px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">US / Americas</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">915 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">EU / UK / India</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">868 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">915 MHz λ/4</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">8.2 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">868 MHz λ/4</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">8.6 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Modulation</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">LoRa (CSS)</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Typical range</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">1–15 km</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -75,62 +75,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Antenna Guide -->
|
|
||||||
<div class="section">
|
|
||||||
<h3>Antenna Guide</h3>
|
|
||||||
<div style="font-size: 11px; color: var(--text-dim); line-height: 1.5;">
|
|
||||||
<p style="margin-bottom: 8px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
Pager frequencies vary by region (130–930 MHz)
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Stock Telescopic Antenna</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Works for:</strong> UHF pager bands (~900 MHz) — the stock antenna is tuned near 1 GHz</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Extend to:</strong> ~8 cm for 929 MHz (quarter-wave)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">For VHF (~150 MHz):</strong> Stock antenna is too short. Build a dipole (see below)</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Simple Dipole (Best for VHF Pagers)</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">For 153 MHz:</strong> Two elements, each ~49 cm (quarter-wave)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">For 929 MHz:</strong> Two elements, each ~8 cm</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Formula:</strong> Element length (cm) = 7500 / frequency (MHz)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Material:</strong> Any wire, coat hanger, or copper rod</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Orientation:</strong> Vertical (pager signals are vertically polarized)</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 6px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Common UHF freq</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">929 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Common VHF freq</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">153.350 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Modulation</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">FM (NFM)</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Bandwidth</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">~12.5 kHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Polarization</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">Vertical</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button class="run-btn" id="startBtn" onclick="startDecoding()">
|
<button class="run-btn" id="startBtn" onclick="startDecoding()">
|
||||||
Start Decoding
|
Start Decoding
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -58,59 +58,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Antenna Guide -->
|
|
||||||
<div class="section">
|
|
||||||
<h3>Antenna Guide</h3>
|
|
||||||
<div style="font-size: 11px; color: var(--text-dim); line-height: 1.5;">
|
|
||||||
<p style="margin-bottom: 8px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
ISM 900 MHz band — stock antenna is close but not optimal
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Stock Telescopic Antenna</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">912 MHz:</strong> Extend to ~8.2 cm (quarter-wave). The stock antenna is close enough to work</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Range:</strong> Most meters transmit at ~100 mW, expect 50–200 m range with stock antenna</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Upgraded Options</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Ground Plane:</strong> 8.2 cm vertical + four 8.2 cm radials at 45° on SMA connector</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Yagi:</strong> Directional for targeting specific meters at distance (~$15–25)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Placement:</strong> Near a window facing the meters. Line-of-sight matters most</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 6px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Frequency (NA)</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">912 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Frequency (EU)</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">868 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">912 MHz λ/4</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">8.2 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Meter TX power</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">~100 mW</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Polarization</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">Vertical</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button class="run-btn" id="startRtlamrBtn" onclick="startRtlamrDecoding()">
|
<button class="run-btn" id="startRtlamrBtn" onclick="startRtlamrDecoding()">
|
||||||
Start Listening
|
Start Listening
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -39,61 +39,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Antenna Guide -->
|
|
||||||
<div class="section">
|
|
||||||
<h3>Antenna Guide</h3>
|
|
||||||
<div style="font-size: 11px; color: var(--text-dim); line-height: 1.5;">
|
|
||||||
<p style="margin-bottom: 8px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
ISM band devices (433 / 868 / 915 MHz)
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Stock Telescopic Antenna</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">433 MHz:</strong> Extend to ~17 cm (quarter-wave). Stock antenna works but isn't ideal</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">868/915 MHz:</strong> Extend to ~8 cm. Stock antenna is nearly tuned for this</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quarter-Wave Ground Plane (Best)</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">433 MHz:</strong> Vertical element 17.3 cm + four 17.3 cm radials at 45°</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">868 MHz:</strong> Vertical element 8.6 cm + four 8.6 cm radials</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">915 MHz:</strong> Vertical element 8.2 cm + four 8.2 cm radials</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Material:</strong> Stiff copper wire soldered to an SMA connector</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Placement:</strong> Outdoors or near a window. Higher is better for range</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 6px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">433 MHz λ/4</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">17.3 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">868 MHz λ/4</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">8.6 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">915 MHz λ/4</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">8.2 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Typical range</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">50–300 m</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Polarization</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">Vertical</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button class="run-btn" id="startSensorBtn" onclick="startSensorDecoding()">
|
<button class="run-btn" id="startSensorBtn" onclick="startSensorDecoding()">
|
||||||
Start Listening
|
Start Listening
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -39,64 +39,4 @@
|
|||||||
Common modes: PD120, PD180, Martin1, Scottie1
|
Common modes: PD120, PD180, Martin1, Scottie1
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Antenna Guide -->
|
|
||||||
<div class="section">
|
|
||||||
<h3>Antenna Guide</h3>
|
|
||||||
<div style="font-size: 11px; color: var(--text-dim); line-height: 1.5;">
|
|
||||||
<p style="margin-bottom: 8px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
2m band (145.800 MHz) — stock SDR antenna will NOT work
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">V-Dipole (Easiest — ~$5)</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Element length:</strong> ~51 cm each (quarter-wave at 145.8 MHz)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Angle:</strong> 120° between elements for partial RHCP</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Orientation:</strong> Lay flat, angled toward the ISS pass direction</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Material:</strong> Wire, coat hanger, or copper rod</li>
|
|
||||||
</ul>
|
|
||||||
<p style="margin-top: 6px; color: var(--text-dim); font-style: italic;">
|
|
||||||
Same antenna as weather satellites (similar frequency). A QFH or turnstile for 137 MHz also works well here.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Tips for ISS Reception</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">ISS altitude:</strong> ~420 km, overhead passes last 5–10 minutes</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Best passes:</strong> Elevation > 30° for clear signal</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Outdoors:</strong> Clear sky view is essential. Roof or open field</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">LNA:</strong> Optional but helps — 2m filtered LNA at antenna feed</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Doppler:</strong> ISS moves fast — signal shifts ±3.5 kHz during pass</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 6px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">ISS SSTV frequency</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">145.800 MHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Quarter-wave length</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">51 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Modulation</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">FM (25 kHz)</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Polarization</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">RHCP (circular)</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Typical pass duration</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">5–10 min</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,244 +0,0 @@
|
|||||||
<!-- WEATHER SATELLITE MODE -->
|
|
||||||
<div id="weatherSatMode" class="mode-content">
|
|
||||||
<div class="section">
|
|
||||||
<h3>Weather Satellite Decoder</h3>
|
|
||||||
<p class="info-text" style="font-size: 11px; color: var(--text-dim); margin-bottom: 12px;">
|
|
||||||
Receive and decode weather images from NOAA and Meteor satellites.
|
|
||||||
Uses SatDump for live SDR capture and image processing.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<h3>Satellite</h3>
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Select Satellite</label>
|
|
||||||
<select id="weatherSatSelect" class="mode-select">
|
|
||||||
<option value="NOAA-15">NOAA-15 (137.620 MHz APT)</option>
|
|
||||||
<option value="NOAA-18" selected>NOAA-18 (137.9125 MHz APT)</option>
|
|
||||||
<option value="NOAA-19">NOAA-19 (137.100 MHz APT)</option>
|
|
||||||
<option value="METEOR-M2-3">Meteor-M2-3 (137.900 MHz LRPT)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Gain (dB)</label>
|
|
||||||
<input type="number" id="weatherSatGain" value="40" step="0.1" min="0" max="50">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label style="display: flex; align-items: center; gap: 6px;">
|
|
||||||
<input type="checkbox" id="weatherSatBiasT" style="width: auto;">
|
|
||||||
Bias-T (power LNA)
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Antenna Guide - detailed -->
|
|
||||||
<div class="section">
|
|
||||||
<h3>Antenna Guide</h3>
|
|
||||||
<div style="font-size: 11px; color: var(--text-dim); line-height: 1.5;">
|
|
||||||
|
|
||||||
<p style="margin-bottom: 10px; color: var(--accent-cyan); font-weight: 600;">
|
|
||||||
137 MHz band — your stock SDR antenna will NOT work.
|
|
||||||
</p>
|
|
||||||
<p style="margin-bottom: 10px;">
|
|
||||||
Weather satellites transmit at 137.1–137.9 MHz. The quarter-wave
|
|
||||||
at this frequency is <strong style="color: var(--text-primary);">~53 cm</strong>,
|
|
||||||
far longer than the small telescopic antenna shipped with most SDRs
|
|
||||||
(tuned for ~1 GHz). You need a purpose-built antenna.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<!-- V-Dipole -->
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">V-Dipole (Easiest — ~$5)</strong>
|
|
||||||
|
|
||||||
<div style="margin: 8px 0; padding: 8px; background: var(--bg-tertiary); border-radius: 3px; font-family: 'JetBrains Mono', monospace; font-size: 10px; color: var(--text-secondary); white-space: pre; line-height: 1.3; text-align: center;"> coax to SDR
|
|
||||||
|
|
|
||||||
===+=== feed point
|
|
||||||
/ \
|
|
||||||
/ 120 \
|
|
||||||
/ \
|
|
||||||
/ deg \
|
|
||||||
53.4cm 53.4cm</div>
|
|
||||||
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Element length:</strong> 53.4 cm each (quarter wavelength at 137 MHz)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Angle:</strong> 120° between elements (not 180°)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Material:</strong> Any stiff wire, coat hanger, or copper rod</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Orientation:</strong> Lay flat or tilt 30° toward expected pass direction</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Polarization:</strong> The 120° angle gives partial RHCP match to satellite signal</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Connection:</strong> Solder elements to coax center + shield, connect to SDR via SMA</li>
|
|
||||||
</ul>
|
|
||||||
<p style="margin-top: 6px; color: var(--text-dim); font-style: italic;">
|
|
||||||
Best starter antenna. Good enough for clear NOAA images with a direct overhead pass.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Turnstile -->
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Turnstile / Crossed Dipole (~$10-15)</strong>
|
|
||||||
|
|
||||||
<div style="margin: 8px 0; padding: 8px; background: var(--bg-tertiary); border-radius: 3px; font-family: 'JetBrains Mono', monospace; font-size: 10px; color: var(--text-secondary); white-space: pre; line-height: 1.3; text-align: center;"> 53.4cm
|
|
||||||
<--------->
|
|
||||||
====+==== dipole 1
|
|
||||||
|
|
|
||||||
====+==== dipole 2
|
|
||||||
<--------->
|
|
||||||
90 deg rotated
|
|
||||||
+ reflector below</div>
|
|
||||||
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Elements:</strong> Two crossed dipoles, each 53.4 cm per side (4 elements total)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Angle:</strong> 90° between the two dipole pairs</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Phasing:</strong> Feed dipole 2 with a 90° delay (quarter-wave coax section ~37 cm of RG-58)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Reflector:</strong> Place ~52 cm below elements (ground plane or wire grid)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Polarization:</strong> Circular (RHCP) — matches satellite transmission</li>
|
|
||||||
</ul>
|
|
||||||
<p style="margin-top: 6px; color: var(--text-dim); font-style: italic;">
|
|
||||||
Better than V-dipole. The reflector rejects ground noise and the RHCP phasing matches the satellite signal.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- QFH -->
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: #00ff88; font-size: 12px;">QFH — Quadrifilar Helix (Best — ~$20-30)</strong>
|
|
||||||
|
|
||||||
<div style="margin: 8px 0; padding: 8px; background: var(--bg-tertiary); border-radius: 3px; font-family: 'JetBrains Mono', monospace; font-size: 10px; color: var(--text-secondary); white-space: pre; line-height: 1.3; text-align: center;"> ___
|
|
||||||
/ \ two helix loops
|
|
||||||
| | | twisted 90 deg
|
|
||||||
| | | around a mast
|
|
||||||
\___/
|
|
||||||
|
|
|
||||||
coax</div>
|
|
||||||
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Design:</strong> Two bifilar helical loops, offset 90°</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Material:</strong> Copper pipe (10mm), copper wire, or coax outer shield</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Total height:</strong> ~46 cm (for 137 MHz)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Loop dimensions:</strong> Use a QFH calculator for exact bending measurements</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Polarization:</strong> True RHCP omnidirectional — ideal for overhead satellite passes</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Gain pattern:</strong> Hemispherical upward coverage, rejects ground interference</li>
|
|
||||||
</ul>
|
|
||||||
<p style="margin-top: 6px; color: var(--text-dim); font-style: italic;">
|
|
||||||
Gold standard for weather satellite reception. No tracking needed — covers the whole sky.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Placement & LNA -->
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px; margin-bottom: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Placement & LNA</strong>
|
|
||||||
<ul style="margin: 6px 0 0 14px; padding: 0;">
|
|
||||||
<li><strong style="color: var(--text-primary);">Location:</strong> OUTDOORS with clear sky view is critical. Roof/balcony/open field.</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Height:</strong> Higher is better but not critical — clear horizon line matters more</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Antenna up:</strong> Point the antenna straight UP (zenith) for best overhead coverage</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Avoid:</strong> Metal roofs, power lines, buildings blocking the sky</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Coax length:</strong> Keep short (<10m). Signal loss at 137 MHz is ~3 dB per 10m of RG-58</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">LNA:</strong> Mount at the antenna feed point, NOT at the SDR end.
|
|
||||||
Recommended: Nooelec SAWbird+ NOAA (137 MHz filtered LNA, ~$30)</li>
|
|
||||||
<li><strong style="color: var(--text-primary);">Bias-T:</strong> Enable the Bias-T checkbox above if your LNA is powered via the coax from the SDR</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Quick reference -->
|
|
||||||
<div style="background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 4px; padding: 10px;">
|
|
||||||
<strong style="color: var(--accent-cyan); font-size: 12px;">Quick Reference</strong>
|
|
||||||
<table style="width: 100%; margin-top: 6px; font-size: 10px; border-collapse: collapse;">
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Wavelength (137 MHz)</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">218.8 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Quarter wave (element length)</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">53.4 cm</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Best pass elevation</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">> 30°</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Typical pass duration</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">10-15 min</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Polarization</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">RHCP</td>
|
|
||||||
</tr>
|
|
||||||
<tr style="border-bottom: 1px solid var(--border-color);">
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">NOAA (APT) bandwidth</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">~40 kHz</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-dim);">Meteor (LRPT) bandwidth</td>
|
|
||||||
<td style="padding: 3px 4px; color: var(--text-primary); text-align: right;">~140 kHz</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<h3 onclick="this.parentElement.querySelector('.wxsat-test-decode-body').classList.toggle('collapsed'); this.querySelector('.wxsat-collapse-icon').classList.toggle('collapsed')" style="cursor: pointer; display: flex; align-items: center; justify-content: space-between; user-select: none;">
|
|
||||||
Test Decode (File)
|
|
||||||
<span class="wxsat-collapse-icon collapsed" style="font-size: 10px; transition: transform 0.2s; display: inline-block;">▼</span>
|
|
||||||
</h3>
|
|
||||||
<div class="wxsat-test-decode-body collapsed" style="overflow: hidden;">
|
|
||||||
<p class="info-text" style="font-size: 11px; color: var(--text-dim); margin-bottom: 8px;">
|
|
||||||
Decode a pre-recorded IQ or WAV file without SDR hardware.
|
|
||||||
Run <code style="font-size: 10px;">./download-weather-sat-samples.sh</code> to fetch sample files.
|
|
||||||
</p>
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Satellite</label>
|
|
||||||
<select id="wxsatTestSatSelect" class="mode-select">
|
|
||||||
<option value="NOAA-15">NOAA-15 (APT)</option>
|
|
||||||
<option value="NOAA-18" selected>NOAA-18 (APT)</option>
|
|
||||||
<option value="NOAA-19">NOAA-19 (APT)</option>
|
|
||||||
<option value="METEOR-M2-3">Meteor-M2-3 (LRPT)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label>File Path (server-side)</label>
|
|
||||||
<input type="text" id="wxsatTestFilePath" value="data/weather_sat/samples/noaa_apt_argentina.wav" style="font-family: 'JetBrains Mono', monospace; font-size: 11px;">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Sample Rate</label>
|
|
||||||
<select id="wxsatTestSampleRate" class="mode-select">
|
|
||||||
<option value="11025">11025 Hz (WAV audio APT)</option>
|
|
||||||
<option value="48000">48000 Hz (WAV audio APT)</option>
|
|
||||||
<option value="500000">500 kHz (IQ LRPT)</option>
|
|
||||||
<option value="1000000" selected>1 MHz (IQ default)</option>
|
|
||||||
<option value="2000000">2 MHz (IQ wideband)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<button class="mode-btn" onclick="WeatherSat.testDecode()" style="width: 100%; margin-top: 4px;">
|
|
||||||
Test Decode
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<h3>Auto-Scheduler</h3>
|
|
||||||
<p class="info-text" style="font-size: 11px; color: var(--text-dim); margin-bottom: 8px;">
|
|
||||||
Automatically capture satellite passes based on predictions.
|
|
||||||
Set your location above and toggle AUTO in the strip bar.
|
|
||||||
</p>
|
|
||||||
<div class="form-group">
|
|
||||||
<label style="display: flex; align-items: center; gap: 6px;">
|
|
||||||
<input type="checkbox" id="wxsatSidebarAutoSchedule" onchange="WeatherSat.toggleScheduler()" style="width: auto;">
|
|
||||||
Enable Auto-Capture
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div id="wxsatSchedulerStatus" style="font-size: 11px; color: var(--text-dim); font-family: 'JetBrains Mono', monospace; margin-top: 4px;">
|
|
||||||
Disabled
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section">
|
|
||||||
<h3>Resources</h3>
|
|
||||||
<div style="display: flex; flex-direction: column; gap: 6px;">
|
|
||||||
<a href="https://github.com/SatDump/SatDump" target="_blank" rel="noopener" class="preset-btn" style="text-decoration: none; text-align: center;">
|
|
||||||
SatDump Documentation
|
|
||||||
</a>
|
|
||||||
<a href="https://www.rtl-sdr.com/rtl-sdr-tutorial-receiving-noaa-weather-satellite-images/" target="_blank" rel="noopener" class="preset-btn" style="text-decoration: none; text-align: center;">
|
|
||||||
NOAA Reception Guide
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
@@ -69,22 +69,7 @@
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>Channel Preset</label>
|
<label>Channel (empty = hop)</label>
|
||||||
<select id="wifiChannelPreset">
|
|
||||||
<option value="">Auto hop (all)</option>
|
|
||||||
<option value="2.4-common">2.4 GHz Common (1,6,11)</option>
|
|
||||||
<option value="2.4-all">2.4 GHz All (1-13)</option>
|
|
||||||
<option value="5-low">5 GHz Low (36-48)</option>
|
|
||||||
<option value="5-mid">5 GHz Mid/DFS (52-64)</option>
|
|
||||||
<option value="5-high">5 GHz High (149-165)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Channel List (overrides preset)</label>
|
|
||||||
<input type="text" id="wifiChannelList" placeholder="e.g., 1,6,11 or 36,40,44,48">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Channel (single)</label>
|
|
||||||
<input type="text" id="wifiChannel" placeholder="e.g., 6 or 36">
|
<input type="text" id="wifiChannel" placeholder="e.g., 6 or 36">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -118,7 +118,6 @@
|
|||||||
{{ mode_item('satellite', 'Satellite', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 7L9 3 5 7l4 4"/><path d="m17 11 4 4-4 4-4-4"/><path d="m8 12 4 4 6-6-4-4-6 6"/><path d="m16 8 3-3"/><path d="M9 21a6 6 0 0 0-6-6"/></svg>', '/satellite/dashboard') }}
|
{{ mode_item('satellite', 'Satellite', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 7L9 3 5 7l4 4"/><path d="m17 11 4 4-4 4-4-4"/><path d="m8 12 4 4 6-6-4-4-6 6"/><path d="m16 8 3-3"/><path d="M9 21a6 6 0 0 0-6-6"/></svg>', '/satellite/dashboard') }}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{{ mode_item('sstv', 'ISS SSTV', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M3 9h2"/><path d="M19 9h2"/><path d="M3 15h2"/><path d="M19 15h2"/></svg>') }}
|
{{ mode_item('sstv', 'ISS SSTV', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M3 9h2"/><path d="M19 9h2"/><path d="M3 15h2"/><path d="M19 15h2"/></svg>') }}
|
||||||
{{ mode_item('weathersat', 'Weather Sat', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>') }}
|
|
||||||
{{ mode_item('sstv_general', 'HF SSTV', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M16.24 7.76a6 6 0 0 1 0 8.49m-8.48-.01a6 6 0 0 1 0-8.49"/></svg>') }}
|
{{ mode_item('sstv_general', 'HF SSTV', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M16.24 7.76a6 6 0 0 1 0 8.49m-8.48-.01a6 6 0 0 1 0-8.49"/></svg>') }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -186,7 +185,6 @@
|
|||||||
{{ mobile_item('satellite', 'Sat', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 7L9 3 5 7l4 4"/><path d="m17 11 4 4-4 4-4-4"/><path d="m8 12 4 4 6-6-4-4-6 6"/></svg>', '/satellite/dashboard') }}
|
{{ mobile_item('satellite', 'Sat', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 7L9 3 5 7l4 4"/><path d="m17 11 4 4-4 4-4-4"/><path d="m8 12 4 4 6-6-4-4-6 6"/></svg>', '/satellite/dashboard') }}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{{ mobile_item('sstv', 'SSTV', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="3"/></svg>') }}
|
{{ mobile_item('sstv', 'SSTV', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="3"/></svg>') }}
|
||||||
{{ mobile_item('weathersat', 'WxSat', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>') }}
|
|
||||||
{{ mobile_item('sstv_general', 'HF SSTV', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="3"/></svg>') }}
|
{{ mobile_item('sstv_general', 'HF SSTV', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="12" cy="12" r="3"/></svg>') }}
|
||||||
{{ mobile_item('listening', 'Scanner', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M9 21V9"/></svg>') }}
|
{{ mobile_item('listening', 'Scanner', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M9 21V9"/></svg>') }}
|
||||||
{{ mobile_item('spystations', 'Spy', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4.9 19.1C1 15.2 1 8.8 4.9 4.9"/><circle cx="12" cy="12" r="2"/><path d="M19.1 4.9C23 8.8 23 15.1 19.1 19"/></svg>') }}
|
{{ mobile_item('spystations', 'Spy', '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4.9 19.1C1 15.2 1 8.8 4.9 4.9"/><circle cx="12" cy="12" r="2"/><path d="M19.1 4.9C23 8.8 23 15.1 19.1 19"/></svg>') }}
|
||||||
|
|||||||
@@ -15,8 +15,6 @@
|
|||||||
<button class="settings-tab" data-tab="display" onclick="switchSettingsTab('display')">Display</button>
|
<button class="settings-tab" data-tab="display" onclick="switchSettingsTab('display')">Display</button>
|
||||||
<button class="settings-tab" data-tab="updates" onclick="switchSettingsTab('updates')">Updates</button>
|
<button class="settings-tab" data-tab="updates" onclick="switchSettingsTab('updates')">Updates</button>
|
||||||
<button class="settings-tab" data-tab="tools" onclick="switchSettingsTab('tools')">Tools</button>
|
<button class="settings-tab" data-tab="tools" onclick="switchSettingsTab('tools')">Tools</button>
|
||||||
<button class="settings-tab" data-tab="alerts" onclick="switchSettingsTab('alerts')">Alerts</button>
|
|
||||||
<button class="settings-tab" data-tab="recording" onclick="switchSettingsTab('recording')">Recording</button>
|
|
||||||
<button class="settings-tab" data-tab="about" onclick="switchSettingsTab('about')">About</button>
|
<button class="settings-tab" data-tab="about" onclick="switchSettingsTab('about')">About</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -282,83 +280,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Alerts Section -->
|
|
||||||
<div id="settings-alerts" class="settings-section">
|
|
||||||
<div class="settings-group">
|
|
||||||
<div class="settings-group-title">Alert Feed <span id="alertsFeedCount" style="color: var(--text-dim); font-weight: 500;"></span></div>
|
|
||||||
<div id="alertsFeedList" class="settings-feed">
|
|
||||||
<div class="settings-feed-empty">No alerts yet</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings-group">
|
|
||||||
<div class="settings-group-title">Quick Rules</div>
|
|
||||||
<div style="display: flex; gap: 10px; flex-wrap: wrap;">
|
|
||||||
<button class="check-assets-btn" onclick="AlertCenter.enableTrackerAlerts()">Enable Tracker Alerts</button>
|
|
||||||
<button class="check-assets-btn" onclick="AlertCenter.disableTrackerAlerts()">Disable Tracker Alerts</button>
|
|
||||||
</div>
|
|
||||||
<div class="settings-info" style="margin-top: 10px;">
|
|
||||||
Use Bluetooth device details to add specific device watchlist alerts.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Recording Section -->
|
|
||||||
<div id="settings-recording" class="settings-section">
|
|
||||||
<div class="settings-group">
|
|
||||||
<div class="settings-group-title">Start Recording</div>
|
|
||||||
<div class="settings-row" style="border-bottom: none; padding-top: 0;">
|
|
||||||
<div class="settings-label">
|
|
||||||
<span class="settings-label-text">Mode</span>
|
|
||||||
<span class="settings-label-desc">Record live events for a mode</span>
|
|
||||||
</div>
|
|
||||||
<select id="recordingModeSelect" class="settings-select" style="width: 200px;">
|
|
||||||
<option value="pager">Pager</option>
|
|
||||||
<option value="sensor">433 Sensors</option>
|
|
||||||
<option value="wifi">WiFi</option>
|
|
||||||
<option value="bluetooth">Bluetooth</option>
|
|
||||||
<option value="adsb">ADS-B</option>
|
|
||||||
<option value="ais">AIS</option>
|
|
||||||
<option value="dsc">DSC</option>
|
|
||||||
<option value="acars">ACARS</option>
|
|
||||||
<option value="aprs">APRS</option>
|
|
||||||
<option value="rtlamr">RTLAMR</option>
|
|
||||||
<option value="dmr">DMR</option>
|
|
||||||
<option value="tscm">TSCM</option>
|
|
||||||
<option value="sstv">SSTV</option>
|
|
||||||
<option value="sstv_general">SSTV General</option>
|
|
||||||
<option value="listening_scanner">Listening Post</option>
|
|
||||||
<option value="waterfall">Waterfall</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="settings-row" style="border-bottom: none;">
|
|
||||||
<div class="settings-label">
|
|
||||||
<span class="settings-label-text">Label</span>
|
|
||||||
<span class="settings-label-desc">Optional note for the session</span>
|
|
||||||
</div>
|
|
||||||
<input type="text" id="recordingLabelInput" class="settings-input" placeholder="Morning sweep" style="width: 200px;">
|
|
||||||
</div>
|
|
||||||
<div style="display: flex; gap: 10px; margin-top: 10px;">
|
|
||||||
<button class="check-assets-btn" onclick="RecordingUI.start()">Start</button>
|
|
||||||
<button class="check-assets-btn" onclick="RecordingUI.stop()">Stop</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings-group">
|
|
||||||
<div class="settings-group-title">Active Sessions</div>
|
|
||||||
<div id="recordingActiveList" class="settings-feed">
|
|
||||||
<div class="settings-feed-empty">No active recordings</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="settings-group">
|
|
||||||
<div class="settings-group-title">Recent Recordings</div>
|
|
||||||
<div id="recordingList" class="settings-feed">
|
|
||||||
<div class="settings-feed-empty">No recordings yet</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- About Section -->
|
<!-- About Section -->
|
||||||
<div id="settings-about" class="settings-section">
|
<div id="settings-about" class="settings-section">
|
||||||
<div class="settings-group">
|
<div class="settings-group">
|
||||||
|
|||||||
+1
-87
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from unittest.mock import patch, MagicMock
|
from unittest.mock import patch, MagicMock
|
||||||
import pytest
|
import pytest
|
||||||
from routes.dmr import parse_dsd_output, _DSD_PROTOCOL_FLAGS, _DSD_FME_PROTOCOL_FLAGS, _DSD_FME_MODULATION
|
from routes.dmr import parse_dsd_output
|
||||||
|
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
@@ -66,16 +66,6 @@ def test_parse_talkgroup_dsd_fme_format():
|
|||||||
assert result['source_id'] == 67890
|
assert result['source_id'] == 67890
|
||||||
|
|
||||||
|
|
||||||
def test_parse_talkgroup_dsd_fme_tgt_src_format():
|
|
||||||
"""Should parse dsd-fme TGT/SRC pipe-delimited format."""
|
|
||||||
result = parse_dsd_output('Slot 1 | TGT: 12345 | SRC: 67890')
|
|
||||||
assert result is not None
|
|
||||||
assert result['type'] == 'call'
|
|
||||||
assert result['talkgroup'] == 12345
|
|
||||||
assert result['source_id'] == 67890
|
|
||||||
assert result['slot'] == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_talkgroup_with_slot():
|
def test_parse_talkgroup_with_slot():
|
||||||
"""TG line with slot info should capture both."""
|
"""TG line with slot info should capture both."""
|
||||||
result = parse_dsd_output('Slot 1 Voice LC, TG: 100, Src: 200')
|
result = parse_dsd_output('Slot 1 Voice LC, TG: 100, Src: 200')
|
||||||
@@ -108,60 +98,6 @@ def test_parse_unrecognized():
|
|||||||
assert result['text'] == 'some random text'
|
assert result['text'] == 'some random text'
|
||||||
|
|
||||||
|
|
||||||
def test_parse_banner_filtered():
|
|
||||||
"""Pure box-drawing lines (banners) should be filtered."""
|
|
||||||
assert parse_dsd_output('╔══════════════╗') is None
|
|
||||||
assert parse_dsd_output('║ ║') is None
|
|
||||||
assert parse_dsd_output('╚══════════════╝') is None
|
|
||||||
assert parse_dsd_output('───────────────') is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_box_drawing_with_data_not_filtered():
|
|
||||||
"""Lines with box-drawing separators AND data should NOT be filtered."""
|
|
||||||
result = parse_dsd_output('DMR BS │ Slot 1 │ TG: 12345 │ SRC: 67890')
|
|
||||||
assert result is not None
|
|
||||||
assert result['type'] == 'call'
|
|
||||||
assert result['talkgroup'] == 12345
|
|
||||||
assert result['source_id'] == 67890
|
|
||||||
|
|
||||||
|
|
||||||
def test_dsd_fme_flags_differ_from_classic():
|
|
||||||
"""dsd-fme remapped several flags; tables must NOT be identical."""
|
|
||||||
assert _DSD_FME_PROTOCOL_FLAGS != _DSD_PROTOCOL_FLAGS
|
|
||||||
|
|
||||||
|
|
||||||
def test_dsd_fme_protocol_flags_known_values():
|
|
||||||
"""dsd-fme flags use its own flag names (NOT classic DSD mappings)."""
|
|
||||||
assert _DSD_FME_PROTOCOL_FLAGS['auto'] == ['-ft'] # XDMA
|
|
||||||
assert _DSD_FME_PROTOCOL_FLAGS['dmr'] == ['-fs'] # Simplex (-fd is D-STAR!)
|
|
||||||
assert _DSD_FME_PROTOCOL_FLAGS['p25'] == ['-f1'] # NOT -fp (ProVoice in fme)
|
|
||||||
assert _DSD_FME_PROTOCOL_FLAGS['p25p2'] == ['-f2'] # Phase 2
|
|
||||||
assert _DSD_FME_PROTOCOL_FLAGS['nxdn'] == ['-fn']
|
|
||||||
assert _DSD_FME_PROTOCOL_FLAGS['dstar'] == ['-fd'] # -fd is D-STAR in dsd-fme
|
|
||||||
assert _DSD_FME_PROTOCOL_FLAGS['provoice'] == ['-fp'] # NOT -fv
|
|
||||||
|
|
||||||
|
|
||||||
def test_dsd_protocol_flags_known_values():
|
|
||||||
"""Classic DSD protocol flags should map to the correct -f flags."""
|
|
||||||
assert _DSD_PROTOCOL_FLAGS['dmr'] == ['-fd']
|
|
||||||
assert _DSD_PROTOCOL_FLAGS['p25'] == ['-fp']
|
|
||||||
assert _DSD_PROTOCOL_FLAGS['nxdn'] == ['-fn']
|
|
||||||
assert _DSD_PROTOCOL_FLAGS['dstar'] == ['-fi']
|
|
||||||
assert _DSD_PROTOCOL_FLAGS['provoice'] == ['-fv']
|
|
||||||
assert _DSD_PROTOCOL_FLAGS['auto'] == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_dsd_fme_modulation_hints():
|
|
||||||
"""C4FM modulation hints should be set for C4FM protocols."""
|
|
||||||
assert _DSD_FME_MODULATION['dmr'] == ['-mc']
|
|
||||||
assert _DSD_FME_MODULATION['p25'] == ['-mc']
|
|
||||||
assert _DSD_FME_MODULATION['p25p2'] == ['-mq']
|
|
||||||
assert _DSD_FME_MODULATION['nxdn'] == ['-mc']
|
|
||||||
# D-Star and ProVoice should not have forced modulation
|
|
||||||
assert 'dstar' not in _DSD_FME_MODULATION
|
|
||||||
assert 'provoice' not in _DSD_FME_MODULATION
|
|
||||||
|
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Endpoint tests
|
# Endpoint tests
|
||||||
# ============================================
|
# ============================================
|
||||||
@@ -237,25 +173,3 @@ def test_dmr_stream_mimetype(auth_client):
|
|||||||
"""Stream should return event-stream content type."""
|
"""Stream should return event-stream content type."""
|
||||||
resp = auth_client.get('/dmr/stream')
|
resp = auth_client.get('/dmr/stream')
|
||||||
assert resp.content_type.startswith('text/event-stream')
|
assert resp.content_type.startswith('text/event-stream')
|
||||||
def test_parse_frame_error_duid():
|
|
||||||
"""Should parse DUID errors as frame_error."""
|
|
||||||
result = parse_dsd_output('P25p2 LCH 0 DUID ERR 11')
|
|
||||||
assert result is not None
|
|
||||||
assert result['type'] == 'frame_error'
|
|
||||||
assert result['kind'] == 'duid'
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_frame_error_rs():
|
|
||||||
"""Should parse Reed-Solomon errors as frame_error."""
|
|
||||||
result = parse_dsd_output('P25p2 SACCH R-S ERR Sc')
|
|
||||||
assert result is not None
|
|
||||||
assert result['type'] == 'frame_error'
|
|
||||||
assert result['kind'] == 'rs'
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_frame_ok_p25p2():
|
|
||||||
"""Should parse P25p2 4V frames as OK."""
|
|
||||||
result = parse_dsd_output('P25p2 LCH 1 4V 1')
|
|
||||||
assert result is not None
|
|
||||||
assert result['type'] == 'frame_ok'
|
|
||||||
assert result['kind'] == 'p25p2'
|
|
||||||
|
|||||||
@@ -1,168 +0,0 @@
|
|||||||
"""Tests for the waterfall FFT pipeline."""
|
|
||||||
|
|
||||||
import struct
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from utils.waterfall_fft import (
|
|
||||||
build_binary_frame,
|
|
||||||
compute_power_spectrum,
|
|
||||||
cu8_to_complex,
|
|
||||||
quantize_to_uint8,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestCu8ToComplex:
|
|
||||||
"""Tests for cu8_to_complex conversion."""
|
|
||||||
|
|
||||||
def test_zero_maps_to_negative_one(self):
|
|
||||||
# I=0, Q=0 -> approximately -1 - 1j
|
|
||||||
result = cu8_to_complex(bytes([0, 0]))
|
|
||||||
assert result[0].real == pytest.approx(-1.0, abs=0.01)
|
|
||||||
assert result[0].imag == pytest.approx(-1.0, abs=0.01)
|
|
||||||
|
|
||||||
def test_255_maps_to_positive_one(self):
|
|
||||||
# I=255, Q=255 -> approximately +1 + 1j
|
|
||||||
result = cu8_to_complex(bytes([255, 255]))
|
|
||||||
assert result[0].real == pytest.approx(1.0, abs=0.01)
|
|
||||||
assert result[0].imag == pytest.approx(1.0, abs=0.01)
|
|
||||||
|
|
||||||
def test_128_maps_to_near_zero(self):
|
|
||||||
# I=128, Q=128 -> approximately 0 + 0j
|
|
||||||
result = cu8_to_complex(bytes([128, 128]))
|
|
||||||
assert abs(result[0].real) < 0.01
|
|
||||||
assert abs(result[0].imag) < 0.01
|
|
||||||
|
|
||||||
def test_output_length(self):
|
|
||||||
raw = bytes(range(256)) * 4 # 1024 bytes -> 512 complex samples
|
|
||||||
result = cu8_to_complex(raw)
|
|
||||||
assert len(result) == 512
|
|
||||||
|
|
||||||
def test_output_dtype(self):
|
|
||||||
result = cu8_to_complex(bytes([100, 200, 50, 150]))
|
|
||||||
assert result.dtype == np.complex64 or np.issubdtype(result.dtype, np.complexfloating)
|
|
||||||
|
|
||||||
|
|
||||||
class TestComputePowerSpectrum:
|
|
||||||
"""Tests for compute_power_spectrum."""
|
|
||||||
|
|
||||||
def test_output_length_matches_fft_size(self):
|
|
||||||
samples = np.zeros(4096, dtype=np.complex64)
|
|
||||||
result = compute_power_spectrum(samples, fft_size=1024, avg_count=4)
|
|
||||||
assert len(result) == 1024
|
|
||||||
|
|
||||||
def test_output_dtype(self):
|
|
||||||
samples = np.zeros(4096, dtype=np.complex64)
|
|
||||||
result = compute_power_spectrum(samples, fft_size=1024, avg_count=4)
|
|
||||||
assert result.dtype == np.float32
|
|
||||||
|
|
||||||
def test_pure_tone_peak_at_correct_bin(self):
|
|
||||||
fft_size = 1024
|
|
||||||
avg_count = 4
|
|
||||||
n = fft_size * avg_count
|
|
||||||
# Generate a pure tone at bin 256 (1/4 of sample rate)
|
|
||||||
t = np.arange(n, dtype=np.float32)
|
|
||||||
freq_bin = 256
|
|
||||||
tone = np.exp(2j * np.pi * freq_bin / fft_size * t).astype(np.complex64)
|
|
||||||
result = compute_power_spectrum(tone, fft_size=fft_size, avg_count=avg_count)
|
|
||||||
# After fftshift, bin 256 maps to index 256 + 512 = 768
|
|
||||||
peak_idx = np.argmax(result)
|
|
||||||
expected_idx = fft_size // 2 + freq_bin
|
|
||||||
assert peak_idx == expected_idx
|
|
||||||
|
|
||||||
def test_insufficient_samples_returns_default(self):
|
|
||||||
# Not enough samples for even one segment
|
|
||||||
samples = np.zeros(100, dtype=np.complex64)
|
|
||||||
result = compute_power_spectrum(samples, fft_size=1024, avg_count=4)
|
|
||||||
assert len(result) == 1024
|
|
||||||
assert np.all(result == -100.0)
|
|
||||||
|
|
||||||
def test_partial_avg_count(self):
|
|
||||||
# Only enough for 2 of 4 requested averages
|
|
||||||
fft_size = 1024
|
|
||||||
samples = np.random.randn(2048).astype(np.float32).view(np.complex64)
|
|
||||||
result = compute_power_spectrum(samples, fft_size=fft_size, avg_count=4)
|
|
||||||
assert len(result) == fft_size
|
|
||||||
# Should still return valid dB values (not -100 default)
|
|
||||||
assert np.any(result != -100.0)
|
|
||||||
|
|
||||||
|
|
||||||
class TestQuantizeToUint8:
|
|
||||||
"""Tests for quantize_to_uint8."""
|
|
||||||
|
|
||||||
def test_db_min_maps_to_zero(self):
|
|
||||||
power = np.array([-90.0], dtype=np.float32)
|
|
||||||
result = quantize_to_uint8(power, db_min=-90, db_max=-20)
|
|
||||||
assert result[0] == 0
|
|
||||||
|
|
||||||
def test_db_max_maps_to_255(self):
|
|
||||||
power = np.array([-20.0], dtype=np.float32)
|
|
||||||
result = quantize_to_uint8(power, db_min=-90, db_max=-20)
|
|
||||||
assert result[0] == 255
|
|
||||||
|
|
||||||
def test_below_min_clamped_to_zero(self):
|
|
||||||
power = np.array([-120.0], dtype=np.float32)
|
|
||||||
result = quantize_to_uint8(power, db_min=-90, db_max=-20)
|
|
||||||
assert result[0] == 0
|
|
||||||
|
|
||||||
def test_above_max_clamped_to_255(self):
|
|
||||||
power = np.array([0.0], dtype=np.float32)
|
|
||||||
result = quantize_to_uint8(power, db_min=-90, db_max=-20)
|
|
||||||
assert result[0] == 255
|
|
||||||
|
|
||||||
def test_midpoint(self):
|
|
||||||
# Midpoint between -90 and -20 is -55 -> ~127-128
|
|
||||||
power = np.array([-55.0], dtype=np.float32)
|
|
||||||
result = quantize_to_uint8(power, db_min=-90, db_max=-20)
|
|
||||||
assert 125 <= result[0] <= 130
|
|
||||||
|
|
||||||
def test_output_length(self):
|
|
||||||
power = np.random.randn(1024).astype(np.float32) * 30 - 60
|
|
||||||
result = quantize_to_uint8(power)
|
|
||||||
assert len(result) == 1024
|
|
||||||
|
|
||||||
|
|
||||||
class TestBuildBinaryFrame:
|
|
||||||
"""Tests for build_binary_frame."""
|
|
||||||
|
|
||||||
def test_header_values(self):
|
|
||||||
bins = bytes([128] * 1024)
|
|
||||||
frame = build_binary_frame(100.0, 102.0, bins)
|
|
||||||
msg_type = frame[0]
|
|
||||||
start_freq, end_freq = struct.unpack_from('<ff', frame, 1)
|
|
||||||
bin_count = struct.unpack_from('<H', frame, 9)[0]
|
|
||||||
assert msg_type == 0x01
|
|
||||||
assert start_freq == pytest.approx(100.0, abs=0.01)
|
|
||||||
assert end_freq == pytest.approx(102.0, abs=0.01)
|
|
||||||
assert bin_count == 1024
|
|
||||||
|
|
||||||
def test_total_length(self):
|
|
||||||
bin_count = 1024
|
|
||||||
bins = bytes([0] * bin_count)
|
|
||||||
frame = build_binary_frame(88.0, 108.0, bins)
|
|
||||||
assert len(frame) == 11 + bin_count
|
|
||||||
|
|
||||||
def test_bins_in_payload(self):
|
|
||||||
bins = bytes(range(256))
|
|
||||||
frame = build_binary_frame(0.0, 1.0, bins)
|
|
||||||
payload = frame[11:]
|
|
||||||
assert payload == bins
|
|
||||||
|
|
||||||
def test_round_trip(self):
|
|
||||||
start = 433.0
|
|
||||||
end = 435.0
|
|
||||||
bins = bytes([i % 256 for i in range(2048)])
|
|
||||||
frame = build_binary_frame(start, end, bins)
|
|
||||||
|
|
||||||
# Parse it back
|
|
||||||
msg_type = frame[0]
|
|
||||||
parsed_start, parsed_end = struct.unpack_from('<ff', frame, 1)
|
|
||||||
parsed_count = struct.unpack_from('<H', frame, 9)[0]
|
|
||||||
parsed_bins = frame[11:]
|
|
||||||
|
|
||||||
assert msg_type == 0x01
|
|
||||||
assert parsed_start == pytest.approx(start, abs=0.01)
|
|
||||||
assert parsed_end == pytest.approx(end, abs=0.01)
|
|
||||||
assert parsed_count == 2048
|
|
||||||
assert parsed_bins == bins
|
|
||||||
@@ -1,643 +0,0 @@
|
|||||||
"""Tests for WeatherSatDecoder class.
|
|
||||||
|
|
||||||
Covers WeatherSatDecoder methods, subprocess management, progress callbacks,
|
|
||||||
and image handling.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import tempfile
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from pathlib import Path
|
|
||||||
from unittest.mock import patch, MagicMock, call, mock_open
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from utils.weather_sat import (
|
|
||||||
WeatherSatDecoder,
|
|
||||||
WeatherSatImage,
|
|
||||||
CaptureProgress,
|
|
||||||
WEATHER_SATELLITES,
|
|
||||||
get_weather_sat_decoder,
|
|
||||||
is_weather_sat_available,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestWeatherSatDecoder:
|
|
||||||
"""Tests for WeatherSatDecoder class."""
|
|
||||||
|
|
||||||
def test_decoder_initialization(self):
|
|
||||||
"""Decoder should initialize with default output directory."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
assert decoder.is_running is False
|
|
||||||
assert decoder.decoder_available == 'satdump'
|
|
||||||
assert decoder.current_satellite == ''
|
|
||||||
assert decoder.current_frequency == 0.0
|
|
||||||
|
|
||||||
def test_decoder_initialization_no_satdump(self):
|
|
||||||
"""Decoder should detect when SatDump is unavailable."""
|
|
||||||
with patch('shutil.which', return_value=None):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
assert decoder.decoder_available is None
|
|
||||||
|
|
||||||
def test_decoder_custom_output_dir(self):
|
|
||||||
"""Decoder should accept custom output directory."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
custom_dir = '/tmp/custom_output'
|
|
||||||
decoder = WeatherSatDecoder(output_dir=custom_dir)
|
|
||||||
assert decoder._output_dir == Path(custom_dir)
|
|
||||||
|
|
||||||
def test_set_callback(self):
|
|
||||||
"""Decoder should accept progress callback."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
assert decoder._callback == callback
|
|
||||||
|
|
||||||
def test_set_on_complete(self):
|
|
||||||
"""Decoder should accept on_complete callback."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_on_complete(callback)
|
|
||||||
assert decoder._on_complete_callback == callback
|
|
||||||
|
|
||||||
def test_start_no_decoder(self):
|
|
||||||
"""start() should fail when no decoder available."""
|
|
||||||
with patch('shutil.which', return_value=None):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
success = decoder.start(satellite='NOAA-18', device_index=0, gain=40.0)
|
|
||||||
|
|
||||||
assert success is False
|
|
||||||
callback.assert_called()
|
|
||||||
progress = callback.call_args[0][0]
|
|
||||||
assert progress.status == 'error'
|
|
||||||
assert 'SatDump' in progress.message
|
|
||||||
|
|
||||||
def test_start_invalid_satellite(self):
|
|
||||||
"""start() should fail with invalid satellite."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
success = decoder.start(satellite='FAKE-SAT', device_index=0, gain=40.0)
|
|
||||||
|
|
||||||
assert success is False
|
|
||||||
callback.assert_called()
|
|
||||||
progress = callback.call_args[0][0]
|
|
||||||
assert progress.status == 'error'
|
|
||||||
assert 'Unknown satellite' in progress.message
|
|
||||||
|
|
||||||
@patch('subprocess.Popen')
|
|
||||||
@patch('pty.openpty')
|
|
||||||
@patch('utils.weather_sat.register_process')
|
|
||||||
def test_start_success(self, mock_register, mock_pty, mock_popen):
|
|
||||||
"""start() should successfully start SatDump."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'), \
|
|
||||||
patch('utils.weather_sat.WeatherSatDecoder._resolve_device_id', return_value='0'):
|
|
||||||
|
|
||||||
mock_pty.return_value = (10, 11)
|
|
||||||
mock_process = MagicMock()
|
|
||||||
mock_process.poll.return_value = None
|
|
||||||
mock_popen.return_value = mock_process
|
|
||||||
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
success = decoder.start(
|
|
||||||
satellite='NOAA-18',
|
|
||||||
device_index=0,
|
|
||||||
gain=40.0,
|
|
||||||
bias_t=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert success is True
|
|
||||||
assert decoder.is_running is True
|
|
||||||
assert decoder.current_satellite == 'NOAA-18'
|
|
||||||
assert decoder.current_frequency == 137.9125
|
|
||||||
assert decoder.current_mode == 'APT'
|
|
||||||
assert decoder.device_index == 0
|
|
||||||
|
|
||||||
mock_popen.assert_called_once()
|
|
||||||
cmd = mock_popen.call_args[0][0]
|
|
||||||
assert cmd[0] == 'satdump'
|
|
||||||
assert 'live' in cmd
|
|
||||||
assert 'noaa_apt' in cmd
|
|
||||||
assert '--bias' in cmd
|
|
||||||
|
|
||||||
@patch('subprocess.Popen')
|
|
||||||
@patch('pty.openpty')
|
|
||||||
def test_start_already_running(self, mock_pty, mock_popen):
|
|
||||||
"""start() should return True when already running."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
decoder._running = True
|
|
||||||
|
|
||||||
success = decoder.start(satellite='NOAA-18', device_index=0, gain=40.0)
|
|
||||||
|
|
||||||
assert success is True
|
|
||||||
mock_popen.assert_not_called()
|
|
||||||
|
|
||||||
@patch('subprocess.Popen')
|
|
||||||
@patch('pty.openpty')
|
|
||||||
def test_start_exception_handling(self, mock_pty, mock_popen):
|
|
||||||
"""start() should handle exceptions gracefully."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
mock_pty.return_value = (10, 11)
|
|
||||||
mock_popen.side_effect = OSError('Device not found')
|
|
||||||
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
success = decoder.start(satellite='NOAA-18', device_index=0, gain=40.0)
|
|
||||||
|
|
||||||
assert success is False
|
|
||||||
assert decoder.is_running is False
|
|
||||||
callback.assert_called()
|
|
||||||
progress = callback.call_args[0][0]
|
|
||||||
assert progress.status == 'error'
|
|
||||||
|
|
||||||
def test_start_from_file_no_decoder(self):
|
|
||||||
"""start_from_file() should fail when no decoder available."""
|
|
||||||
with patch('shutil.which', return_value=None):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
success = decoder.start_from_file(
|
|
||||||
satellite='NOAA-18',
|
|
||||||
input_file='data/test.wav',
|
|
||||||
)
|
|
||||||
|
|
||||||
assert success is False
|
|
||||||
callback.assert_called()
|
|
||||||
|
|
||||||
@patch('subprocess.Popen')
|
|
||||||
@patch('pty.openpty')
|
|
||||||
@patch('pathlib.Path.is_file', return_value=True)
|
|
||||||
@patch('pathlib.Path.resolve')
|
|
||||||
def test_start_from_file_success(self, mock_resolve, mock_is_file, mock_pty, mock_popen):
|
|
||||||
"""start_from_file() should successfully decode from file."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'), \
|
|
||||||
patch('utils.weather_sat.register_process'):
|
|
||||||
|
|
||||||
# Mock path resolution
|
|
||||||
mock_path = MagicMock()
|
|
||||||
mock_path.is_relative_to.return_value = True
|
|
||||||
mock_path.suffix = '.wav'
|
|
||||||
mock_resolve.return_value = mock_path
|
|
||||||
|
|
||||||
mock_pty.return_value = (10, 11)
|
|
||||||
mock_process = MagicMock()
|
|
||||||
mock_popen.return_value = mock_process
|
|
||||||
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
success = decoder.start_from_file(
|
|
||||||
satellite='NOAA-18',
|
|
||||||
input_file='data/test.wav',
|
|
||||||
sample_rate=1000000,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert success is True
|
|
||||||
assert decoder.is_running is True
|
|
||||||
assert decoder.current_satellite == 'NOAA-18'
|
|
||||||
|
|
||||||
mock_popen.assert_called_once()
|
|
||||||
cmd = mock_popen.call_args[0][0]
|
|
||||||
assert cmd[0] == 'satdump'
|
|
||||||
assert 'noaa_apt' in cmd
|
|
||||||
assert 'audio_wav' in cmd
|
|
||||||
assert '--samplerate' in cmd
|
|
||||||
|
|
||||||
@patch('pathlib.Path.resolve')
|
|
||||||
def test_start_from_file_path_traversal(self, mock_resolve):
|
|
||||||
"""start_from_file() should block path traversal."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
# Mock path outside allowed directory
|
|
||||||
mock_path = MagicMock()
|
|
||||||
mock_path.is_relative_to.return_value = False
|
|
||||||
mock_resolve.return_value = mock_path
|
|
||||||
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
success = decoder.start_from_file(
|
|
||||||
satellite='NOAA-18',
|
|
||||||
input_file='/etc/passwd',
|
|
||||||
)
|
|
||||||
|
|
||||||
assert success is False
|
|
||||||
callback.assert_called()
|
|
||||||
progress = callback.call_args[0][0]
|
|
||||||
assert 'data/ directory' in progress.message
|
|
||||||
|
|
||||||
@patch('pathlib.Path.is_file', return_value=False)
|
|
||||||
@patch('pathlib.Path.resolve')
|
|
||||||
def test_start_from_file_not_found(self, mock_resolve, mock_is_file):
|
|
||||||
"""start_from_file() should fail when file not found."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
mock_path = MagicMock()
|
|
||||||
mock_path.is_relative_to.return_value = True
|
|
||||||
mock_resolve.return_value = mock_path
|
|
||||||
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
success = decoder.start_from_file(
|
|
||||||
satellite='NOAA-18',
|
|
||||||
input_file='data/missing.wav',
|
|
||||||
)
|
|
||||||
|
|
||||||
assert success is False
|
|
||||||
callback.assert_called()
|
|
||||||
progress = callback.call_args[0][0]
|
|
||||||
assert 'not found' in progress.message.lower()
|
|
||||||
|
|
||||||
def test_stop_not_running(self):
|
|
||||||
"""stop() should be safe when not running."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
decoder.stop() # Should not raise
|
|
||||||
|
|
||||||
@patch('utils.weather_sat.safe_terminate')
|
|
||||||
def test_stop_running(self, mock_terminate):
|
|
||||||
"""stop() should terminate process."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
mock_process = MagicMock()
|
|
||||||
decoder._process = mock_process
|
|
||||||
decoder._running = True
|
|
||||||
decoder._pty_master_fd = 10
|
|
||||||
|
|
||||||
with patch('os.close') as mock_close:
|
|
||||||
decoder.stop()
|
|
||||||
|
|
||||||
assert decoder._running is False
|
|
||||||
mock_terminate.assert_called_once_with(mock_process)
|
|
||||||
mock_close.assert_called_once_with(10)
|
|
||||||
|
|
||||||
def test_get_images_empty(self):
|
|
||||||
"""get_images() should return empty list initially."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
images = decoder.get_images()
|
|
||||||
assert images == []
|
|
||||||
|
|
||||||
@patch('pathlib.Path.glob')
|
|
||||||
@patch('pathlib.Path.stat')
|
|
||||||
def test_get_images_scans_directory(self, mock_stat, mock_glob):
|
|
||||||
"""get_images() should scan output directory."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
|
|
||||||
# Mock image files
|
|
||||||
mock_file = MagicMock()
|
|
||||||
mock_file.name = 'NOAA-18_test.png'
|
|
||||||
mock_file.stat.return_value.st_size = 10000
|
|
||||||
mock_file.stat.return_value.st_mtime = time.time()
|
|
||||||
mock_glob.return_value = [mock_file]
|
|
||||||
|
|
||||||
images = decoder.get_images()
|
|
||||||
|
|
||||||
assert len(images) == 1
|
|
||||||
assert images[0].filename == 'NOAA-18_test.png'
|
|
||||||
assert images[0].satellite == 'NOAA-18'
|
|
||||||
|
|
||||||
def test_delete_image_success(self):
|
|
||||||
"""delete_image() should delete file."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
|
|
||||||
with patch('pathlib.Path.exists', return_value=True), \
|
|
||||||
patch('pathlib.Path.unlink') as mock_unlink:
|
|
||||||
|
|
||||||
result = decoder.delete_image('test.png')
|
|
||||||
|
|
||||||
assert result is True
|
|
||||||
mock_unlink.assert_called_once()
|
|
||||||
|
|
||||||
def test_delete_image_not_found(self):
|
|
||||||
"""delete_image() should return False for non-existent file."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
|
|
||||||
with patch('pathlib.Path.exists', return_value=False):
|
|
||||||
result = decoder.delete_image('missing.png')
|
|
||||||
|
|
||||||
assert result is False
|
|
||||||
|
|
||||||
def test_delete_all_images(self):
|
|
||||||
"""delete_all_images() should delete all images."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
|
|
||||||
mock_files = [MagicMock() for _ in range(3)]
|
|
||||||
with patch('pathlib.Path.glob', return_value=mock_files):
|
|
||||||
count = decoder.delete_all_images()
|
|
||||||
|
|
||||||
assert count == 3
|
|
||||||
for f in mock_files:
|
|
||||||
f.unlink.assert_called_once()
|
|
||||||
|
|
||||||
def test_get_status_idle(self):
|
|
||||||
"""get_status() should return idle status."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
status = decoder.get_status()
|
|
||||||
|
|
||||||
assert status['available'] is True
|
|
||||||
assert status['decoder'] == 'satdump'
|
|
||||||
assert status['running'] is False
|
|
||||||
assert status['satellite'] == ''
|
|
||||||
|
|
||||||
def test_get_status_running(self):
|
|
||||||
"""get_status() should return running status."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
decoder._running = True
|
|
||||||
decoder._current_satellite = 'NOAA-18'
|
|
||||||
decoder._current_frequency = 137.9125
|
|
||||||
decoder._current_mode = 'APT'
|
|
||||||
decoder._capture_start_time = time.time() - 60
|
|
||||||
|
|
||||||
status = decoder.get_status()
|
|
||||||
|
|
||||||
assert status['running'] is True
|
|
||||||
assert status['satellite'] == 'NOAA-18'
|
|
||||||
assert status['frequency'] == 137.9125
|
|
||||||
assert status['mode'] == 'APT'
|
|
||||||
assert status['elapsed_seconds'] >= 60
|
|
||||||
|
|
||||||
def test_classify_log_type_error(self):
|
|
||||||
"""_classify_log_type() should detect errors."""
|
|
||||||
assert WeatherSatDecoder._classify_log_type('(E) Error occurred') == 'error'
|
|
||||||
assert WeatherSatDecoder._classify_log_type('Failed to open device') == 'error'
|
|
||||||
|
|
||||||
def test_classify_log_type_progress(self):
|
|
||||||
"""_classify_log_type() should detect progress."""
|
|
||||||
assert WeatherSatDecoder._classify_log_type('Progress: 50%') == 'progress'
|
|
||||||
|
|
||||||
def test_classify_log_type_save(self):
|
|
||||||
"""_classify_log_type() should detect save events."""
|
|
||||||
assert WeatherSatDecoder._classify_log_type('Saved image: test.png') == 'save'
|
|
||||||
assert WeatherSatDecoder._classify_log_type('Writing output file') == 'save'
|
|
||||||
|
|
||||||
def test_classify_log_type_signal(self):
|
|
||||||
"""_classify_log_type() should detect signal events."""
|
|
||||||
assert WeatherSatDecoder._classify_log_type('Signal detected') == 'signal'
|
|
||||||
assert WeatherSatDecoder._classify_log_type('Lock acquired') == 'signal'
|
|
||||||
|
|
||||||
def test_classify_log_type_warning(self):
|
|
||||||
"""_classify_log_type() should detect warnings."""
|
|
||||||
assert WeatherSatDecoder._classify_log_type('(W) Low signal quality') == 'warning'
|
|
||||||
|
|
||||||
def test_classify_log_type_debug(self):
|
|
||||||
"""_classify_log_type() should detect debug messages."""
|
|
||||||
assert WeatherSatDecoder._classify_log_type('(D) Debug info') == 'debug'
|
|
||||||
|
|
||||||
@patch('subprocess.run')
|
|
||||||
def test_resolve_device_id_success(self, mock_run):
|
|
||||||
"""_resolve_device_id() should extract serial from rtl_test."""
|
|
||||||
mock_result = MagicMock()
|
|
||||||
mock_result.stdout = 'Found 1 device(s):\n 0: RTLSDRBlog, SN: 00004000'
|
|
||||||
mock_result.stderr = ''
|
|
||||||
mock_run.return_value = mock_result
|
|
||||||
|
|
||||||
serial = WeatherSatDecoder._resolve_device_id(0)
|
|
||||||
|
|
||||||
assert serial == '00004000'
|
|
||||||
mock_run.assert_called_once()
|
|
||||||
|
|
||||||
@patch('subprocess.run')
|
|
||||||
def test_resolve_device_id_fallback(self, mock_run):
|
|
||||||
"""_resolve_device_id() should fall back to index string."""
|
|
||||||
mock_run.side_effect = FileNotFoundError
|
|
||||||
|
|
||||||
serial = WeatherSatDecoder._resolve_device_id(0)
|
|
||||||
|
|
||||||
assert serial == '0'
|
|
||||||
|
|
||||||
def test_parse_product_name_rgb(self):
|
|
||||||
"""_parse_product_name() should identify RGB composite."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
product = decoder._parse_product_name(Path('/tmp/output/rgb_composite.png'))
|
|
||||||
assert product == 'RGB Composite'
|
|
||||||
|
|
||||||
def test_parse_product_name_thermal(self):
|
|
||||||
"""_parse_product_name() should identify thermal imagery."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
product = decoder._parse_product_name(Path('/tmp/output/thermal_image.png'))
|
|
||||||
assert product == 'Thermal'
|
|
||||||
|
|
||||||
def test_parse_product_name_channel(self):
|
|
||||||
"""_parse_product_name() should identify channel images."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
product = decoder._parse_product_name(Path('/tmp/output/channel_3.png'))
|
|
||||||
assert product == 'Channel 3'
|
|
||||||
|
|
||||||
def test_parse_product_name_unknown(self):
|
|
||||||
"""_parse_product_name() should return stem for unknown products."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
product = decoder._parse_product_name(Path('/tmp/output/unknown_image.png'))
|
|
||||||
assert product == 'unknown_image'
|
|
||||||
|
|
||||||
def test_emit_progress(self):
|
|
||||||
"""_emit_progress() should call callback."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock()
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
progress = CaptureProgress(status='capturing', message='Test')
|
|
||||||
decoder._emit_progress(progress)
|
|
||||||
|
|
||||||
callback.assert_called_once_with(progress)
|
|
||||||
|
|
||||||
def test_emit_progress_no_callback(self):
|
|
||||||
"""_emit_progress() should handle missing callback."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
progress = CaptureProgress(status='capturing', message='Test')
|
|
||||||
decoder._emit_progress(progress) # Should not raise
|
|
||||||
|
|
||||||
def test_emit_progress_callback_exception(self):
|
|
||||||
"""_emit_progress() should handle callback exceptions."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
decoder = WeatherSatDecoder()
|
|
||||||
callback = MagicMock(side_effect=Exception('Callback error'))
|
|
||||||
decoder.set_callback(callback)
|
|
||||||
|
|
||||||
progress = CaptureProgress(status='capturing', message='Test')
|
|
||||||
decoder._emit_progress(progress) # Should not raise
|
|
||||||
|
|
||||||
|
|
||||||
class TestWeatherSatImage:
|
|
||||||
"""Tests for WeatherSatImage dataclass."""
|
|
||||||
|
|
||||||
def test_to_dict(self):
|
|
||||||
"""WeatherSatImage.to_dict() should serialize correctly."""
|
|
||||||
image = WeatherSatImage(
|
|
||||||
filename='test.png',
|
|
||||||
path=Path('/tmp/test.png'),
|
|
||||||
satellite='NOAA-18',
|
|
||||||
mode='APT',
|
|
||||||
timestamp=datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
|
|
||||||
frequency=137.9125,
|
|
||||||
size_bytes=12345,
|
|
||||||
product='RGB Composite',
|
|
||||||
)
|
|
||||||
|
|
||||||
data = image.to_dict()
|
|
||||||
|
|
||||||
assert data['filename'] == 'test.png'
|
|
||||||
assert data['satellite'] == 'NOAA-18'
|
|
||||||
assert data['mode'] == 'APT'
|
|
||||||
assert data['timestamp'] == '2024-01-01T12:00:00+00:00'
|
|
||||||
assert data['frequency'] == 137.9125
|
|
||||||
assert data['size_bytes'] == 12345
|
|
||||||
assert data['product'] == 'RGB Composite'
|
|
||||||
assert data['url'] == '/weather-sat/images/test.png'
|
|
||||||
|
|
||||||
|
|
||||||
class TestCaptureProgress:
|
|
||||||
"""Tests for CaptureProgress dataclass."""
|
|
||||||
|
|
||||||
def test_to_dict_minimal(self):
|
|
||||||
"""CaptureProgress.to_dict() with minimal fields."""
|
|
||||||
progress = CaptureProgress(status='idle')
|
|
||||||
data = progress.to_dict()
|
|
||||||
|
|
||||||
assert data['type'] == 'weather_sat_progress'
|
|
||||||
assert data['status'] == 'idle'
|
|
||||||
assert data['satellite'] == ''
|
|
||||||
assert data['message'] == ''
|
|
||||||
assert data['progress'] == 0
|
|
||||||
|
|
||||||
def test_to_dict_complete(self):
|
|
||||||
"""CaptureProgress.to_dict() with all fields."""
|
|
||||||
image = WeatherSatImage(
|
|
||||||
filename='test.png',
|
|
||||||
path=Path('/tmp/test.png'),
|
|
||||||
satellite='NOAA-18',
|
|
||||||
mode='APT',
|
|
||||||
timestamp=datetime.now(timezone.utc),
|
|
||||||
frequency=137.9125,
|
|
||||||
)
|
|
||||||
|
|
||||||
progress = CaptureProgress(
|
|
||||||
status='complete',
|
|
||||||
satellite='NOAA-18',
|
|
||||||
frequency=137.9125,
|
|
||||||
mode='APT',
|
|
||||||
message='Capture complete',
|
|
||||||
progress_percent=100,
|
|
||||||
elapsed_seconds=600,
|
|
||||||
image=image,
|
|
||||||
log_type='info',
|
|
||||||
capture_phase='complete',
|
|
||||||
)
|
|
||||||
|
|
||||||
data = progress.to_dict()
|
|
||||||
|
|
||||||
assert data['status'] == 'complete'
|
|
||||||
assert data['satellite'] == 'NOAA-18'
|
|
||||||
assert data['frequency'] == 137.9125
|
|
||||||
assert data['mode'] == 'APT'
|
|
||||||
assert data['message'] == 'Capture complete'
|
|
||||||
assert data['progress'] == 100
|
|
||||||
assert data['elapsed_seconds'] == 600
|
|
||||||
assert 'image' in data
|
|
||||||
assert data['log_type'] == 'info'
|
|
||||||
assert data['capture_phase'] == 'complete'
|
|
||||||
|
|
||||||
|
|
||||||
class TestGlobalFunctions:
|
|
||||||
"""Tests for global utility functions."""
|
|
||||||
|
|
||||||
def test_get_weather_sat_decoder_singleton(self):
|
|
||||||
"""get_weather_sat_decoder() should return singleton."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
import utils.weather_sat as mod
|
|
||||||
old = mod._decoder
|
|
||||||
mod._decoder = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
decoder1 = get_weather_sat_decoder()
|
|
||||||
decoder2 = get_weather_sat_decoder()
|
|
||||||
|
|
||||||
assert decoder1 is decoder2
|
|
||||||
finally:
|
|
||||||
mod._decoder = old
|
|
||||||
|
|
||||||
def test_is_weather_sat_available_true(self):
|
|
||||||
"""is_weather_sat_available() should return True when available."""
|
|
||||||
with patch('shutil.which', return_value='/usr/bin/satdump'):
|
|
||||||
import utils.weather_sat as mod
|
|
||||||
old = mod._decoder
|
|
||||||
mod._decoder = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
assert is_weather_sat_available() is True
|
|
||||||
finally:
|
|
||||||
mod._decoder = old
|
|
||||||
|
|
||||||
def test_is_weather_sat_available_false(self):
|
|
||||||
"""is_weather_sat_available() should return False when unavailable."""
|
|
||||||
with patch('shutil.which', return_value=None):
|
|
||||||
import utils.weather_sat as mod
|
|
||||||
old = mod._decoder
|
|
||||||
mod._decoder = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
assert is_weather_sat_available() is False
|
|
||||||
finally:
|
|
||||||
mod._decoder = old
|
|
||||||
|
|
||||||
|
|
||||||
class TestWeatherSatellitesConstant:
|
|
||||||
"""Tests for WEATHER_SATELLITES constant."""
|
|
||||||
|
|
||||||
def test_weather_satellites_structure(self):
|
|
||||||
"""WEATHER_SATELLITES should have correct structure."""
|
|
||||||
assert 'NOAA-18' in WEATHER_SATELLITES
|
|
||||||
sat = WEATHER_SATELLITES['NOAA-18']
|
|
||||||
|
|
||||||
assert 'name' in sat
|
|
||||||
assert 'frequency' in sat
|
|
||||||
assert 'mode' in sat
|
|
||||||
assert 'pipeline' in sat
|
|
||||||
assert 'tle_key' in sat
|
|
||||||
assert 'description' in sat
|
|
||||||
assert 'active' in sat
|
|
||||||
|
|
||||||
def test_noaa_satellites(self):
|
|
||||||
"""NOAA satellites should have correct frequencies."""
|
|
||||||
assert WEATHER_SATELLITES['NOAA-15']['frequency'] == 137.620
|
|
||||||
assert WEATHER_SATELLITES['NOAA-18']['frequency'] == 137.9125
|
|
||||||
assert WEATHER_SATELLITES['NOAA-19']['frequency'] == 137.100
|
|
||||||
|
|
||||||
def test_meteor_satellite(self):
|
|
||||||
"""Meteor satellite should use LRPT mode."""
|
|
||||||
meteor = WEATHER_SATELLITES['METEOR-M2-3']
|
|
||||||
assert meteor['mode'] == 'LRPT'
|
|
||||||
assert meteor['frequency'] == 137.900
|
|
||||||
assert meteor['pipeline'] == 'meteor_m2-x_lrpt'
|
|
||||||
@@ -1,675 +0,0 @@
|
|||||||
"""Tests for weather satellite pass prediction.
|
|
||||||
|
|
||||||
Covers predict_passes() function, TLE handling, trajectory computation,
|
|
||||||
and ground track generation.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime, timezone, timedelta
|
|
||||||
from unittest.mock import patch, MagicMock
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from utils.weather_sat_predict import predict_passes
|
|
||||||
|
|
||||||
|
|
||||||
class TestPredictPasses:
|
|
||||||
"""Tests for predict_passes() function."""
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
def test_predict_passes_no_tle_data(self, mock_tle, mock_load):
|
|
||||||
"""predict_passes() should handle missing TLE data."""
|
|
||||||
mock_tle.get.return_value = None
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
mock_ts.now.return_value = MagicMock()
|
|
||||||
mock_ts.utc.return_value = MagicMock()
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
|
|
||||||
assert passes == []
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_basic(self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load):
|
|
||||||
"""predict_passes() should predict basic passes."""
|
|
||||||
# Mock timescale
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
# Mock TLE data
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
# Mock observer
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
# Mock satellite
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
# Mock pass detection - one pass
|
|
||||||
rise_time = MagicMock()
|
|
||||||
rise_time.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set_time = MagicMock()
|
|
||||||
set_time.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
mock_find.return_value = ([rise_time, set_time], [True, False])
|
|
||||||
|
|
||||||
# Mock topocentric calculations
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 45.0
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
|
|
||||||
assert len(passes) == 1
|
|
||||||
pass_data = passes[0]
|
|
||||||
assert pass_data['satellite'] == 'NOAA-18'
|
|
||||||
assert pass_data['name'] == 'NOAA 18'
|
|
||||||
assert pass_data['frequency'] == 137.9125
|
|
||||||
assert pass_data['mode'] == 'APT'
|
|
||||||
assert 'maxEl' in pass_data
|
|
||||||
assert 'duration' in pass_data
|
|
||||||
assert 'quality' in pass_data
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_below_min_elevation(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should filter passes below min elevation."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
rise_time = MagicMock()
|
|
||||||
rise_time.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set_time = MagicMock()
|
|
||||||
set_time.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
mock_find.return_value = ([rise_time, set_time], [True, False])
|
|
||||||
|
|
||||||
# Mock low elevation pass
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 10.0 # Below min_elevation of 15
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
|
|
||||||
assert len(passes) == 0
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_with_trajectory(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should include trajectory when requested."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
rise_time = MagicMock()
|
|
||||||
rise_time.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set_time = MagicMock()
|
|
||||||
set_time.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
mock_find.return_value = ([rise_time, set_time], [True, False])
|
|
||||||
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 45.0
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
passes = predict_passes(
|
|
||||||
lat=51.5, lon=-0.1, hours=24, min_elevation=15, include_trajectory=True
|
|
||||||
)
|
|
||||||
|
|
||||||
assert len(passes) == 1
|
|
||||||
assert 'trajectory' in passes[0]
|
|
||||||
assert len(passes[0]['trajectory']) == 30
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_with_ground_track(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should include ground track when requested."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
rise_time = MagicMock()
|
|
||||||
rise_time.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set_time = MagicMock()
|
|
||||||
set_time.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
mock_find.return_value = ([rise_time, set_time], [True, False])
|
|
||||||
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 45.0
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
# Mock geocentric position
|
|
||||||
def mock_at(t):
|
|
||||||
geocentric = MagicMock()
|
|
||||||
return geocentric
|
|
||||||
|
|
||||||
mock_satellite_obj.at.side_effect = mock_at
|
|
||||||
|
|
||||||
# Mock subpoint
|
|
||||||
mock_subpoint = MagicMock()
|
|
||||||
mock_lat = MagicMock()
|
|
||||||
mock_lat.degrees = 51.5
|
|
||||||
mock_lon = MagicMock()
|
|
||||||
mock_lon.degrees = -0.1
|
|
||||||
mock_subpoint.latitude = mock_lat
|
|
||||||
mock_subpoint.longitude = mock_lon
|
|
||||||
mock_wgs84.subpoint.return_value = mock_subpoint
|
|
||||||
|
|
||||||
passes = predict_passes(
|
|
||||||
lat=51.5, lon=-0.1, hours=24, min_elevation=15, include_ground_track=True
|
|
||||||
)
|
|
||||||
|
|
||||||
assert len(passes) == 1
|
|
||||||
assert 'groundTrack' in passes[0]
|
|
||||||
assert len(passes[0]['groundTrack']) == 60
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_quality_excellent(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should mark high elevation passes as excellent."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
rise_time = MagicMock()
|
|
||||||
rise_time.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set_time = MagicMock()
|
|
||||||
set_time.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
mock_find.return_value = ([rise_time, set_time], [True, False])
|
|
||||||
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 75.0 # Excellent pass
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
|
|
||||||
assert len(passes) == 1
|
|
||||||
assert passes[0]['quality'] == 'excellent'
|
|
||||||
assert passes[0]['maxEl'] >= 60
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_quality_good(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should mark medium elevation passes as good."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
rise_time = MagicMock()
|
|
||||||
rise_time.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set_time = MagicMock()
|
|
||||||
set_time.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
mock_find.return_value = ([rise_time, set_time], [True, False])
|
|
||||||
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 45.0 # Good pass
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
|
|
||||||
assert len(passes) == 1
|
|
||||||
assert passes[0]['quality'] == 'good'
|
|
||||||
assert 30 <= passes[0]['maxEl'] < 60
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_quality_fair(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should mark low elevation passes as fair."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
rise_time = MagicMock()
|
|
||||||
rise_time.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set_time = MagicMock()
|
|
||||||
set_time.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
mock_find.return_value = ([rise_time, set_time], [True, False])
|
|
||||||
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 20.0 # Fair pass
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
|
|
||||||
assert len(passes) == 1
|
|
||||||
assert passes[0]['quality'] == 'fair'
|
|
||||||
assert passes[0]['maxEl'] < 30
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_inactive_satellite(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should skip inactive satellites."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
# Temporarily mark satellite as inactive
|
|
||||||
from utils.weather_sat import WEATHER_SATELLITES
|
|
||||||
original_active = WEATHER_SATELLITES['NOAA-18']['active']
|
|
||||||
WEATHER_SATELLITES['NOAA-18']['active'] = False
|
|
||||||
|
|
||||||
try:
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
# Should not include NOAA-18
|
|
||||||
noaa_18_passes = [p for p in passes if p['satellite'] == 'NOAA-18']
|
|
||||||
assert len(noaa_18_passes) == 0
|
|
||||||
finally:
|
|
||||||
WEATHER_SATELLITES['NOAA-18']['active'] = original_active
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_exception_handling(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should handle exceptions gracefully."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
# Make find_discrete raise exception
|
|
||||||
mock_find.side_effect = Exception('Computation error')
|
|
||||||
|
|
||||||
# Should not raise, just skip this satellite
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
# May include passes from other satellites or be empty
|
|
||||||
assert isinstance(passes, list)
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
def test_predict_passes_uses_tle_cache(self, mock_tle, mock_load):
|
|
||||||
"""predict_passes() should use live TLE cache if available."""
|
|
||||||
with patch('utils.weather_sat_predict._tle_cache', {'NOAA-18': ('NOAA-18', 'line1', 'line2')}):
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
mock_ts.now.return_value = MagicMock()
|
|
||||||
mock_ts.utc.return_value = MagicMock()
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
# Even though TLE_SATELLITES is mocked, should use _tle_cache
|
|
||||||
with patch('utils.weather_sat_predict.wgs84'), \
|
|
||||||
patch('utils.weather_sat_predict.EarthSatellite'), \
|
|
||||||
patch('utils.weather_sat_predict.find_discrete', return_value=([], [])):
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
# Should not raise
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_predict_passes_sorted_by_time(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""predict_passes() should return passes sorted by start time."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: self._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
# Two passes
|
|
||||||
rise1 = MagicMock()
|
|
||||||
rise1.utc_datetime.return_value = now + timedelta(hours=4)
|
|
||||||
set1 = MagicMock()
|
|
||||||
set1.utc_datetime.return_value = now + timedelta(hours=4, minutes=15)
|
|
||||||
rise2 = MagicMock()
|
|
||||||
rise2.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set2 = MagicMock()
|
|
||||||
set2.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
# Return in non-chronological order
|
|
||||||
mock_find.return_value = ([rise1, set1, rise2, set2], [True, False, True, False])
|
|
||||||
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 45.0
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
|
|
||||||
# Should be sorted with earliest pass first
|
|
||||||
if len(passes) >= 2:
|
|
||||||
assert passes[0]['startTimeISO'] < passes[1]['startTimeISO']
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _mock_time(dt):
|
|
||||||
"""Helper to create mock time object."""
|
|
||||||
mock_t = MagicMock()
|
|
||||||
if isinstance(dt, datetime):
|
|
||||||
mock_t.utc_datetime.return_value = dt
|
|
||||||
else:
|
|
||||||
mock_t.utc_datetime.return_value = datetime.now(timezone.utc)
|
|
||||||
return mock_t
|
|
||||||
|
|
||||||
|
|
||||||
class TestPassDataStructure:
|
|
||||||
"""Tests for pass data structure."""
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_predict.load')
|
|
||||||
@patch('utils.weather_sat_predict.TLE_SATELLITES')
|
|
||||||
@patch('utils.weather_sat_predict.wgs84')
|
|
||||||
@patch('utils.weather_sat_predict.EarthSatellite')
|
|
||||||
@patch('utils.weather_sat_predict.find_discrete')
|
|
||||||
def test_pass_data_fields(
|
|
||||||
self, mock_find, mock_sat, mock_wgs84, mock_tle, mock_load
|
|
||||||
):
|
|
||||||
"""Pass data should contain all required fields."""
|
|
||||||
mock_ts = MagicMock()
|
|
||||||
now = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
mock_now = MagicMock()
|
|
||||||
mock_now.utc_datetime.return_value = now
|
|
||||||
mock_ts.now.return_value = mock_now
|
|
||||||
mock_ts.utc.side_effect = lambda dt: TestPredictPasses._mock_time(dt)
|
|
||||||
mock_load.timescale.return_value = mock_ts
|
|
||||||
|
|
||||||
mock_tle.get.return_value = (
|
|
||||||
'NOAA-18',
|
|
||||||
'1 28654U 05018A 24001.50000000 .00000000 00000-0 00000-0 0 9999',
|
|
||||||
'2 28654 98.7000 100.0000 0001000 0.0000 0.0000 14.12500000000000'
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_observer = MagicMock()
|
|
||||||
mock_wgs84.latlon.return_value = mock_observer
|
|
||||||
|
|
||||||
mock_satellite_obj = MagicMock()
|
|
||||||
mock_sat.return_value = mock_satellite_obj
|
|
||||||
|
|
||||||
rise_time = MagicMock()
|
|
||||||
rise_time.utc_datetime.return_value = now + timedelta(hours=2)
|
|
||||||
set_time = MagicMock()
|
|
||||||
set_time.utc_datetime.return_value = now + timedelta(hours=2, minutes=15)
|
|
||||||
|
|
||||||
mock_find.return_value = ([rise_time, set_time], [True, False])
|
|
||||||
|
|
||||||
def mock_topocentric(t):
|
|
||||||
topo = MagicMock()
|
|
||||||
alt = MagicMock()
|
|
||||||
alt.degrees = 45.0
|
|
||||||
az = MagicMock()
|
|
||||||
az.degrees = 180.0
|
|
||||||
topo.altaz.return_value = (alt, az, MagicMock())
|
|
||||||
return topo
|
|
||||||
|
|
||||||
mock_diff = MagicMock()
|
|
||||||
mock_diff.at.side_effect = mock_topocentric
|
|
||||||
mock_satellite_obj.__sub__.return_value = mock_diff
|
|
||||||
|
|
||||||
passes = predict_passes(lat=51.5, lon=-0.1, hours=24, min_elevation=15)
|
|
||||||
|
|
||||||
assert len(passes) == 1
|
|
||||||
pass_data = passes[0]
|
|
||||||
|
|
||||||
# Check all required fields
|
|
||||||
required_fields = [
|
|
||||||
'id', 'satellite', 'name', 'frequency', 'mode',
|
|
||||||
'startTime', 'startTimeISO', 'endTimeISO',
|
|
||||||
'maxEl', 'maxElAz', 'riseAz', 'setAz',
|
|
||||||
'duration', 'quality'
|
|
||||||
]
|
|
||||||
for field in required_fields:
|
|
||||||
assert field in pass_data, f"Missing required field: {field}"
|
|
||||||
|
|
||||||
def test_import_error_propagates(self):
|
|
||||||
"""predict_passes() should raise ImportError if skyfield unavailable."""
|
|
||||||
with patch.dict('sys.modules', {'skyfield': None, 'skyfield.api': None}):
|
|
||||||
with pytest.raises((ImportError, AttributeError)):
|
|
||||||
predict_passes(lat=51.5, lon=-0.1)
|
|
||||||
@@ -1,801 +0,0 @@
|
|||||||
"""Tests for weather satellite routes.
|
|
||||||
|
|
||||||
Covers all weather_sat endpoints: /status, /satellites, /start, /test-decode,
|
|
||||||
/stop, /images, /passes, and scheduler endpoints.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
from unittest.mock import patch, MagicMock, mock_open
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from utils.weather_sat import WeatherSatImage, WEATHER_SATELLITES
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
|
|
||||||
class TestWeatherSatRoutes:
|
|
||||||
"""Tests for weather satellite routes."""
|
|
||||||
|
|
||||||
def test_get_status(self, client):
|
|
||||||
"""GET /weather-sat/status returns decoder status."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.get_status.return_value = {
|
|
||||||
'available': True,
|
|
||||||
'decoder': 'satdump',
|
|
||||||
'running': False,
|
|
||||||
'satellite': '',
|
|
||||||
'frequency': 0.0,
|
|
||||||
'mode': '',
|
|
||||||
'elapsed_seconds': 0,
|
|
||||||
'image_count': 0,
|
|
||||||
}
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/status')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['available'] is True
|
|
||||||
assert data['decoder'] == 'satdump'
|
|
||||||
assert data['running'] is False
|
|
||||||
|
|
||||||
def test_list_satellites(self, client):
|
|
||||||
"""GET /weather-sat/satellites returns satellite list."""
|
|
||||||
response = client.get('/weather-sat/satellites')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'ok'
|
|
||||||
assert 'satellites' in data
|
|
||||||
assert len(data['satellites']) > 0
|
|
||||||
|
|
||||||
# Check structure
|
|
||||||
sat = data['satellites'][0]
|
|
||||||
assert 'key' in sat
|
|
||||||
assert 'name' in sat
|
|
||||||
assert 'frequency' in sat
|
|
||||||
assert 'mode' in sat
|
|
||||||
assert 'description' in sat
|
|
||||||
assert 'active' in sat
|
|
||||||
|
|
||||||
# Verify NOAA-18 is in list
|
|
||||||
noaa_18 = next((s for s in data['satellites'] if s['key'] == 'NOAA-18'), None)
|
|
||||||
assert noaa_18 is not None
|
|
||||||
assert noaa_18['frequency'] == 137.9125
|
|
||||||
assert noaa_18['mode'] == 'APT'
|
|
||||||
|
|
||||||
def test_start_capture_success(self, client):
|
|
||||||
"""POST /weather-sat/start successfully starts capture."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get, \
|
|
||||||
patch('routes.weather_sat.queue.Queue') as mock_queue:
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_decoder.start.return_value = True
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'device': 0,
|
|
||||||
'gain': 40.0,
|
|
||||||
'bias_t': False,
|
|
||||||
}
|
|
||||||
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/start',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'started'
|
|
||||||
assert data['satellite'] == 'NOAA-18'
|
|
||||||
assert data['frequency'] == 137.9125
|
|
||||||
assert data['mode'] == 'APT'
|
|
||||||
assert data['device'] == 0
|
|
||||||
|
|
||||||
mock_decoder.start.assert_called_once_with(
|
|
||||||
satellite='NOAA-18',
|
|
||||||
device_index=0,
|
|
||||||
gain=40.0,
|
|
||||||
bias_t=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_start_capture_no_satdump(self, client):
|
|
||||||
"""POST /weather-sat/start returns error when SatDump unavailable."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=False):
|
|
||||||
payload = {'satellite': 'NOAA-18'}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/start',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'SatDump not installed' in data['message']
|
|
||||||
|
|
||||||
def test_start_capture_already_running(self, client):
|
|
||||||
"""POST /weather-sat/start when already running."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = True
|
|
||||||
mock_decoder.current_satellite = 'NOAA-19'
|
|
||||||
mock_decoder.current_frequency = 137.100
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {'satellite': 'NOAA-18'}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/start',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'already_running'
|
|
||||||
assert data['satellite'] == 'NOAA-19'
|
|
||||||
|
|
||||||
def test_start_capture_invalid_satellite(self, client):
|
|
||||||
"""POST /weather-sat/start with invalid satellite."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {'satellite': 'FAKE-SAT-99'}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/start',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'Invalid satellite' in data['message']
|
|
||||||
|
|
||||||
def test_start_capture_invalid_device(self, client):
|
|
||||||
"""POST /weather-sat/start with invalid device index."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {'satellite': 'NOAA-18', 'device': -1}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/start',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
|
|
||||||
def test_start_capture_invalid_gain(self, client):
|
|
||||||
"""POST /weather-sat/start with invalid gain."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {'satellite': 'NOAA-18', 'gain': 999}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/start',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
|
|
||||||
def test_start_capture_device_busy(self, client):
|
|
||||||
"""POST /weather-sat/start when SDR device is busy."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get, \
|
|
||||||
patch('app.claim_sdr_device', return_value='Device busy with pager') as mock_claim:
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {'satellite': 'NOAA-18'}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/start',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 409
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert data['error_type'] == 'DEVICE_BUSY'
|
|
||||||
assert 'Device busy' in data['message']
|
|
||||||
|
|
||||||
def test_start_capture_start_failure(self, client):
|
|
||||||
"""POST /weather-sat/start when decoder.start() fails."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_decoder.start.return_value = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {'satellite': 'NOAA-18'}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/start',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 500
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'Failed to start capture' in data['message']
|
|
||||||
|
|
||||||
def test_test_decode_success(self, client):
|
|
||||||
"""POST /weather-sat/test-decode successfully starts file decode."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get, \
|
|
||||||
patch('pathlib.Path.is_file', return_value=True), \
|
|
||||||
patch('pathlib.Path.resolve') as mock_resolve:
|
|
||||||
|
|
||||||
# Mock path resolution to be under data/
|
|
||||||
mock_path = MagicMock()
|
|
||||||
mock_path.is_relative_to.return_value = True
|
|
||||||
mock_resolve.return_value = mock_path
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_decoder.start_from_file.return_value = True
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'input_file': 'data/weather_sat/test.wav',
|
|
||||||
'sample_rate': 1000000,
|
|
||||||
}
|
|
||||||
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/test-decode',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'started'
|
|
||||||
assert data['satellite'] == 'NOAA-18'
|
|
||||||
assert data['source'] == 'file'
|
|
||||||
|
|
||||||
def test_test_decode_invalid_path(self, client):
|
|
||||||
"""POST /weather-sat/test-decode with path outside data/."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get, \
|
|
||||||
patch('pathlib.Path.resolve') as mock_resolve:
|
|
||||||
|
|
||||||
# Mock path outside allowed directory
|
|
||||||
mock_path = MagicMock()
|
|
||||||
mock_path.is_relative_to.return_value = False
|
|
||||||
mock_resolve.return_value = mock_path
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'input_file': '/etc/passwd',
|
|
||||||
}
|
|
||||||
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/test-decode',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 403
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'data/ directory' in data['message']
|
|
||||||
|
|
||||||
def test_test_decode_file_not_found(self, client):
|
|
||||||
"""POST /weather-sat/test-decode with non-existent file."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get, \
|
|
||||||
patch('pathlib.Path.is_file', return_value=False), \
|
|
||||||
patch('pathlib.Path.resolve') as mock_resolve:
|
|
||||||
|
|
||||||
mock_path = MagicMock()
|
|
||||||
mock_path.is_relative_to.return_value = True
|
|
||||||
mock_resolve.return_value = mock_path
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'input_file': 'data/missing.wav',
|
|
||||||
}
|
|
||||||
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/test-decode',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 404
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'not found' in data['message'].lower()
|
|
||||||
|
|
||||||
def test_test_decode_invalid_sample_rate(self, client):
|
|
||||||
"""POST /weather-sat/test-decode with invalid sample rate."""
|
|
||||||
with patch('routes.weather_sat.is_weather_sat_available', return_value=True), \
|
|
||||||
patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'input_file': 'data/test.wav',
|
|
||||||
'sample_rate': 100, # Too low
|
|
||||||
}
|
|
||||||
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/test-decode',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'sample_rate' in data['message']
|
|
||||||
|
|
||||||
def test_stop_capture(self, client):
|
|
||||||
"""POST /weather-sat/stop stops capture."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.device_index = 0
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.post('/weather-sat/stop')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'stopped'
|
|
||||||
mock_decoder.stop.assert_called_once()
|
|
||||||
|
|
||||||
def test_list_images_empty(self, client):
|
|
||||||
"""GET /weather-sat/images with no images."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.get_images.return_value = []
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/images')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'ok'
|
|
||||||
assert data['images'] == []
|
|
||||||
assert data['count'] == 0
|
|
||||||
|
|
||||||
def test_list_images_with_data(self, client):
|
|
||||||
"""GET /weather-sat/images with images."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
image = WeatherSatImage(
|
|
||||||
filename='NOAA-18_test.png',
|
|
||||||
path=Path('/tmp/test.png'),
|
|
||||||
satellite='NOAA-18',
|
|
||||||
mode='APT',
|
|
||||||
timestamp=datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
|
|
||||||
frequency=137.9125,
|
|
||||||
size_bytes=12345,
|
|
||||||
product='RGB Composite',
|
|
||||||
)
|
|
||||||
mock_decoder.get_images.return_value = [image]
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/images')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'ok'
|
|
||||||
assert data['count'] == 1
|
|
||||||
assert data['images'][0]['filename'] == 'NOAA-18_test.png'
|
|
||||||
assert data['images'][0]['satellite'] == 'NOAA-18'
|
|
||||||
|
|
||||||
def test_list_images_with_filter(self, client):
|
|
||||||
"""GET /weather-sat/images with satellite filter."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
image1 = WeatherSatImage(
|
|
||||||
filename='NOAA-18_test.png',
|
|
||||||
path=Path('/tmp/test1.png'),
|
|
||||||
satellite='NOAA-18',
|
|
||||||
mode='APT',
|
|
||||||
timestamp=datetime.now(timezone.utc),
|
|
||||||
frequency=137.9125,
|
|
||||||
)
|
|
||||||
image2 = WeatherSatImage(
|
|
||||||
filename='NOAA-19_test.png',
|
|
||||||
path=Path('/tmp/test2.png'),
|
|
||||||
satellite='NOAA-19',
|
|
||||||
mode='APT',
|
|
||||||
timestamp=datetime.now(timezone.utc),
|
|
||||||
frequency=137.100,
|
|
||||||
)
|
|
||||||
mock_decoder.get_images.return_value = [image1, image2]
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/images?satellite=NOAA-18')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['count'] == 1
|
|
||||||
assert data['images'][0]['satellite'] == 'NOAA-18'
|
|
||||||
|
|
||||||
def test_list_images_with_limit(self, client):
|
|
||||||
"""GET /weather-sat/images with limit."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
images = [
|
|
||||||
WeatherSatImage(
|
|
||||||
filename=f'test{i}.png',
|
|
||||||
path=Path(f'/tmp/test{i}.png'),
|
|
||||||
satellite='NOAA-18',
|
|
||||||
mode='APT',
|
|
||||||
timestamp=datetime.now(timezone.utc),
|
|
||||||
frequency=137.9125,
|
|
||||||
)
|
|
||||||
for i in range(10)
|
|
||||||
]
|
|
||||||
mock_decoder.get_images.return_value = images
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/images?limit=5')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['count'] == 5
|
|
||||||
|
|
||||||
def test_get_image_success(self, client):
|
|
||||||
"""GET /weather-sat/images/<filename> serves image."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get, \
|
|
||||||
patch('routes.weather_sat.send_file') as mock_send, \
|
|
||||||
patch('pathlib.Path.exists', return_value=True):
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder._output_dir = Path('/tmp')
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
mock_send.return_value = MagicMock()
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/images/test_image.png')
|
|
||||||
mock_send.assert_called_once()
|
|
||||||
call_args = mock_send.call_args
|
|
||||||
assert call_args[1]['mimetype'] == 'image/png'
|
|
||||||
|
|
||||||
def test_get_image_invalid_filename(self, client):
|
|
||||||
"""GET /weather-sat/images/<filename> with invalid filename."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/images/../../../etc/passwd')
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'Invalid filename' in data['message']
|
|
||||||
|
|
||||||
def test_get_image_wrong_extension(self, client):
|
|
||||||
"""GET /weather-sat/images/<filename> with wrong extension."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/images/test.txt')
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert 'PNG/JPG' in data['message']
|
|
||||||
|
|
||||||
def test_get_image_not_found(self, client):
|
|
||||||
"""GET /weather-sat/images/<filename> for non-existent image."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get, \
|
|
||||||
patch('pathlib.Path.exists', return_value=False):
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder._output_dir = Path('/tmp')
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/images/missing.png')
|
|
||||||
assert response.status_code == 404
|
|
||||||
|
|
||||||
def test_delete_image_success(self, client):
|
|
||||||
"""DELETE /weather-sat/images/<filename> deletes image."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.delete_image.return_value = True
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.delete('/weather-sat/images/test.png')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'deleted'
|
|
||||||
assert data['filename'] == 'test.png'
|
|
||||||
|
|
||||||
def test_delete_image_not_found(self, client):
|
|
||||||
"""DELETE /weather-sat/images/<filename> for non-existent image."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.delete_image.return_value = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.delete('/weather-sat/images/missing.png')
|
|
||||||
assert response.status_code == 404
|
|
||||||
|
|
||||||
def test_delete_all_images(self, client):
|
|
||||||
"""DELETE /weather-sat/images deletes all images."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_decoder') as mock_get:
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.delete_all_images.return_value = 5
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
response = client.delete('/weather-sat/images')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'ok'
|
|
||||||
assert data['deleted'] == 5
|
|
||||||
|
|
||||||
def test_stream_progress(self, client):
|
|
||||||
"""GET /weather-sat/stream returns SSE stream."""
|
|
||||||
response = client.get('/weather-sat/stream')
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.mimetype == 'text/event-stream'
|
|
||||||
assert response.headers['Cache-Control'] == 'no-cache'
|
|
||||||
|
|
||||||
def test_get_passes_missing_params(self, client):
|
|
||||||
"""GET /weather-sat/passes without required params."""
|
|
||||||
response = client.get('/weather-sat/passes')
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'latitude and longitude' in data['message']
|
|
||||||
|
|
||||||
def test_get_passes_invalid_coords(self, client):
|
|
||||||
"""GET /weather-sat/passes with invalid coordinates."""
|
|
||||||
response = client.get('/weather-sat/passes?latitude=999&longitude=0')
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
|
|
||||||
def test_get_passes_success(self, client):
|
|
||||||
"""GET /weather-sat/passes successfully predicts passes."""
|
|
||||||
with patch('routes.weather_sat.predict_passes') as mock_predict:
|
|
||||||
mock_predict.return_value = [
|
|
||||||
{
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTime': '2024-01-01 12:00 UTC',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'maxElAz': 180.0,
|
|
||||||
'riseAz': 160.0,
|
|
||||||
'setAz': 200.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/passes?latitude=51.5&longitude=-0.1')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'ok'
|
|
||||||
assert data['count'] == 1
|
|
||||||
assert data['passes'][0]['satellite'] == 'NOAA-18'
|
|
||||||
|
|
||||||
def test_get_passes_with_options(self, client):
|
|
||||||
"""GET /weather-sat/passes with trajectory and ground track."""
|
|
||||||
with patch('routes.weather_sat.predict_passes') as mock_predict:
|
|
||||||
mock_predict.return_value = []
|
|
||||||
|
|
||||||
response = client.get(
|
|
||||||
'/weather-sat/passes?latitude=51.5&longitude=-0.1&'
|
|
||||||
'hours=48&min_elevation=20&trajectory=true&ground_track=true'
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
|
|
||||||
mock_predict.assert_called_once()
|
|
||||||
call_kwargs = mock_predict.call_args[1]
|
|
||||||
assert call_kwargs['lat'] == 51.5
|
|
||||||
assert call_kwargs['lon'] == -0.1
|
|
||||||
assert call_kwargs['hours'] == 48
|
|
||||||
assert call_kwargs['min_elevation'] == 20.0
|
|
||||||
assert call_kwargs['include_trajectory'] is True
|
|
||||||
assert call_kwargs['include_ground_track'] is True
|
|
||||||
|
|
||||||
def test_get_passes_import_error(self, client):
|
|
||||||
"""GET /weather-sat/passes when skyfield not installed."""
|
|
||||||
with patch('routes.weather_sat.predict_passes', side_effect=ImportError):
|
|
||||||
response = client.get('/weather-sat/passes?latitude=51.5&longitude=-0.1')
|
|
||||||
assert response.status_code == 503
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'skyfield' in data['message']
|
|
||||||
|
|
||||||
def test_get_passes_prediction_error(self, client):
|
|
||||||
"""GET /weather-sat/passes when prediction fails."""
|
|
||||||
with patch('routes.weather_sat.predict_passes', side_effect=Exception('TLE error')):
|
|
||||||
response = client.get('/weather-sat/passes?latitude=51.5&longitude=-0.1')
|
|
||||||
assert response.status_code == 500
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
|
|
||||||
|
|
||||||
class TestWeatherSatScheduler:
|
|
||||||
"""Tests for weather satellite scheduler endpoints."""
|
|
||||||
|
|
||||||
def test_enable_schedule_success(self, client):
|
|
||||||
"""POST /weather-sat/schedule/enable enables scheduler."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_scheduler') as mock_get:
|
|
||||||
mock_scheduler = MagicMock()
|
|
||||||
mock_scheduler.enable.return_value = {
|
|
||||||
'enabled': True,
|
|
||||||
'observer': {'latitude': 51.5, 'longitude': -0.1},
|
|
||||||
'device': 0,
|
|
||||||
'gain': 40.0,
|
|
||||||
'bias_t': False,
|
|
||||||
'min_elevation': 15.0,
|
|
||||||
'scheduled_count': 3,
|
|
||||||
'total_passes': 3,
|
|
||||||
}
|
|
||||||
mock_get.return_value = mock_scheduler
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
'latitude': 51.5,
|
|
||||||
'longitude': -0.1,
|
|
||||||
'min_elevation': 15,
|
|
||||||
'device': 0,
|
|
||||||
'gain': 40.0,
|
|
||||||
'bias_t': False,
|
|
||||||
}
|
|
||||||
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/schedule/enable',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'ok'
|
|
||||||
assert data['enabled'] is True
|
|
||||||
|
|
||||||
def test_enable_schedule_missing_coords(self, client):
|
|
||||||
"""POST /weather-sat/schedule/enable without coordinates."""
|
|
||||||
payload = {'device': 0}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/schedule/enable',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'latitude and longitude' in data['message']
|
|
||||||
|
|
||||||
def test_enable_schedule_invalid_coords(self, client):
|
|
||||||
"""POST /weather-sat/schedule/enable with invalid coordinates."""
|
|
||||||
payload = {'latitude': 999, 'longitude': 0}
|
|
||||||
response = client.post(
|
|
||||||
'/weather-sat/schedule/enable',
|
|
||||||
data=json.dumps(payload),
|
|
||||||
content_type='application/json'
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
|
|
||||||
def test_disable_schedule(self, client):
|
|
||||||
"""POST /weather-sat/schedule/disable disables scheduler."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_scheduler') as mock_get:
|
|
||||||
mock_scheduler = MagicMock()
|
|
||||||
mock_scheduler.disable.return_value = {'status': 'disabled'}
|
|
||||||
mock_get.return_value = mock_scheduler
|
|
||||||
|
|
||||||
response = client.post('/weather-sat/schedule/disable')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'disabled'
|
|
||||||
|
|
||||||
def test_schedule_status(self, client):
|
|
||||||
"""GET /weather-sat/schedule/status returns scheduler status."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_scheduler') as mock_get:
|
|
||||||
mock_scheduler = MagicMock()
|
|
||||||
mock_scheduler.get_status.return_value = {
|
|
||||||
'enabled': False,
|
|
||||||
'observer': {'latitude': 0, 'longitude': 0},
|
|
||||||
'device': 0,
|
|
||||||
'gain': 40.0,
|
|
||||||
'bias_t': False,
|
|
||||||
'min_elevation': 15.0,
|
|
||||||
'scheduled_count': 0,
|
|
||||||
'total_passes': 0,
|
|
||||||
}
|
|
||||||
mock_get.return_value = mock_scheduler
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/schedule/status')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert 'enabled' in data
|
|
||||||
|
|
||||||
def test_schedule_passes(self, client):
|
|
||||||
"""GET /weather-sat/schedule/passes lists scheduled passes."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_scheduler') as mock_get:
|
|
||||||
mock_scheduler = MagicMock()
|
|
||||||
mock_scheduler.get_passes.return_value = [
|
|
||||||
{
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'status': 'scheduled',
|
|
||||||
}
|
|
||||||
]
|
|
||||||
mock_get.return_value = mock_scheduler
|
|
||||||
|
|
||||||
response = client.get('/weather-sat/schedule/passes')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'ok'
|
|
||||||
assert data['count'] == 1
|
|
||||||
|
|
||||||
def test_skip_pass_success(self, client):
|
|
||||||
"""POST /weather-sat/schedule/skip/<id> skips a pass."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_scheduler') as mock_get:
|
|
||||||
mock_scheduler = MagicMock()
|
|
||||||
mock_scheduler.skip_pass.return_value = True
|
|
||||||
mock_get.return_value = mock_scheduler
|
|
||||||
|
|
||||||
response = client.post('/weather-sat/schedule/skip/NOAA-18_202401011200')
|
|
||||||
assert response.status_code == 200
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'skipped'
|
|
||||||
assert data['pass_id'] == 'NOAA-18_202401011200'
|
|
||||||
|
|
||||||
def test_skip_pass_not_found(self, client):
|
|
||||||
"""POST /weather-sat/schedule/skip/<id> for non-existent pass."""
|
|
||||||
with patch('routes.weather_sat.get_weather_sat_scheduler') as mock_get:
|
|
||||||
mock_scheduler = MagicMock()
|
|
||||||
mock_scheduler.skip_pass.return_value = False
|
|
||||||
mock_get.return_value = mock_scheduler
|
|
||||||
|
|
||||||
response = client.post('/weather-sat/schedule/skip/nonexistent')
|
|
||||||
assert response.status_code == 404
|
|
||||||
|
|
||||||
def test_skip_pass_invalid_id(self, client):
|
|
||||||
"""POST /weather-sat/schedule/skip/<id> with invalid ID."""
|
|
||||||
response = client.post('/weather-sat/schedule/skip/../../../etc/passwd')
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.get_json()
|
|
||||||
assert data['status'] == 'error'
|
|
||||||
assert 'Invalid pass ID' in data['message']
|
|
||||||
@@ -1,779 +0,0 @@
|
|||||||
"""Tests for weather satellite auto-scheduler.
|
|
||||||
|
|
||||||
Covers WeatherSatScheduler class, pass scheduling, timer management,
|
|
||||||
and automatic capture execution.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from datetime import datetime, timezone, timedelta
|
|
||||||
from unittest.mock import patch, MagicMock, call
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from utils.weather_sat_scheduler import (
|
|
||||||
WeatherSatScheduler,
|
|
||||||
ScheduledPass,
|
|
||||||
get_weather_sat_scheduler,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestScheduledPass:
|
|
||||||
"""Tests for ScheduledPass class."""
|
|
||||||
|
|
||||||
def test_scheduled_pass_initialization(self):
|
|
||||||
"""ScheduledPass should initialize from pass data."""
|
|
||||||
pass_data = {
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
assert sp.id == 'NOAA-18_202401011200'
|
|
||||||
assert sp.satellite == 'NOAA-18'
|
|
||||||
assert sp.name == 'NOAA 18'
|
|
||||||
assert sp.frequency == 137.9125
|
|
||||||
assert sp.mode == 'APT'
|
|
||||||
assert sp.max_el == 45.0
|
|
||||||
assert sp.duration == 15.0
|
|
||||||
assert sp.quality == 'good'
|
|
||||||
assert sp.status == 'scheduled'
|
|
||||||
assert sp.skipped is False
|
|
||||||
|
|
||||||
def test_scheduled_pass_start_dt(self):
|
|
||||||
"""ScheduledPass.start_dt should parse ISO datetime."""
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
assert sp.start_dt.year == 2024
|
|
||||||
assert sp.start_dt.month == 1
|
|
||||||
assert sp.start_dt.day == 1
|
|
||||||
assert sp.start_dt.hour == 12
|
|
||||||
assert sp.start_dt.tzinfo == timezone.utc
|
|
||||||
|
|
||||||
def test_scheduled_pass_end_dt(self):
|
|
||||||
"""ScheduledPass.end_dt should parse ISO datetime."""
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
assert sp.end_dt.year == 2024
|
|
||||||
assert sp.end_dt.minute == 15
|
|
||||||
|
|
||||||
def test_scheduled_pass_to_dict(self):
|
|
||||||
"""ScheduledPass.to_dict() should serialize correctly."""
|
|
||||||
pass_data = {
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
sp.status = 'complete'
|
|
||||||
|
|
||||||
data = sp.to_dict()
|
|
||||||
|
|
||||||
assert data['id'] == 'NOAA-18_202401011200'
|
|
||||||
assert data['satellite'] == 'NOAA-18'
|
|
||||||
assert data['status'] == 'complete'
|
|
||||||
assert data['skipped'] is False
|
|
||||||
|
|
||||||
|
|
||||||
class TestWeatherSatScheduler:
|
|
||||||
"""Tests for WeatherSatScheduler class."""
|
|
||||||
|
|
||||||
def test_scheduler_initialization(self):
|
|
||||||
"""Scheduler should initialize with defaults."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
|
|
||||||
assert scheduler.enabled is False
|
|
||||||
assert scheduler._lat == 0.0
|
|
||||||
assert scheduler._lon == 0.0
|
|
||||||
assert scheduler._min_elevation == 15.0
|
|
||||||
assert scheduler._device == 0
|
|
||||||
assert scheduler._gain == 40.0
|
|
||||||
assert scheduler._bias_t is False
|
|
||||||
assert scheduler._passes == []
|
|
||||||
|
|
||||||
def test_set_callbacks(self):
|
|
||||||
"""Scheduler should accept callbacks."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
progress_cb = MagicMock()
|
|
||||||
event_cb = MagicMock()
|
|
||||||
|
|
||||||
scheduler.set_callbacks(progress_cb, event_cb)
|
|
||||||
|
|
||||||
assert scheduler._progress_callback == progress_cb
|
|
||||||
assert scheduler._event_callback == event_cb
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.WeatherSatScheduler._refresh_passes')
|
|
||||||
def test_enable(self, mock_refresh):
|
|
||||||
"""enable() should start scheduler."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
|
|
||||||
result = scheduler.enable(
|
|
||||||
lat=51.5,
|
|
||||||
lon=-0.1,
|
|
||||||
min_elevation=20.0,
|
|
||||||
device=1,
|
|
||||||
gain=35.0,
|
|
||||||
bias_t=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert scheduler._enabled is True
|
|
||||||
assert scheduler._lat == 51.5
|
|
||||||
assert scheduler._lon == -0.1
|
|
||||||
assert scheduler._min_elevation == 20.0
|
|
||||||
assert scheduler._device == 1
|
|
||||||
assert scheduler._gain == 35.0
|
|
||||||
assert scheduler._bias_t is True
|
|
||||||
mock_refresh.assert_called_once()
|
|
||||||
assert 'enabled' in result
|
|
||||||
|
|
||||||
def test_disable(self):
|
|
||||||
"""disable() should stop scheduler and cancel timers."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
|
|
||||||
# Add mock timer
|
|
||||||
mock_timer = MagicMock()
|
|
||||||
scheduler._refresh_timer = mock_timer
|
|
||||||
|
|
||||||
# Add pass with timer
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
sp._timer = MagicMock()
|
|
||||||
sp._stop_timer = MagicMock()
|
|
||||||
scheduler._passes = [sp]
|
|
||||||
|
|
||||||
result = scheduler.disable()
|
|
||||||
|
|
||||||
assert scheduler._enabled is False
|
|
||||||
assert scheduler._passes == []
|
|
||||||
mock_timer.cancel.assert_called_once()
|
|
||||||
sp._timer.cancel.assert_called_once()
|
|
||||||
sp._stop_timer.cancel.assert_called_once()
|
|
||||||
assert result['status'] == 'disabled'
|
|
||||||
|
|
||||||
def test_skip_pass_success(self):
|
|
||||||
"""skip_pass() should skip a scheduled pass."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
event_cb = MagicMock()
|
|
||||||
scheduler.set_callbacks(MagicMock(), event_cb)
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
sp._timer = MagicMock()
|
|
||||||
scheduler._passes = [sp]
|
|
||||||
|
|
||||||
result = scheduler.skip_pass('NOAA-18_202401011200')
|
|
||||||
|
|
||||||
assert result is True
|
|
||||||
assert sp.status == 'skipped'
|
|
||||||
assert sp.skipped is True
|
|
||||||
sp._timer.cancel.assert_called_once()
|
|
||||||
event_cb.assert_called_once()
|
|
||||||
|
|
||||||
def test_skip_pass_not_found(self):
|
|
||||||
"""skip_pass() should return False for non-existent pass."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
|
|
||||||
result = scheduler.skip_pass('NONEXISTENT')
|
|
||||||
|
|
||||||
assert result is False
|
|
||||||
|
|
||||||
def test_skip_pass_already_complete(self):
|
|
||||||
"""skip_pass() should not skip already complete passes."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
sp.status = 'complete'
|
|
||||||
scheduler._passes = [sp]
|
|
||||||
|
|
||||||
result = scheduler.skip_pass('NOAA-18_202401011200')
|
|
||||||
|
|
||||||
assert result is False
|
|
||||||
assert sp.status == 'complete'
|
|
||||||
|
|
||||||
def test_get_status(self):
|
|
||||||
"""get_status() should return scheduler state."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
scheduler._lat = 51.5
|
|
||||||
scheduler._lon = -0.1
|
|
||||||
scheduler._device = 0
|
|
||||||
scheduler._gain = 40.0
|
|
||||||
scheduler._bias_t = False
|
|
||||||
scheduler._min_elevation = 15.0
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
scheduler._passes = [sp]
|
|
||||||
|
|
||||||
status = scheduler.get_status()
|
|
||||||
|
|
||||||
assert status['enabled'] is True
|
|
||||||
assert status['observer']['latitude'] == 51.5
|
|
||||||
assert status['observer']['longitude'] == -0.1
|
|
||||||
assert status['device'] == 0
|
|
||||||
assert status['gain'] == 40.0
|
|
||||||
assert status['bias_t'] is False
|
|
||||||
assert status['min_elevation'] == 15.0
|
|
||||||
assert status['scheduled_count'] == 1
|
|
||||||
assert status['total_passes'] == 1
|
|
||||||
|
|
||||||
def test_get_passes(self):
|
|
||||||
"""get_passes() should return list of scheduled passes."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
scheduler._passes = [sp]
|
|
||||||
|
|
||||||
passes = scheduler.get_passes()
|
|
||||||
|
|
||||||
assert len(passes) == 1
|
|
||||||
assert passes[0]['id'] == 'NOAA-18_202401011200'
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.predict_passes')
|
|
||||||
@patch('threading.Timer')
|
|
||||||
def test_refresh_passes(self, mock_timer, mock_predict):
|
|
||||||
"""_refresh_passes() should schedule future passes."""
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
future_pass = {
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': (now + timedelta(hours=2)).isoformat(),
|
|
||||||
'endTimeISO': (now + timedelta(hours=2, minutes=15)).isoformat(),
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
mock_predict.return_value = [future_pass]
|
|
||||||
|
|
||||||
mock_timer_instance = MagicMock()
|
|
||||||
mock_timer.return_value = mock_timer_instance
|
|
||||||
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
scheduler._lat = 51.5
|
|
||||||
scheduler._lon = -0.1
|
|
||||||
|
|
||||||
scheduler._refresh_passes()
|
|
||||||
|
|
||||||
mock_predict.assert_called_once()
|
|
||||||
assert len(scheduler._passes) == 1
|
|
||||||
assert scheduler._passes[0].satellite == 'NOAA-18'
|
|
||||||
mock_timer_instance.start.assert_called()
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.predict_passes')
|
|
||||||
def test_refresh_passes_skip_past(self, mock_predict):
|
|
||||||
"""_refresh_passes() should skip passes that already started."""
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
past_pass = {
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': (now - timedelta(hours=1)).isoformat(),
|
|
||||||
'endTimeISO': (now - timedelta(hours=1) + timedelta(minutes=15)).isoformat(),
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
mock_predict.return_value = [past_pass]
|
|
||||||
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
scheduler._lat = 51.5
|
|
||||||
scheduler._lon = -0.1
|
|
||||||
|
|
||||||
scheduler._refresh_passes()
|
|
||||||
|
|
||||||
# Should not schedule past passes
|
|
||||||
assert len(scheduler._passes) == 0
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.predict_passes')
|
|
||||||
def test_refresh_passes_disabled(self, mock_predict):
|
|
||||||
"""_refresh_passes() should do nothing when disabled."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = False
|
|
||||||
|
|
||||||
scheduler._refresh_passes()
|
|
||||||
|
|
||||||
mock_predict.assert_not_called()
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.predict_passes')
|
|
||||||
def test_refresh_passes_error_handling(self, mock_predict):
|
|
||||||
"""_refresh_passes() should handle prediction errors."""
|
|
||||||
mock_predict.side_effect = Exception('TLE error')
|
|
||||||
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
scheduler._lat = 51.5
|
|
||||||
scheduler._lon = -0.1
|
|
||||||
|
|
||||||
# Should not raise
|
|
||||||
scheduler._refresh_passes()
|
|
||||||
|
|
||||||
assert len(scheduler._passes) == 0
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.get_weather_sat_decoder')
|
|
||||||
def test_execute_capture_disabled(self, mock_get):
|
|
||||||
"""_execute_capture() should do nothing when disabled."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = False
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
scheduler._execute_capture(sp)
|
|
||||||
|
|
||||||
mock_get.assert_not_called()
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.get_weather_sat_decoder')
|
|
||||||
def test_execute_capture_skipped(self, mock_get):
|
|
||||||
"""_execute_capture() should do nothing for skipped passes."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
sp.skipped = True
|
|
||||||
|
|
||||||
scheduler._execute_capture(sp)
|
|
||||||
|
|
||||||
mock_get.assert_not_called()
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.get_weather_sat_decoder')
|
|
||||||
def test_execute_capture_decoder_busy(self, mock_get):
|
|
||||||
"""_execute_capture() should skip when decoder is busy."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
event_cb = MagicMock()
|
|
||||||
scheduler.set_callbacks(MagicMock(), event_cb)
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = True
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
scheduler._execute_capture(sp)
|
|
||||||
|
|
||||||
assert sp.status == 'skipped'
|
|
||||||
assert sp.skipped is True
|
|
||||||
event_cb.assert_called_once()
|
|
||||||
event_data = event_cb.call_args[0][0]
|
|
||||||
assert event_data['type'] == 'schedule_capture_skipped'
|
|
||||||
assert event_data['reason'] == 'sdr_busy'
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.get_weather_sat_decoder')
|
|
||||||
@patch('threading.Timer')
|
|
||||||
def test_execute_capture_success(self, mock_timer, mock_get):
|
|
||||||
"""_execute_capture() should start capture."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
scheduler._device = 0
|
|
||||||
scheduler._gain = 40.0
|
|
||||||
scheduler._bias_t = False
|
|
||||||
progress_cb = MagicMock()
|
|
||||||
event_cb = MagicMock()
|
|
||||||
scheduler.set_callbacks(progress_cb, event_cb)
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_decoder.start.return_value = True
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
mock_timer_instance = MagicMock()
|
|
||||||
mock_timer.return_value = mock_timer_instance
|
|
||||||
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': (now + timedelta(seconds=10)).isoformat(),
|
|
||||||
'endTimeISO': (now + timedelta(minutes=15)).isoformat(),
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
scheduler._execute_capture(sp)
|
|
||||||
|
|
||||||
assert sp.status == 'capturing'
|
|
||||||
mock_decoder.set_callback.assert_called_once_with(progress_cb)
|
|
||||||
mock_decoder.start.assert_called_once_with(
|
|
||||||
satellite='NOAA-18',
|
|
||||||
device_index=0,
|
|
||||||
gain=40.0,
|
|
||||||
bias_t=False,
|
|
||||||
)
|
|
||||||
event_cb.assert_called_once()
|
|
||||||
event_data = event_cb.call_args[0][0]
|
|
||||||
assert event_data['type'] == 'schedule_capture_start'
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.get_weather_sat_decoder')
|
|
||||||
def test_execute_capture_start_failed(self, mock_get):
|
|
||||||
"""_execute_capture() should handle start failure."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
scheduler._enabled = True
|
|
||||||
event_cb = MagicMock()
|
|
||||||
scheduler.set_callbacks(MagicMock(), event_cb)
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_decoder.start.return_value = False
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
scheduler._execute_capture(sp)
|
|
||||||
|
|
||||||
assert sp.status == 'skipped'
|
|
||||||
event_cb.assert_called_once()
|
|
||||||
event_data = event_cb.call_args[0][0]
|
|
||||||
assert event_data['reason'] == 'start_failed'
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.get_weather_sat_decoder')
|
|
||||||
def test_stop_capture(self, mock_get):
|
|
||||||
"""_stop_capture() should stop decoder."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = True
|
|
||||||
mock_get.return_value = mock_decoder
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
scheduler._stop_capture(sp)
|
|
||||||
|
|
||||||
mock_decoder.stop.assert_called_once()
|
|
||||||
|
|
||||||
def test_on_capture_complete(self):
|
|
||||||
"""_on_capture_complete() should mark pass complete and emit event."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
event_cb = MagicMock()
|
|
||||||
scheduler.set_callbacks(MagicMock(), event_cb)
|
|
||||||
release_fn = MagicMock()
|
|
||||||
|
|
||||||
pass_data = {
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': '2024-01-01T12:00:00+00:00',
|
|
||||||
'endTimeISO': '2024-01-01T12:15:00+00:00',
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
sp = ScheduledPass(pass_data)
|
|
||||||
|
|
||||||
scheduler._on_capture_complete(sp, release_fn)
|
|
||||||
|
|
||||||
assert sp.status == 'complete'
|
|
||||||
release_fn.assert_called_once()
|
|
||||||
event_cb.assert_called_once()
|
|
||||||
event_data = event_cb.call_args[0][0]
|
|
||||||
assert event_data['type'] == 'schedule_capture_complete'
|
|
||||||
|
|
||||||
def test_emit_event(self):
|
|
||||||
"""_emit_event() should call event callback."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
event_cb = MagicMock()
|
|
||||||
scheduler.set_callbacks(MagicMock(), event_cb)
|
|
||||||
|
|
||||||
event = {'type': 'test_event', 'data': 'test'}
|
|
||||||
scheduler._emit_event(event)
|
|
||||||
|
|
||||||
event_cb.assert_called_once_with(event)
|
|
||||||
|
|
||||||
def test_emit_event_no_callback(self):
|
|
||||||
"""_emit_event() should handle missing callback."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
|
|
||||||
event = {'type': 'test_event'}
|
|
||||||
scheduler._emit_event(event) # Should not raise
|
|
||||||
|
|
||||||
def test_emit_event_callback_exception(self):
|
|
||||||
"""_emit_event() should handle callback exceptions."""
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
event_cb = MagicMock(side_effect=Exception('Callback error'))
|
|
||||||
scheduler.set_callbacks(MagicMock(), event_cb)
|
|
||||||
|
|
||||||
event = {'type': 'test_event'}
|
|
||||||
scheduler._emit_event(event) # Should not raise
|
|
||||||
|
|
||||||
|
|
||||||
class TestGlobalScheduler:
|
|
||||||
"""Tests for global scheduler singleton."""
|
|
||||||
|
|
||||||
def test_get_weather_sat_scheduler_singleton(self):
|
|
||||||
"""get_weather_sat_scheduler() should return singleton."""
|
|
||||||
import utils.weather_sat_scheduler as mod
|
|
||||||
old = mod._scheduler
|
|
||||||
mod._scheduler = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
scheduler1 = get_weather_sat_scheduler()
|
|
||||||
scheduler2 = get_weather_sat_scheduler()
|
|
||||||
|
|
||||||
assert scheduler1 is scheduler2
|
|
||||||
finally:
|
|
||||||
mod._scheduler = old
|
|
||||||
|
|
||||||
def test_get_weather_sat_scheduler_thread_safe(self):
|
|
||||||
"""get_weather_sat_scheduler() should be thread-safe."""
|
|
||||||
import utils.weather_sat_scheduler as mod
|
|
||||||
old = mod._scheduler
|
|
||||||
mod._scheduler = None
|
|
||||||
|
|
||||||
schedulers = []
|
|
||||||
|
|
||||||
def create_scheduler():
|
|
||||||
schedulers.append(get_weather_sat_scheduler())
|
|
||||||
|
|
||||||
try:
|
|
||||||
threads = [threading.Thread(target=create_scheduler) for _ in range(10)]
|
|
||||||
for t in threads:
|
|
||||||
t.start()
|
|
||||||
for t in threads:
|
|
||||||
t.join()
|
|
||||||
|
|
||||||
# All should be the same instance
|
|
||||||
assert all(s is schedulers[0] for s in schedulers)
|
|
||||||
finally:
|
|
||||||
mod._scheduler = old
|
|
||||||
|
|
||||||
|
|
||||||
class TestSchedulerConfiguration:
|
|
||||||
"""Tests for scheduler configuration constants."""
|
|
||||||
|
|
||||||
def test_config_constants(self):
|
|
||||||
"""Scheduler should have configuration constants."""
|
|
||||||
from utils.weather_sat_scheduler import (
|
|
||||||
WEATHER_SAT_SCHEDULE_REFRESH_MINUTES,
|
|
||||||
WEATHER_SAT_CAPTURE_BUFFER_SECONDS,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert isinstance(WEATHER_SAT_SCHEDULE_REFRESH_MINUTES, int)
|
|
||||||
assert isinstance(WEATHER_SAT_CAPTURE_BUFFER_SECONDS, int)
|
|
||||||
assert WEATHER_SAT_SCHEDULE_REFRESH_MINUTES > 0
|
|
||||||
assert WEATHER_SAT_CAPTURE_BUFFER_SECONDS >= 0
|
|
||||||
|
|
||||||
|
|
||||||
class TestSchedulerIntegration:
|
|
||||||
"""Integration tests for scheduler."""
|
|
||||||
|
|
||||||
@patch('utils.weather_sat_scheduler.predict_passes')
|
|
||||||
@patch('utils.weather_sat_scheduler.get_weather_sat_decoder')
|
|
||||||
@patch('threading.Timer')
|
|
||||||
def test_full_scheduling_cycle(self, mock_timer, mock_get_decoder, mock_predict):
|
|
||||||
"""Test complete scheduling cycle from enable to execute."""
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
future_pass = {
|
|
||||||
'id': 'NOAA-18_202401011200',
|
|
||||||
'satellite': 'NOAA-18',
|
|
||||||
'name': 'NOAA 18',
|
|
||||||
'frequency': 137.9125,
|
|
||||||
'mode': 'APT',
|
|
||||||
'startTimeISO': (now + timedelta(hours=2)).isoformat(),
|
|
||||||
'endTimeISO': (now + timedelta(hours=2, minutes=15)).isoformat(),
|
|
||||||
'maxEl': 45.0,
|
|
||||||
'duration': 15.0,
|
|
||||||
'quality': 'good',
|
|
||||||
}
|
|
||||||
mock_predict.return_value = [future_pass]
|
|
||||||
|
|
||||||
mock_timer_instance = MagicMock()
|
|
||||||
mock_timer.return_value = mock_timer_instance
|
|
||||||
|
|
||||||
mock_decoder = MagicMock()
|
|
||||||
mock_decoder.is_running = False
|
|
||||||
mock_decoder.start.return_value = True
|
|
||||||
mock_get_decoder.return_value = mock_decoder
|
|
||||||
|
|
||||||
scheduler = WeatherSatScheduler()
|
|
||||||
progress_cb = MagicMock()
|
|
||||||
event_cb = MagicMock()
|
|
||||||
scheduler.set_callbacks(progress_cb, event_cb)
|
|
||||||
|
|
||||||
# Enable scheduler
|
|
||||||
result = scheduler.enable(lat=51.5, lon=-0.1)
|
|
||||||
|
|
||||||
assert result['enabled'] is True
|
|
||||||
assert len(scheduler._passes) == 1
|
|
||||||
assert scheduler._passes[0].satellite == 'NOAA-18'
|
|
||||||
|
|
||||||
# Simulate timer firing (capture start)
|
|
||||||
scheduler._execute_capture(scheduler._passes[0])
|
|
||||||
|
|
||||||
assert scheduler._passes[0].status == 'capturing'
|
|
||||||
mock_decoder.start.assert_called_once()
|
|
||||||
|
|
||||||
# Simulate completion
|
|
||||||
release_fn = MagicMock()
|
|
||||||
scheduler._on_capture_complete(scheduler._passes[0], release_fn)
|
|
||||||
|
|
||||||
assert scheduler._passes[0].status == 'complete'
|
|
||||||
release_fn.assert_called_once()
|
|
||||||
|
|
||||||
# Disable scheduler
|
|
||||||
scheduler.disable()
|
|
||||||
|
|
||||||
assert scheduler.enabled is False
|
|
||||||
assert len(scheduler._passes) == 0
|
|
||||||
-443
@@ -1,443 +0,0 @@
|
|||||||
"""Alerting engine for cross-mode events."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import queue
|
|
||||||
import re
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from typing import Any, Generator
|
|
||||||
|
|
||||||
from config import ALERT_WEBHOOK_URL, ALERT_WEBHOOK_TIMEOUT, ALERT_WEBHOOK_SECRET
|
|
||||||
from utils.database import get_db
|
|
||||||
|
|
||||||
logger = logging.getLogger('intercept.alerts')
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class AlertRule:
|
|
||||||
id: int
|
|
||||||
name: str
|
|
||||||
mode: str | None
|
|
||||||
event_type: str | None
|
|
||||||
match: dict
|
|
||||||
severity: str
|
|
||||||
enabled: bool
|
|
||||||
notify: dict
|
|
||||||
created_at: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class AlertManager:
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self._queue: queue.Queue = queue.Queue(maxsize=1000)
|
|
||||||
self._rules_cache: list[AlertRule] = []
|
|
||||||
self._rules_loaded_at = 0.0
|
|
||||||
self._cache_lock = threading.Lock()
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
# Rule management
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
|
|
||||||
def invalidate_cache(self) -> None:
|
|
||||||
with self._cache_lock:
|
|
||||||
self._rules_loaded_at = 0.0
|
|
||||||
|
|
||||||
def _load_rules(self) -> None:
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute('''
|
|
||||||
SELECT id, name, mode, event_type, match, severity, enabled, notify, created_at
|
|
||||||
FROM alert_rules
|
|
||||||
WHERE enabled = 1
|
|
||||||
ORDER BY id ASC
|
|
||||||
''')
|
|
||||||
rules: list[AlertRule] = []
|
|
||||||
for row in cursor:
|
|
||||||
match = {}
|
|
||||||
notify = {}
|
|
||||||
try:
|
|
||||||
match = json.loads(row['match']) if row['match'] else {}
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
match = {}
|
|
||||||
try:
|
|
||||||
notify = json.loads(row['notify']) if row['notify'] else {}
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
notify = {}
|
|
||||||
rules.append(AlertRule(
|
|
||||||
id=row['id'],
|
|
||||||
name=row['name'],
|
|
||||||
mode=row['mode'],
|
|
||||||
event_type=row['event_type'],
|
|
||||||
match=match,
|
|
||||||
severity=row['severity'] or 'medium',
|
|
||||||
enabled=bool(row['enabled']),
|
|
||||||
notify=notify,
|
|
||||||
created_at=row['created_at'],
|
|
||||||
))
|
|
||||||
with self._cache_lock:
|
|
||||||
self._rules_cache = rules
|
|
||||||
self._rules_loaded_at = time.time()
|
|
||||||
|
|
||||||
def _get_rules(self) -> list[AlertRule]:
|
|
||||||
with self._cache_lock:
|
|
||||||
stale = (time.time() - self._rules_loaded_at) > 10
|
|
||||||
if stale:
|
|
||||||
self._load_rules()
|
|
||||||
with self._cache_lock:
|
|
||||||
return list(self._rules_cache)
|
|
||||||
|
|
||||||
def list_rules(self, include_disabled: bool = False) -> list[dict]:
|
|
||||||
with get_db() as conn:
|
|
||||||
if include_disabled:
|
|
||||||
cursor = conn.execute('''
|
|
||||||
SELECT id, name, mode, event_type, match, severity, enabled, notify, created_at
|
|
||||||
FROM alert_rules
|
|
||||||
ORDER BY id DESC
|
|
||||||
''')
|
|
||||||
else:
|
|
||||||
cursor = conn.execute('''
|
|
||||||
SELECT id, name, mode, event_type, match, severity, enabled, notify, created_at
|
|
||||||
FROM alert_rules
|
|
||||||
WHERE enabled = 1
|
|
||||||
ORDER BY id DESC
|
|
||||||
''')
|
|
||||||
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
'id': row['id'],
|
|
||||||
'name': row['name'],
|
|
||||||
'mode': row['mode'],
|
|
||||||
'event_type': row['event_type'],
|
|
||||||
'match': json.loads(row['match']) if row['match'] else {},
|
|
||||||
'severity': row['severity'],
|
|
||||||
'enabled': bool(row['enabled']),
|
|
||||||
'notify': json.loads(row['notify']) if row['notify'] else {},
|
|
||||||
'created_at': row['created_at'],
|
|
||||||
}
|
|
||||||
for row in cursor
|
|
||||||
]
|
|
||||||
|
|
||||||
def add_rule(self, rule: dict) -> int:
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute('''
|
|
||||||
INSERT INTO alert_rules (name, mode, event_type, match, severity, enabled, notify)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
||||||
''', (
|
|
||||||
rule.get('name') or 'Alert Rule',
|
|
||||||
rule.get('mode'),
|
|
||||||
rule.get('event_type'),
|
|
||||||
json.dumps(rule.get('match') or {}),
|
|
||||||
rule.get('severity') or 'medium',
|
|
||||||
1 if rule.get('enabled', True) else 0,
|
|
||||||
json.dumps(rule.get('notify') or {}),
|
|
||||||
))
|
|
||||||
rule_id = cursor.lastrowid
|
|
||||||
self.invalidate_cache()
|
|
||||||
return int(rule_id)
|
|
||||||
|
|
||||||
def update_rule(self, rule_id: int, updates: dict) -> bool:
|
|
||||||
fields = []
|
|
||||||
params = []
|
|
||||||
for key in ('name', 'mode', 'event_type', 'severity'):
|
|
||||||
if key in updates:
|
|
||||||
fields.append(f"{key} = ?")
|
|
||||||
params.append(updates[key])
|
|
||||||
if 'enabled' in updates:
|
|
||||||
fields.append('enabled = ?')
|
|
||||||
params.append(1 if updates['enabled'] else 0)
|
|
||||||
if 'match' in updates:
|
|
||||||
fields.append('match = ?')
|
|
||||||
params.append(json.dumps(updates['match'] or {}))
|
|
||||||
if 'notify' in updates:
|
|
||||||
fields.append('notify = ?')
|
|
||||||
params.append(json.dumps(updates['notify'] or {}))
|
|
||||||
|
|
||||||
if not fields:
|
|
||||||
return False
|
|
||||||
|
|
||||||
params.append(rule_id)
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute(
|
|
||||||
f"UPDATE alert_rules SET {', '.join(fields)} WHERE id = ?",
|
|
||||||
params
|
|
||||||
)
|
|
||||||
updated = cursor.rowcount > 0
|
|
||||||
|
|
||||||
if updated:
|
|
||||||
self.invalidate_cache()
|
|
||||||
return updated
|
|
||||||
|
|
||||||
def delete_rule(self, rule_id: int) -> bool:
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute('DELETE FROM alert_rules WHERE id = ?', (rule_id,))
|
|
||||||
deleted = cursor.rowcount > 0
|
|
||||||
if deleted:
|
|
||||||
self.invalidate_cache()
|
|
||||||
return deleted
|
|
||||||
|
|
||||||
def list_events(self, limit: int = 100, mode: str | None = None, severity: str | None = None) -> list[dict]:
|
|
||||||
query = 'SELECT id, rule_id, mode, event_type, severity, title, message, payload, created_at FROM alert_events'
|
|
||||||
clauses = []
|
|
||||||
params: list[Any] = []
|
|
||||||
if mode:
|
|
||||||
clauses.append('mode = ?')
|
|
||||||
params.append(mode)
|
|
||||||
if severity:
|
|
||||||
clauses.append('severity = ?')
|
|
||||||
params.append(severity)
|
|
||||||
if clauses:
|
|
||||||
query += ' WHERE ' + ' AND '.join(clauses)
|
|
||||||
query += ' ORDER BY id DESC LIMIT ?'
|
|
||||||
params.append(limit)
|
|
||||||
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute(query, params)
|
|
||||||
events = []
|
|
||||||
for row in cursor:
|
|
||||||
events.append({
|
|
||||||
'id': row['id'],
|
|
||||||
'rule_id': row['rule_id'],
|
|
||||||
'mode': row['mode'],
|
|
||||||
'event_type': row['event_type'],
|
|
||||||
'severity': row['severity'],
|
|
||||||
'title': row['title'],
|
|
||||||
'message': row['message'],
|
|
||||||
'payload': json.loads(row['payload']) if row['payload'] else {},
|
|
||||||
'created_at': row['created_at'],
|
|
||||||
})
|
|
||||||
return events
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
# Event processing
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
|
|
||||||
def process_event(self, mode: str, event: dict, event_type: str | None = None) -> None:
|
|
||||||
if not isinstance(event, dict):
|
|
||||||
return
|
|
||||||
|
|
||||||
if event_type in ('keepalive', 'ping', 'status'):
|
|
||||||
return
|
|
||||||
|
|
||||||
rules = self._get_rules()
|
|
||||||
if not rules:
|
|
||||||
return
|
|
||||||
|
|
||||||
for rule in rules:
|
|
||||||
if rule.mode and rule.mode != mode:
|
|
||||||
continue
|
|
||||||
if rule.event_type and event_type and rule.event_type != event_type:
|
|
||||||
continue
|
|
||||||
if rule.event_type and not event_type:
|
|
||||||
continue
|
|
||||||
if not self._match_rule(rule.match, event):
|
|
||||||
continue
|
|
||||||
|
|
||||||
title = rule.name or 'Alert'
|
|
||||||
message = self._build_message(rule, event, event_type)
|
|
||||||
payload = {
|
|
||||||
'mode': mode,
|
|
||||||
'event_type': event_type,
|
|
||||||
'event': event,
|
|
||||||
'rule': {
|
|
||||||
'id': rule.id,
|
|
||||||
'name': rule.name,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
event_id = self._store_event(rule.id, mode, event_type, rule.severity, title, message, payload)
|
|
||||||
alert_payload = {
|
|
||||||
'id': event_id,
|
|
||||||
'rule_id': rule.id,
|
|
||||||
'mode': mode,
|
|
||||||
'event_type': event_type,
|
|
||||||
'severity': rule.severity,
|
|
||||||
'title': title,
|
|
||||||
'message': message,
|
|
||||||
'payload': payload,
|
|
||||||
'created_at': datetime.now(timezone.utc).isoformat(),
|
|
||||||
}
|
|
||||||
self._queue_event(alert_payload)
|
|
||||||
self._maybe_send_webhook(alert_payload, rule.notify)
|
|
||||||
|
|
||||||
def _build_message(self, rule: AlertRule, event: dict, event_type: str | None) -> str:
|
|
||||||
if isinstance(rule.notify, dict) and rule.notify.get('message'):
|
|
||||||
return str(rule.notify.get('message'))
|
|
||||||
summary_bits = []
|
|
||||||
if event_type:
|
|
||||||
summary_bits.append(event_type)
|
|
||||||
if 'name' in event:
|
|
||||||
summary_bits.append(str(event.get('name')))
|
|
||||||
if 'ssid' in event:
|
|
||||||
summary_bits.append(str(event.get('ssid')))
|
|
||||||
if 'bssid' in event:
|
|
||||||
summary_bits.append(str(event.get('bssid')))
|
|
||||||
if 'address' in event:
|
|
||||||
summary_bits.append(str(event.get('address')))
|
|
||||||
if 'mac' in event:
|
|
||||||
summary_bits.append(str(event.get('mac')))
|
|
||||||
summary = ' | '.join(summary_bits) if summary_bits else 'Alert triggered'
|
|
||||||
return summary
|
|
||||||
|
|
||||||
def _store_event(
|
|
||||||
self,
|
|
||||||
rule_id: int,
|
|
||||||
mode: str,
|
|
||||||
event_type: str | None,
|
|
||||||
severity: str,
|
|
||||||
title: str,
|
|
||||||
message: str,
|
|
||||||
payload: dict,
|
|
||||||
) -> int:
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute('''
|
|
||||||
INSERT INTO alert_events (rule_id, mode, event_type, severity, title, message, payload)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
||||||
''', (
|
|
||||||
rule_id,
|
|
||||||
mode,
|
|
||||||
event_type,
|
|
||||||
severity,
|
|
||||||
title,
|
|
||||||
message,
|
|
||||||
json.dumps(payload),
|
|
||||||
))
|
|
||||||
return int(cursor.lastrowid)
|
|
||||||
|
|
||||||
def _queue_event(self, alert_payload: dict) -> None:
|
|
||||||
try:
|
|
||||||
self._queue.put_nowait(alert_payload)
|
|
||||||
except queue.Full:
|
|
||||||
try:
|
|
||||||
self._queue.get_nowait()
|
|
||||||
self._queue.put_nowait(alert_payload)
|
|
||||||
except queue.Empty:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _maybe_send_webhook(self, payload: dict, notify: dict) -> None:
|
|
||||||
if not ALERT_WEBHOOK_URL:
|
|
||||||
return
|
|
||||||
if isinstance(notify, dict) and notify.get('webhook') is False:
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
import urllib.request
|
|
||||||
req = urllib.request.Request(
|
|
||||||
ALERT_WEBHOOK_URL,
|
|
||||||
data=json.dumps(payload).encode('utf-8'),
|
|
||||||
headers={
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'User-Agent': 'Intercept-Alert',
|
|
||||||
'X-Alert-Token': ALERT_WEBHOOK_SECRET or '',
|
|
||||||
},
|
|
||||||
method='POST'
|
|
||||||
)
|
|
||||||
with urllib.request.urlopen(req, timeout=ALERT_WEBHOOK_TIMEOUT) as _:
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"Alert webhook failed: {e}")
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
# Matching
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _match_rule(self, rule_match: dict, event: dict) -> bool:
|
|
||||||
if not rule_match:
|
|
||||||
return True
|
|
||||||
|
|
||||||
for key, expected in rule_match.items():
|
|
||||||
actual = self._extract_value(event, key)
|
|
||||||
if not self._match_value(actual, expected):
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
def _extract_value(self, event: dict, key: str) -> Any:
|
|
||||||
if '.' not in key:
|
|
||||||
return event.get(key)
|
|
||||||
current: Any = event
|
|
||||||
for part in key.split('.'):
|
|
||||||
if isinstance(current, dict):
|
|
||||||
current = current.get(part)
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
return current
|
|
||||||
|
|
||||||
def _match_value(self, actual: Any, expected: Any) -> bool:
|
|
||||||
if isinstance(expected, dict) and 'op' in expected:
|
|
||||||
op = expected.get('op')
|
|
||||||
value = expected.get('value')
|
|
||||||
return self._apply_op(op, actual, value)
|
|
||||||
|
|
||||||
if isinstance(expected, list):
|
|
||||||
return actual in expected
|
|
||||||
|
|
||||||
if isinstance(expected, str):
|
|
||||||
if actual is None:
|
|
||||||
return False
|
|
||||||
return str(actual).lower() == expected.lower()
|
|
||||||
|
|
||||||
return actual == expected
|
|
||||||
|
|
||||||
def _apply_op(self, op: str, actual: Any, value: Any) -> bool:
|
|
||||||
if op == 'exists':
|
|
||||||
return actual is not None
|
|
||||||
if op == 'eq':
|
|
||||||
return actual == value
|
|
||||||
if op == 'neq':
|
|
||||||
return actual != value
|
|
||||||
if op == 'gt':
|
|
||||||
return _safe_number(actual) is not None and _safe_number(actual) > _safe_number(value)
|
|
||||||
if op == 'gte':
|
|
||||||
return _safe_number(actual) is not None and _safe_number(actual) >= _safe_number(value)
|
|
||||||
if op == 'lt':
|
|
||||||
return _safe_number(actual) is not None and _safe_number(actual) < _safe_number(value)
|
|
||||||
if op == 'lte':
|
|
||||||
return _safe_number(actual) is not None and _safe_number(actual) <= _safe_number(value)
|
|
||||||
if op == 'in':
|
|
||||||
return actual in (value or [])
|
|
||||||
if op == 'contains':
|
|
||||||
if actual is None:
|
|
||||||
return False
|
|
||||||
if isinstance(actual, list):
|
|
||||||
return any(str(value).lower() in str(item).lower() for item in actual)
|
|
||||||
return str(value).lower() in str(actual).lower()
|
|
||||||
if op == 'regex':
|
|
||||||
if actual is None or value is None:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
return re.search(str(value), str(actual)) is not None
|
|
||||||
except re.error:
|
|
||||||
return False
|
|
||||||
return False
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
# Streaming
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
|
|
||||||
def stream_events(self, timeout: float = 1.0) -> Generator[dict, None, None]:
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
event = self._queue.get(timeout=timeout)
|
|
||||||
yield event
|
|
||||||
except queue.Empty:
|
|
||||||
yield {'type': 'keepalive'}
|
|
||||||
|
|
||||||
|
|
||||||
_alert_manager: AlertManager | None = None
|
|
||||||
_alert_lock = threading.Lock()
|
|
||||||
|
|
||||||
|
|
||||||
def get_alert_manager() -> AlertManager:
|
|
||||||
global _alert_manager
|
|
||||||
with _alert_lock:
|
|
||||||
if _alert_manager is None:
|
|
||||||
_alert_manager = AlertManager()
|
|
||||||
return _alert_manager
|
|
||||||
|
|
||||||
|
|
||||||
def _safe_number(value: Any) -> float | None:
|
|
||||||
try:
|
|
||||||
return float(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None
|
|
||||||
@@ -151,7 +151,6 @@ class BTDeviceAggregate:
|
|||||||
# Baseline tracking
|
# Baseline tracking
|
||||||
in_baseline: bool = False
|
in_baseline: bool = False
|
||||||
baseline_id: Optional[int] = None
|
baseline_id: Optional[int] = None
|
||||||
seen_before: bool = False
|
|
||||||
|
|
||||||
# Tracker detection fields
|
# Tracker detection fields
|
||||||
is_tracker: bool = False
|
is_tracker: bool = False
|
||||||
@@ -278,7 +277,6 @@ class BTDeviceAggregate:
|
|||||||
# Baseline
|
# Baseline
|
||||||
'in_baseline': self.in_baseline,
|
'in_baseline': self.in_baseline,
|
||||||
'baseline_id': self.baseline_id,
|
'baseline_id': self.baseline_id,
|
||||||
'seen_before': self.seen_before,
|
|
||||||
|
|
||||||
# Tracker detection
|
# Tracker detection
|
||||||
'tracker': {
|
'tracker': {
|
||||||
@@ -329,7 +327,6 @@ class BTDeviceAggregate:
|
|||||||
'seen_count': self.seen_count,
|
'seen_count': self.seen_count,
|
||||||
'heuristic_flags': self.heuristic_flags,
|
'heuristic_flags': self.heuristic_flags,
|
||||||
'in_baseline': self.in_baseline,
|
'in_baseline': self.in_baseline,
|
||||||
'seen_before': self.seen_before,
|
|
||||||
# Tracker info for list view
|
# Tracker info for list view
|
||||||
'is_tracker': self.is_tracker,
|
'is_tracker': self.is_tracker,
|
||||||
'tracker_type': self.tracker_type,
|
'tracker_type': self.tracker_type,
|
||||||
|
|||||||
+2
-30
@@ -142,7 +142,7 @@ class DataStore:
|
|||||||
|
|
||||||
|
|
||||||
class CleanupManager:
|
class CleanupManager:
|
||||||
"""Manages periodic cleanup of multiple data stores and database tables."""
|
"""Manages periodic cleanup of multiple data stores."""
|
||||||
|
|
||||||
def __init__(self, interval: float = 60.0):
|
def __init__(self, interval: float = 60.0):
|
||||||
"""
|
"""
|
||||||
@@ -152,11 +152,9 @@ class CleanupManager:
|
|||||||
interval: Cleanup interval in seconds
|
interval: Cleanup interval in seconds
|
||||||
"""
|
"""
|
||||||
self.stores: list[DataStore] = []
|
self.stores: list[DataStore] = []
|
||||||
self.db_cleanup_funcs: list[tuple[callable, int]] = [] # (func, interval_multiplier)
|
|
||||||
self.interval = interval
|
self.interval = interval
|
||||||
self._timer: threading.Timer | None = None
|
self._timer: threading.Timer | None = None
|
||||||
self._running = False
|
self._running = False
|
||||||
self._cleanup_count = 0
|
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
def register(self, store: DataStore) -> None:
|
def register(self, store: DataStore) -> None:
|
||||||
@@ -171,17 +169,6 @@ class CleanupManager:
|
|||||||
if store in self.stores:
|
if store in self.stores:
|
||||||
self.stores.remove(store)
|
self.stores.remove(store)
|
||||||
|
|
||||||
def register_db_cleanup(self, func: callable, interval_multiplier: int = 60) -> None:
|
|
||||||
"""
|
|
||||||
Register a database cleanup function.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
func: Cleanup function to call (should return number of deleted rows)
|
|
||||||
interval_multiplier: How many cleanup cycles to wait between calls (default: 60 = 1 hour if interval is 60s)
|
|
||||||
"""
|
|
||||||
with self._lock:
|
|
||||||
self.db_cleanup_funcs.append((func, interval_multiplier))
|
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
"""Start the cleanup timer."""
|
"""Start the cleanup timer."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -207,15 +194,11 @@ class CleanupManager:
|
|||||||
self._timer.start()
|
self._timer.start()
|
||||||
|
|
||||||
def _run_cleanup(self) -> None:
|
def _run_cleanup(self) -> None:
|
||||||
"""Run cleanup on all registered stores and database tables."""
|
"""Run cleanup on all registered stores."""
|
||||||
total_cleaned = 0
|
total_cleaned = 0
|
||||||
|
|
||||||
# Cleanup in-memory data stores
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
stores = list(self.stores)
|
stores = list(self.stores)
|
||||||
db_funcs = list(self.db_cleanup_funcs)
|
|
||||||
self._cleanup_count += 1
|
|
||||||
current_count = self._cleanup_count
|
|
||||||
|
|
||||||
for store in stores:
|
for store in stores:
|
||||||
try:
|
try:
|
||||||
@@ -223,17 +206,6 @@ class CleanupManager:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error cleaning up {store.name}: {e}")
|
logger.error(f"Error cleaning up {store.name}: {e}")
|
||||||
|
|
||||||
# Cleanup database tables (less frequently)
|
|
||||||
for func, interval_multiplier in db_funcs:
|
|
||||||
if current_count % interval_multiplier == 0:
|
|
||||||
try:
|
|
||||||
deleted = func()
|
|
||||||
if deleted > 0:
|
|
||||||
logger.info(f"Database cleanup: {func.__name__} removed {deleted} rows")
|
|
||||||
total_cleaned += deleted
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error in database cleanup {func.__name__}: {e}")
|
|
||||||
|
|
||||||
if total_cleaned > 0:
|
if total_cleaned > 0:
|
||||||
logger.info(f"Cleanup complete: removed {total_cleaned} stale entries")
|
logger.info(f"Cleanup complete: removed {total_cleaned} stale entries")
|
||||||
|
|
||||||
|
|||||||
@@ -274,4 +274,3 @@ MAX_DEAUTH_ALERTS_AGE_SECONDS = 300 # 5 minutes
|
|||||||
|
|
||||||
# Deauth detector sniff timeout (seconds)
|
# Deauth detector sniff timeout (seconds)
|
||||||
DEAUTH_SNIFF_TIMEOUT = 0.5
|
DEAUTH_SNIFF_TIMEOUT = 0.5
|
||||||
|
|
||||||
|
|||||||
+2
-111
@@ -102,98 +102,6 @@ def init_db() -> None:
|
|||||||
)
|
)
|
||||||
''')
|
''')
|
||||||
|
|
||||||
# Alert rules
|
|
||||||
conn.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS alert_rules (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
mode TEXT,
|
|
||||||
event_type TEXT,
|
|
||||||
match TEXT,
|
|
||||||
severity TEXT DEFAULT 'medium',
|
|
||||||
enabled BOOLEAN DEFAULT 1,
|
|
||||||
notify TEXT,
|
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# Alert events
|
|
||||||
conn.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS alert_events (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
rule_id INTEGER,
|
|
||||||
mode TEXT,
|
|
||||||
event_type TEXT,
|
|
||||||
severity TEXT DEFAULT 'medium',
|
|
||||||
title TEXT,
|
|
||||||
message TEXT,
|
|
||||||
payload TEXT,
|
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
FOREIGN KEY (rule_id) REFERENCES alert_rules(id) ON DELETE SET NULL
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# Session recordings
|
|
||||||
conn.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS recording_sessions (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
mode TEXT NOT NULL,
|
|
||||||
label TEXT,
|
|
||||||
started_at TIMESTAMP NOT NULL,
|
|
||||||
stopped_at TIMESTAMP,
|
|
||||||
file_path TEXT NOT NULL,
|
|
||||||
event_count INTEGER DEFAULT 0,
|
|
||||||
size_bytes INTEGER DEFAULT 0,
|
|
||||||
metadata TEXT
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# Alert rules
|
|
||||||
conn.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS alert_rules (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
mode TEXT,
|
|
||||||
event_type TEXT,
|
|
||||||
match TEXT,
|
|
||||||
severity TEXT DEFAULT 'medium',
|
|
||||||
enabled BOOLEAN DEFAULT 1,
|
|
||||||
notify TEXT,
|
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# Alert events
|
|
||||||
conn.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS alert_events (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
rule_id INTEGER,
|
|
||||||
mode TEXT,
|
|
||||||
event_type TEXT,
|
|
||||||
severity TEXT DEFAULT 'medium',
|
|
||||||
title TEXT,
|
|
||||||
message TEXT,
|
|
||||||
payload TEXT,
|
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
FOREIGN KEY (rule_id) REFERENCES alert_rules(id) ON DELETE SET NULL
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# Session recordings
|
|
||||||
conn.execute('''
|
|
||||||
CREATE TABLE IF NOT EXISTS recording_sessions (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
mode TEXT NOT NULL,
|
|
||||||
label TEXT,
|
|
||||||
started_at TIMESTAMP NOT NULL,
|
|
||||||
stopped_at TIMESTAMP,
|
|
||||||
file_path TEXT NOT NULL,
|
|
||||||
event_count INTEGER DEFAULT 0,
|
|
||||||
size_bytes INTEGER DEFAULT 0,
|
|
||||||
metadata TEXT
|
|
||||||
)
|
|
||||||
''')
|
|
||||||
|
|
||||||
# Users table for authentication
|
# Users table for authentication
|
||||||
conn.execute('''
|
conn.execute('''
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
@@ -231,7 +139,6 @@ def init_db() -> None:
|
|||||||
description TEXT,
|
description TEXT,
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
wifi_networks TEXT,
|
wifi_networks TEXT,
|
||||||
wifi_clients TEXT,
|
|
||||||
bt_devices TEXT,
|
bt_devices TEXT,
|
||||||
rf_frequencies TEXT,
|
rf_frequencies TEXT,
|
||||||
gps_coords TEXT,
|
gps_coords TEXT,
|
||||||
@@ -239,14 +146,6 @@ def init_db() -> None:
|
|||||||
)
|
)
|
||||||
''')
|
''')
|
||||||
|
|
||||||
# Ensure new columns exist for older databases
|
|
||||||
try:
|
|
||||||
columns = {row['name'] for row in conn.execute("PRAGMA table_info(tscm_baselines)")}
|
|
||||||
if 'wifi_clients' not in columns:
|
|
||||||
conn.execute('ALTER TABLE tscm_baselines ADD COLUMN wifi_clients TEXT')
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"Schema update skipped for tscm_baselines: {e}")
|
|
||||||
|
|
||||||
# TSCM Sweeps - Individual sweep sessions
|
# TSCM Sweeps - Individual sweep sessions
|
||||||
conn.execute('''
|
conn.execute('''
|
||||||
CREATE TABLE IF NOT EXISTS tscm_sweeps (
|
CREATE TABLE IF NOT EXISTS tscm_sweeps (
|
||||||
@@ -791,7 +690,6 @@ def create_tscm_baseline(
|
|||||||
location: str | None = None,
|
location: str | None = None,
|
||||||
description: str | None = None,
|
description: str | None = None,
|
||||||
wifi_networks: list | None = None,
|
wifi_networks: list | None = None,
|
||||||
wifi_clients: list | None = None,
|
|
||||||
bt_devices: list | None = None,
|
bt_devices: list | None = None,
|
||||||
rf_frequencies: list | None = None,
|
rf_frequencies: list | None = None,
|
||||||
gps_coords: dict | None = None
|
gps_coords: dict | None = None
|
||||||
@@ -805,14 +703,13 @@ def create_tscm_baseline(
|
|||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cursor = conn.execute('''
|
cursor = conn.execute('''
|
||||||
INSERT INTO tscm_baselines
|
INSERT INTO tscm_baselines
|
||||||
(name, location, description, wifi_networks, wifi_clients, bt_devices, rf_frequencies, gps_coords)
|
(name, location, description, wifi_networks, bt_devices, rf_frequencies, gps_coords)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
''', (
|
''', (
|
||||||
name,
|
name,
|
||||||
location,
|
location,
|
||||||
description,
|
description,
|
||||||
json.dumps(wifi_networks) if wifi_networks else None,
|
json.dumps(wifi_networks) if wifi_networks else None,
|
||||||
json.dumps(wifi_clients) if wifi_clients else None,
|
|
||||||
json.dumps(bt_devices) if bt_devices else None,
|
json.dumps(bt_devices) if bt_devices else None,
|
||||||
json.dumps(rf_frequencies) if rf_frequencies else None,
|
json.dumps(rf_frequencies) if rf_frequencies else None,
|
||||||
json.dumps(gps_coords) if gps_coords else None
|
json.dumps(gps_coords) if gps_coords else None
|
||||||
@@ -838,7 +735,6 @@ def get_tscm_baseline(baseline_id: int) -> dict | None:
|
|||||||
'description': row['description'],
|
'description': row['description'],
|
||||||
'created_at': row['created_at'],
|
'created_at': row['created_at'],
|
||||||
'wifi_networks': json.loads(row['wifi_networks']) if row['wifi_networks'] else [],
|
'wifi_networks': json.loads(row['wifi_networks']) if row['wifi_networks'] else [],
|
||||||
'wifi_clients': json.loads(row['wifi_clients']) if row['wifi_clients'] else [],
|
|
||||||
'bt_devices': json.loads(row['bt_devices']) if row['bt_devices'] else [],
|
'bt_devices': json.loads(row['bt_devices']) if row['bt_devices'] else [],
|
||||||
'rf_frequencies': json.loads(row['rf_frequencies']) if row['rf_frequencies'] else [],
|
'rf_frequencies': json.loads(row['rf_frequencies']) if row['rf_frequencies'] else [],
|
||||||
'gps_coords': json.loads(row['gps_coords']) if row['gps_coords'] else None,
|
'gps_coords': json.loads(row['gps_coords']) if row['gps_coords'] else None,
|
||||||
@@ -888,7 +784,6 @@ def set_active_tscm_baseline(baseline_id: int) -> bool:
|
|||||||
def update_tscm_baseline(
|
def update_tscm_baseline(
|
||||||
baseline_id: int,
|
baseline_id: int,
|
||||||
wifi_networks: list | None = None,
|
wifi_networks: list | None = None,
|
||||||
wifi_clients: list | None = None,
|
|
||||||
bt_devices: list | None = None,
|
bt_devices: list | None = None,
|
||||||
rf_frequencies: list | None = None
|
rf_frequencies: list | None = None
|
||||||
) -> bool:
|
) -> bool:
|
||||||
@@ -899,9 +794,6 @@ def update_tscm_baseline(
|
|||||||
if wifi_networks is not None:
|
if wifi_networks is not None:
|
||||||
updates.append('wifi_networks = ?')
|
updates.append('wifi_networks = ?')
|
||||||
params.append(json.dumps(wifi_networks))
|
params.append(json.dumps(wifi_networks))
|
||||||
if wifi_clients is not None:
|
|
||||||
updates.append('wifi_clients = ?')
|
|
||||||
params.append(json.dumps(wifi_clients))
|
|
||||||
if bt_devices is not None:
|
if bt_devices is not None:
|
||||||
updates.append('bt_devices = ?')
|
updates.append('bt_devices = ?')
|
||||||
params.append(json.dumps(bt_devices))
|
params.append(json.dumps(bt_devices))
|
||||||
@@ -2169,4 +2061,3 @@ def cleanup_old_payloads(max_age_hours: int = 24) -> int:
|
|||||||
WHERE received_at < datetime('now', ?)
|
WHERE received_at < datetime('now', ?)
|
||||||
''', (f'-{max_age_hours} hours',))
|
''', (f'-{max_age_hours} hours',))
|
||||||
return cursor.rowcount
|
return cursor.rowcount
|
||||||
|
|
||||||
|
|||||||
@@ -443,7 +443,7 @@ TOOL_DEPENDENCIES = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
"""Shared event pipeline for alerts and recordings."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from utils.alerts import get_alert_manager
|
|
||||||
from utils.recording import get_recording_manager
|
|
||||||
|
|
||||||
IGNORE_TYPES = {'keepalive', 'ping'}
|
|
||||||
|
|
||||||
|
|
||||||
def process_event(mode: str, event: dict | Any, event_type: str | None = None) -> None:
|
|
||||||
if event_type in IGNORE_TYPES:
|
|
||||||
return
|
|
||||||
if not isinstance(event, dict):
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
get_recording_manager().record_event(mode, event, event_type)
|
|
||||||
except Exception:
|
|
||||||
# Recording failures should never break streaming
|
|
||||||
pass
|
|
||||||
|
|
||||||
try:
|
|
||||||
get_alert_manager().process_event(mode, event, event_type)
|
|
||||||
except Exception:
|
|
||||||
# Alert failures should never break streaming
|
|
||||||
pass
|
|
||||||
+4
-6
@@ -85,13 +85,11 @@ atexit.register(cleanup_all_processes)
|
|||||||
|
|
||||||
# Handle signals for graceful shutdown
|
# Handle signals for graceful shutdown
|
||||||
def _signal_handler(signum, frame):
|
def _signal_handler(signum, frame):
|
||||||
"""Handle termination signals.
|
"""Handle termination signals."""
|
||||||
|
|
||||||
Keep this minimal — logging and lock acquisition in signal handlers
|
|
||||||
can deadlock when another thread holds the logging or process lock.
|
|
||||||
Process cleanup is handled by the atexit handler registered above.
|
|
||||||
"""
|
|
||||||
import sys
|
import sys
|
||||||
|
logger.info(f"Received signal {signum}, cleaning up...")
|
||||||
|
cleanup_all_processes()
|
||||||
|
# Re-raise KeyboardInterrupt for SIGINT so Flask can handle shutdown
|
||||||
if signum == signal.SIGINT:
|
if signum == signal.SIGINT:
|
||||||
raise KeyboardInterrupt()
|
raise KeyboardInterrupt()
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|||||||
@@ -1,222 +0,0 @@
|
|||||||
"""Session recording utilities for SSE/event streams."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import threading
|
|
||||||
import uuid
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from utils.database import get_db
|
|
||||||
|
|
||||||
logger = logging.getLogger('intercept.recording')
|
|
||||||
|
|
||||||
RECORDING_ROOT = Path(__file__).parent.parent / 'instance' / 'recordings'
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class RecordingSession:
|
|
||||||
id: str
|
|
||||||
mode: str
|
|
||||||
label: str | None
|
|
||||||
file_path: Path
|
|
||||||
started_at: datetime
|
|
||||||
stopped_at: datetime | None = None
|
|
||||||
event_count: int = 0
|
|
||||||
size_bytes: int = 0
|
|
||||||
metadata: dict | None = None
|
|
||||||
|
|
||||||
_file_handle: Any | None = None
|
|
||||||
_lock: threading.Lock = threading.Lock()
|
|
||||||
|
|
||||||
def open(self) -> None:
|
|
||||||
self.file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
self._file_handle = self.file_path.open('a', encoding='utf-8')
|
|
||||||
|
|
||||||
def close(self) -> None:
|
|
||||||
if self._file_handle:
|
|
||||||
self._file_handle.flush()
|
|
||||||
self._file_handle.close()
|
|
||||||
self._file_handle = None
|
|
||||||
|
|
||||||
def write_event(self, record: dict) -> None:
|
|
||||||
if not self._file_handle:
|
|
||||||
self.open()
|
|
||||||
line = json.dumps(record, ensure_ascii=True) + '\n'
|
|
||||||
with self._lock:
|
|
||||||
self._file_handle.write(line)
|
|
||||||
self._file_handle.flush()
|
|
||||||
self.event_count += 1
|
|
||||||
self.size_bytes += len(line.encode('utf-8'))
|
|
||||||
|
|
||||||
|
|
||||||
class RecordingManager:
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self._active_by_mode: dict[str, RecordingSession] = {}
|
|
||||||
self._active_by_id: dict[str, RecordingSession] = {}
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
|
|
||||||
def start_recording(self, mode: str, label: str | None = None, metadata: dict | None = None) -> RecordingSession:
|
|
||||||
with self._lock:
|
|
||||||
existing = self._active_by_mode.get(mode)
|
|
||||||
if existing:
|
|
||||||
return existing
|
|
||||||
|
|
||||||
session_id = str(uuid.uuid4())
|
|
||||||
started_at = datetime.now(timezone.utc)
|
|
||||||
filename = f"{mode}_{started_at.strftime('%Y%m%d_%H%M%S')}_{session_id}.jsonl"
|
|
||||||
file_path = RECORDING_ROOT / mode / filename
|
|
||||||
|
|
||||||
session = RecordingSession(
|
|
||||||
id=session_id,
|
|
||||||
mode=mode,
|
|
||||||
label=label,
|
|
||||||
file_path=file_path,
|
|
||||||
started_at=started_at,
|
|
||||||
metadata=metadata or {},
|
|
||||||
)
|
|
||||||
session.open()
|
|
||||||
|
|
||||||
self._active_by_mode[mode] = session
|
|
||||||
self._active_by_id[session_id] = session
|
|
||||||
|
|
||||||
with get_db() as conn:
|
|
||||||
conn.execute('''
|
|
||||||
INSERT INTO recording_sessions
|
|
||||||
(id, mode, label, started_at, file_path, event_count, size_bytes, metadata)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
||||||
''', (
|
|
||||||
session.id,
|
|
||||||
session.mode,
|
|
||||||
session.label,
|
|
||||||
session.started_at.isoformat(),
|
|
||||||
str(session.file_path),
|
|
||||||
session.event_count,
|
|
||||||
session.size_bytes,
|
|
||||||
json.dumps(session.metadata or {}),
|
|
||||||
))
|
|
||||||
|
|
||||||
return session
|
|
||||||
|
|
||||||
def stop_recording(self, mode: str | None = None, session_id: str | None = None) -> RecordingSession | None:
|
|
||||||
with self._lock:
|
|
||||||
session = None
|
|
||||||
if session_id:
|
|
||||||
session = self._active_by_id.get(session_id)
|
|
||||||
elif mode:
|
|
||||||
session = self._active_by_mode.get(mode)
|
|
||||||
|
|
||||||
if not session:
|
|
||||||
return None
|
|
||||||
|
|
||||||
session.stopped_at = datetime.now(timezone.utc)
|
|
||||||
session.close()
|
|
||||||
|
|
||||||
self._active_by_mode.pop(session.mode, None)
|
|
||||||
self._active_by_id.pop(session.id, None)
|
|
||||||
|
|
||||||
with get_db() as conn:
|
|
||||||
conn.execute('''
|
|
||||||
UPDATE recording_sessions
|
|
||||||
SET stopped_at = ?, event_count = ?, size_bytes = ?
|
|
||||||
WHERE id = ?
|
|
||||||
''', (
|
|
||||||
session.stopped_at.isoformat(),
|
|
||||||
session.event_count,
|
|
||||||
session.size_bytes,
|
|
||||||
session.id,
|
|
||||||
))
|
|
||||||
|
|
||||||
return session
|
|
||||||
|
|
||||||
def record_event(self, mode: str, event: dict, event_type: str | None = None) -> None:
|
|
||||||
if event_type in ('keepalive', 'ping'):
|
|
||||||
return
|
|
||||||
session = self._active_by_mode.get(mode)
|
|
||||||
if not session:
|
|
||||||
return
|
|
||||||
record = {
|
|
||||||
'timestamp': datetime.now(timezone.utc).isoformat(),
|
|
||||||
'mode': mode,
|
|
||||||
'event_type': event_type,
|
|
||||||
'event': event,
|
|
||||||
}
|
|
||||||
try:
|
|
||||||
session.write_event(record)
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"Recording write failed: {e}")
|
|
||||||
|
|
||||||
def list_recordings(self, limit: int = 50) -> list[dict]:
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute('''
|
|
||||||
SELECT id, mode, label, started_at, stopped_at, file_path, event_count, size_bytes, metadata
|
|
||||||
FROM recording_sessions
|
|
||||||
ORDER BY started_at DESC
|
|
||||||
LIMIT ?
|
|
||||||
''', (limit,))
|
|
||||||
rows = []
|
|
||||||
for row in cursor:
|
|
||||||
rows.append({
|
|
||||||
'id': row['id'],
|
|
||||||
'mode': row['mode'],
|
|
||||||
'label': row['label'],
|
|
||||||
'started_at': row['started_at'],
|
|
||||||
'stopped_at': row['stopped_at'],
|
|
||||||
'file_path': row['file_path'],
|
|
||||||
'event_count': row['event_count'],
|
|
||||||
'size_bytes': row['size_bytes'],
|
|
||||||
'metadata': json.loads(row['metadata']) if row['metadata'] else {},
|
|
||||||
})
|
|
||||||
return rows
|
|
||||||
|
|
||||||
def get_recording(self, session_id: str) -> dict | None:
|
|
||||||
with get_db() as conn:
|
|
||||||
cursor = conn.execute('''
|
|
||||||
SELECT id, mode, label, started_at, stopped_at, file_path, event_count, size_bytes, metadata
|
|
||||||
FROM recording_sessions
|
|
||||||
WHERE id = ?
|
|
||||||
''', (session_id,))
|
|
||||||
row = cursor.fetchone()
|
|
||||||
if not row:
|
|
||||||
return None
|
|
||||||
return {
|
|
||||||
'id': row['id'],
|
|
||||||
'mode': row['mode'],
|
|
||||||
'label': row['label'],
|
|
||||||
'started_at': row['started_at'],
|
|
||||||
'stopped_at': row['stopped_at'],
|
|
||||||
'file_path': row['file_path'],
|
|
||||||
'event_count': row['event_count'],
|
|
||||||
'size_bytes': row['size_bytes'],
|
|
||||||
'metadata': json.loads(row['metadata']) if row['metadata'] else {},
|
|
||||||
}
|
|
||||||
|
|
||||||
def get_active(self) -> list[dict]:
|
|
||||||
with self._lock:
|
|
||||||
sessions = []
|
|
||||||
for session in self._active_by_mode.values():
|
|
||||||
sessions.append({
|
|
||||||
'id': session.id,
|
|
||||||
'mode': session.mode,
|
|
||||||
'label': session.label,
|
|
||||||
'started_at': session.started_at.isoformat(),
|
|
||||||
'event_count': session.event_count,
|
|
||||||
'size_bytes': session.size_bytes,
|
|
||||||
})
|
|
||||||
return sessions
|
|
||||||
|
|
||||||
|
|
||||||
_recording_manager: RecordingManager | None = None
|
|
||||||
_recording_lock = threading.Lock()
|
|
||||||
|
|
||||||
|
|
||||||
def get_recording_manager() -> RecordingManager:
|
|
||||||
global _recording_manager
|
|
||||||
with _recording_lock:
|
|
||||||
if _recording_manager is None:
|
|
||||||
_recording_manager = RecordingManager()
|
|
||||||
return _recording_manager
|
|
||||||
@@ -26,7 +26,7 @@ from __future__ import annotations
|
|||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from .base import CommandBuilder, SDRCapabilities, SDRDevice, SDRType
|
from .base import CommandBuilder, SDRCapabilities, SDRDevice, SDRType
|
||||||
from .detection import detect_all_devices, probe_rtlsdr_device
|
from .detection import detect_all_devices
|
||||||
from .rtlsdr import RTLSDRCommandBuilder
|
from .rtlsdr import RTLSDRCommandBuilder
|
||||||
from .limesdr import LimeSDRCommandBuilder
|
from .limesdr import LimeSDRCommandBuilder
|
||||||
from .hackrf import HackRFCommandBuilder
|
from .hackrf import HackRFCommandBuilder
|
||||||
@@ -229,6 +229,4 @@ __all__ = [
|
|||||||
'validate_device_index',
|
'validate_device_index',
|
||||||
'validate_squelch',
|
'validate_squelch',
|
||||||
'get_capabilities_for_type',
|
'get_capabilities_for_type',
|
||||||
# Device probing
|
|
||||||
'probe_rtlsdr_device',
|
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -185,43 +185,6 @@ class AirspyCommandBuilder(CommandBuilder):
|
|||||||
|
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
def build_iq_capture_command(
|
|
||||||
self,
|
|
||||||
device: SDRDevice,
|
|
||||||
frequency_mhz: float,
|
|
||||||
sample_rate: int = 2048000,
|
|
||||||
gain: Optional[float] = None,
|
|
||||||
ppm: Optional[int] = None,
|
|
||||||
bias_t: bool = False,
|
|
||||||
output_format: str = 'cu8',
|
|
||||||
) -> list[str]:
|
|
||||||
"""
|
|
||||||
Build rx_sdr command for raw I/Q capture with Airspy.
|
|
||||||
|
|
||||||
Outputs unsigned 8-bit I/Q pairs to stdout for waterfall display.
|
|
||||||
"""
|
|
||||||
device_str = self._build_device_string(device)
|
|
||||||
freq_hz = int(frequency_mhz * 1e6)
|
|
||||||
|
|
||||||
cmd = [
|
|
||||||
'rx_sdr',
|
|
||||||
'-d', device_str,
|
|
||||||
'-f', str(freq_hz),
|
|
||||||
'-s', str(sample_rate),
|
|
||||||
'-F', 'CU8',
|
|
||||||
]
|
|
||||||
|
|
||||||
if gain is not None and gain > 0:
|
|
||||||
cmd.extend(['-g', self._format_gain(gain)])
|
|
||||||
|
|
||||||
if bias_t:
|
|
||||||
cmd.append('-T')
|
|
||||||
|
|
||||||
# Output to stdout
|
|
||||||
cmd.append('-')
|
|
||||||
|
|
||||||
return cmd
|
|
||||||
|
|
||||||
def get_capabilities(self) -> SDRCapabilities:
|
def get_capabilities(self) -> SDRCapabilities:
|
||||||
"""Return Airspy capabilities."""
|
"""Return Airspy capabilities."""
|
||||||
return self.CAPABILITIES
|
return self.CAPABILITIES
|
||||||
|
|||||||
@@ -186,41 +186,6 @@ class CommandBuilder(ABC):
|
|||||||
"""Return hardware capabilities for this SDR type."""
|
"""Return hardware capabilities for this SDR type."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def build_iq_capture_command(
|
|
||||||
self,
|
|
||||||
device: SDRDevice,
|
|
||||||
frequency_mhz: float,
|
|
||||||
sample_rate: int = 2048000,
|
|
||||||
gain: Optional[float] = None,
|
|
||||||
ppm: Optional[int] = None,
|
|
||||||
bias_t: bool = False,
|
|
||||||
output_format: str = 'cu8',
|
|
||||||
) -> list[str]:
|
|
||||||
"""
|
|
||||||
Build raw I/Q capture command for streaming samples to stdout.
|
|
||||||
|
|
||||||
Used for real-time waterfall/spectrum display. Output is unsigned
|
|
||||||
8-bit I/Q pairs (cu8) written continuously to stdout.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
device: The SDR device to use
|
|
||||||
frequency_mhz: Center frequency in MHz
|
|
||||||
sample_rate: Sample rate in Hz (default 2048000)
|
|
||||||
gain: Gain in dB (None for auto)
|
|
||||||
ppm: PPM frequency correction
|
|
||||||
bias_t: Enable bias-T power (for active antennas)
|
|
||||||
output_format: Output sample format (default 'cu8')
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Command as list of strings for subprocess
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
NotImplementedError: If the SDR type does not support I/Q capture.
|
|
||||||
"""
|
|
||||||
raise NotImplementedError(
|
|
||||||
f"{self.__class__.__name__} does not support raw I/Q capture"
|
|
||||||
)
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def get_sdr_type(cls) -> SDRType:
|
def get_sdr_type(cls) -> SDRType:
|
||||||
|
|||||||
@@ -348,68 +348,6 @@ def detect_hackrf_devices() -> list[SDRDevice]:
|
|||||||
return devices
|
return devices
|
||||||
|
|
||||||
|
|
||||||
def probe_rtlsdr_device(device_index: int) -> str | None:
|
|
||||||
"""Probe whether an RTL-SDR device is available at the USB level.
|
|
||||||
|
|
||||||
Runs a quick ``rtl_test`` invocation targeting a single device to
|
|
||||||
check for USB claim errors that indicate the device is held by an
|
|
||||||
external process (or a stale handle from a previous crash).
|
|
||||||
|
|
||||||
Args:
|
|
||||||
device_index: The RTL-SDR device index to probe.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
An error message string if the device cannot be opened,
|
|
||||||
or ``None`` if the device is available.
|
|
||||||
"""
|
|
||||||
if not _check_tool('rtl_test'):
|
|
||||||
# Can't probe without rtl_test — let the caller proceed and
|
|
||||||
# surface errors from the actual decoder process instead.
|
|
||||||
return None
|
|
||||||
|
|
||||||
try:
|
|
||||||
import os
|
|
||||||
import platform
|
|
||||||
env = os.environ.copy()
|
|
||||||
|
|
||||||
if platform.system() == 'Darwin':
|
|
||||||
lib_paths = ['/usr/local/lib', '/opt/homebrew/lib']
|
|
||||||
current_ld = env.get('DYLD_LIBRARY_PATH', '')
|
|
||||||
env['DYLD_LIBRARY_PATH'] = ':'.join(
|
|
||||||
lib_paths + [current_ld] if current_ld else lib_paths
|
|
||||||
)
|
|
||||||
|
|
||||||
result = subprocess.run(
|
|
||||||
['rtl_test', '-d', str(device_index), '-t'],
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
timeout=3,
|
|
||||||
env=env,
|
|
||||||
)
|
|
||||||
output = result.stderr + result.stdout
|
|
||||||
|
|
||||||
if 'usb_claim_interface' in output or 'Failed to open' in output:
|
|
||||||
logger.warning(
|
|
||||||
f"RTL-SDR device {device_index} USB probe failed: "
|
|
||||||
f"device busy or unavailable"
|
|
||||||
)
|
|
||||||
return (
|
|
||||||
f'SDR device {device_index} is busy at the USB level — '
|
|
||||||
f'another process outside INTERCEPT may be using it. '
|
|
||||||
f'Check for stale rtl_fm/rtl_433/dump1090 processes, '
|
|
||||||
f'or try a different device.'
|
|
||||||
)
|
|
||||||
|
|
||||||
except subprocess.TimeoutExpired:
|
|
||||||
# rtl_test opened the device successfully and is running the
|
|
||||||
# test — that means the device *is* available.
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"RTL-SDR probe error for device {device_index}: {e}")
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def detect_all_devices() -> list[SDRDevice]:
|
def detect_all_devices() -> list[SDRDevice]:
|
||||||
"""
|
"""
|
||||||
Detect all connected SDR devices across all supported hardware types.
|
Detect all connected SDR devices across all supported hardware types.
|
||||||
|
|||||||
@@ -185,44 +185,6 @@ class HackRFCommandBuilder(CommandBuilder):
|
|||||||
|
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
def build_iq_capture_command(
|
|
||||||
self,
|
|
||||||
device: SDRDevice,
|
|
||||||
frequency_mhz: float,
|
|
||||||
sample_rate: int = 2048000,
|
|
||||||
gain: Optional[float] = None,
|
|
||||||
ppm: Optional[int] = None,
|
|
||||||
bias_t: bool = False,
|
|
||||||
output_format: str = 'cu8',
|
|
||||||
) -> list[str]:
|
|
||||||
"""
|
|
||||||
Build rx_sdr command for raw I/Q capture with HackRF.
|
|
||||||
|
|
||||||
Outputs unsigned 8-bit I/Q pairs to stdout for waterfall display.
|
|
||||||
"""
|
|
||||||
device_str = self._build_device_string(device)
|
|
||||||
freq_hz = int(frequency_mhz * 1e6)
|
|
||||||
|
|
||||||
cmd = [
|
|
||||||
'rx_sdr',
|
|
||||||
'-d', device_str,
|
|
||||||
'-f', str(freq_hz),
|
|
||||||
'-s', str(sample_rate),
|
|
||||||
'-F', 'CU8',
|
|
||||||
]
|
|
||||||
|
|
||||||
if gain is not None and gain > 0:
|
|
||||||
lna, vga = self._split_gain(gain)
|
|
||||||
cmd.extend(['-g', f'LNA={lna},VGA={vga}'])
|
|
||||||
|
|
||||||
if bias_t:
|
|
||||||
cmd.append('-T')
|
|
||||||
|
|
||||||
# Output to stdout
|
|
||||||
cmd.append('-')
|
|
||||||
|
|
||||||
return cmd
|
|
||||||
|
|
||||||
def get_capabilities(self) -> SDRCapabilities:
|
def get_capabilities(self) -> SDRCapabilities:
|
||||||
"""Return HackRF capabilities."""
|
"""Return HackRF capabilities."""
|
||||||
return self.CAPABILITIES
|
return self.CAPABILITIES
|
||||||
|
|||||||
@@ -162,41 +162,6 @@ class LimeSDRCommandBuilder(CommandBuilder):
|
|||||||
|
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
def build_iq_capture_command(
|
|
||||||
self,
|
|
||||||
device: SDRDevice,
|
|
||||||
frequency_mhz: float,
|
|
||||||
sample_rate: int = 2048000,
|
|
||||||
gain: Optional[float] = None,
|
|
||||||
ppm: Optional[int] = None,
|
|
||||||
bias_t: bool = False,
|
|
||||||
output_format: str = 'cu8',
|
|
||||||
) -> list[str]:
|
|
||||||
"""
|
|
||||||
Build rx_sdr command for raw I/Q capture with LimeSDR.
|
|
||||||
|
|
||||||
Outputs unsigned 8-bit I/Q pairs to stdout for waterfall display.
|
|
||||||
Note: LimeSDR does not support bias-T, parameter is ignored.
|
|
||||||
"""
|
|
||||||
device_str = self._build_device_string(device)
|
|
||||||
freq_hz = int(frequency_mhz * 1e6)
|
|
||||||
|
|
||||||
cmd = [
|
|
||||||
'rx_sdr',
|
|
||||||
'-d', device_str,
|
|
||||||
'-f', str(freq_hz),
|
|
||||||
'-s', str(sample_rate),
|
|
||||||
'-F', 'CU8',
|
|
||||||
]
|
|
||||||
|
|
||||||
if gain is not None and gain > 0:
|
|
||||||
cmd.extend(['-g', f'LNAH={int(gain)}'])
|
|
||||||
|
|
||||||
# Output to stdout
|
|
||||||
cmd.append('-')
|
|
||||||
|
|
||||||
return cmd
|
|
||||||
|
|
||||||
def get_capabilities(self) -> SDRCapabilities:
|
def get_capabilities(self) -> SDRCapabilities:
|
||||||
"""Return LimeSDR capabilities."""
|
"""Return LimeSDR capabilities."""
|
||||||
return self.CAPABILITIES
|
return self.CAPABILITIES
|
||||||
|
|||||||
@@ -231,45 +231,6 @@ class RTLSDRCommandBuilder(CommandBuilder):
|
|||||||
|
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
def build_iq_capture_command(
|
|
||||||
self,
|
|
||||||
device: SDRDevice,
|
|
||||||
frequency_mhz: float,
|
|
||||||
sample_rate: int = 2048000,
|
|
||||||
gain: Optional[float] = None,
|
|
||||||
ppm: Optional[int] = None,
|
|
||||||
bias_t: bool = False,
|
|
||||||
output_format: str = 'cu8',
|
|
||||||
) -> list[str]:
|
|
||||||
"""
|
|
||||||
Build rtl_sdr command for raw I/Q capture.
|
|
||||||
|
|
||||||
Outputs unsigned 8-bit I/Q pairs to stdout for waterfall display.
|
|
||||||
"""
|
|
||||||
rtl_sdr_path = get_tool_path('rtl_sdr') or 'rtl_sdr'
|
|
||||||
freq_hz = int(frequency_mhz * 1e6)
|
|
||||||
|
|
||||||
cmd = [
|
|
||||||
rtl_sdr_path,
|
|
||||||
'-d', self._get_device_arg(device),
|
|
||||||
'-f', str(freq_hz),
|
|
||||||
'-s', str(sample_rate),
|
|
||||||
]
|
|
||||||
|
|
||||||
if gain is not None and gain > 0:
|
|
||||||
cmd.extend(['-g', str(gain)])
|
|
||||||
|
|
||||||
if ppm is not None and ppm != 0:
|
|
||||||
cmd.extend(['-p', str(ppm)])
|
|
||||||
|
|
||||||
if bias_t:
|
|
||||||
cmd.append('-T')
|
|
||||||
|
|
||||||
# Output to stdout
|
|
||||||
cmd.append('-')
|
|
||||||
|
|
||||||
return cmd
|
|
||||||
|
|
||||||
def get_capabilities(self) -> SDRCapabilities:
|
def get_capabilities(self) -> SDRCapabilities:
|
||||||
"""Return RTL-SDR capabilities."""
|
"""Return RTL-SDR capabilities."""
|
||||||
return self.CAPABILITIES
|
return self.CAPABILITIES
|
||||||
|
|||||||
@@ -163,43 +163,6 @@ class SDRPlayCommandBuilder(CommandBuilder):
|
|||||||
|
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
def build_iq_capture_command(
|
|
||||||
self,
|
|
||||||
device: SDRDevice,
|
|
||||||
frequency_mhz: float,
|
|
||||||
sample_rate: int = 2048000,
|
|
||||||
gain: Optional[float] = None,
|
|
||||||
ppm: Optional[int] = None,
|
|
||||||
bias_t: bool = False,
|
|
||||||
output_format: str = 'cu8',
|
|
||||||
) -> list[str]:
|
|
||||||
"""
|
|
||||||
Build rx_sdr command for raw I/Q capture with SDRPlay.
|
|
||||||
|
|
||||||
Outputs unsigned 8-bit I/Q pairs to stdout for waterfall display.
|
|
||||||
"""
|
|
||||||
device_str = self._build_device_string(device)
|
|
||||||
freq_hz = int(frequency_mhz * 1e6)
|
|
||||||
|
|
||||||
cmd = [
|
|
||||||
'rx_sdr',
|
|
||||||
'-d', device_str,
|
|
||||||
'-f', str(freq_hz),
|
|
||||||
'-s', str(sample_rate),
|
|
||||||
'-F', 'CU8',
|
|
||||||
]
|
|
||||||
|
|
||||||
if gain is not None and gain > 0:
|
|
||||||
cmd.extend(['-g', f'IFGR={int(gain)}'])
|
|
||||||
|
|
||||||
if bias_t:
|
|
||||||
cmd.append('-T')
|
|
||||||
|
|
||||||
# Output to stdout
|
|
||||||
cmd.append('-')
|
|
||||||
|
|
||||||
return cmd
|
|
||||||
|
|
||||||
def get_capabilities(self) -> SDRCapabilities:
|
def get_capabilities(self) -> SDRCapabilities:
|
||||||
"""Return SDRPlay capabilities."""
|
"""Return SDRPlay capabilities."""
|
||||||
return self.CAPABILITIES
|
return self.CAPABILITIES
|
||||||
|
|||||||
@@ -225,7 +225,7 @@ class SSTVDecoder:
|
|||||||
self._rtl_process = None
|
self._rtl_process = None
|
||||||
self._running = False
|
self._running = False
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
self._callback: Callable[[dict], None] | None = None
|
self._callback: Callable[[DecodeProgress], None] | None = None
|
||||||
self._output_dir = Path(output_dir) if output_dir else Path('instance/sstv_images')
|
self._output_dir = Path(output_dir) if output_dir else Path('instance/sstv_images')
|
||||||
self._url_prefix = url_prefix
|
self._url_prefix = url_prefix
|
||||||
self._images: list[SSTVImage] = []
|
self._images: list[SSTVImage] = []
|
||||||
@@ -253,7 +253,7 @@ class SSTVDecoder:
|
|||||||
"""Return name of available decoder. Always available with pure Python."""
|
"""Return name of available decoder. Always available with pure Python."""
|
||||||
return 'python-sstv'
|
return 'python-sstv'
|
||||||
|
|
||||||
def set_callback(self, callback: Callable[[dict], None]) -> None:
|
def set_callback(self, callback: Callable[[DecodeProgress], None]) -> None:
|
||||||
"""Set callback for decode progress updates."""
|
"""Set callback for decode progress updates."""
|
||||||
self._callback = callback
|
self._callback = callback
|
||||||
|
|
||||||
@@ -420,10 +420,6 @@ class SSTVDecoder:
|
|||||||
|
|
||||||
chunk_counter += 1
|
chunk_counter += 1
|
||||||
|
|
||||||
# Scope: compute RMS/peak from raw int16 samples every chunk
|
|
||||||
rms_val = int(np.sqrt(np.mean(raw_samples.astype(np.float64) ** 2)))
|
|
||||||
peak_val = int(np.max(np.abs(raw_samples)))
|
|
||||||
|
|
||||||
if image_decoder is not None:
|
if image_decoder is not None:
|
||||||
# Currently decoding an image
|
# Currently decoding an image
|
||||||
complete = image_decoder.feed(samples)
|
complete = image_decoder.feed(samples)
|
||||||
@@ -451,7 +447,6 @@ class SSTVDecoder:
|
|||||||
message=f'Decoding {current_mode_name}: {pct}%',
|
message=f'Decoding {current_mode_name}: {pct}%',
|
||||||
partial_image=partial_url,
|
partial_image=partial_url,
|
||||||
))
|
))
|
||||||
self._emit_scope(rms_val, peak_val, 'decoding')
|
|
||||||
|
|
||||||
if complete:
|
if complete:
|
||||||
# Save image
|
# Save image
|
||||||
@@ -484,7 +479,6 @@ class SSTVDecoder:
|
|||||||
vis_detector.reset()
|
vis_detector.reset()
|
||||||
|
|
||||||
# Emit signal level metrics every ~500ms (every 5th 100ms chunk)
|
# Emit signal level metrics every ~500ms (every 5th 100ms chunk)
|
||||||
scope_tone: str | None = None
|
|
||||||
if chunk_counter % 5 == 0 and image_decoder is None:
|
if chunk_counter % 5 == 0 and image_decoder is None:
|
||||||
rms = float(np.sqrt(np.mean(samples ** 2)))
|
rms = float(np.sqrt(np.mean(samples ** 2)))
|
||||||
signal_level = min(100, int(rms * 500))
|
signal_level = min(100, int(rms * 500))
|
||||||
@@ -507,8 +501,6 @@ class SSTVDecoder:
|
|||||||
else:
|
else:
|
||||||
sstv_tone = None
|
sstv_tone = None
|
||||||
|
|
||||||
scope_tone = sstv_tone
|
|
||||||
|
|
||||||
self._emit_progress(DecodeProgress(
|
self._emit_progress(DecodeProgress(
|
||||||
status='detecting',
|
status='detecting',
|
||||||
message='Listening...',
|
message='Listening...',
|
||||||
@@ -517,8 +509,6 @@ class SSTVDecoder:
|
|||||||
vis_state=vis_detector.state.value,
|
vis_state=vis_detector.state.value,
|
||||||
))
|
))
|
||||||
|
|
||||||
self._emit_scope(rms_val, peak_val, scope_tone)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error in decode thread: {e}")
|
logger.error(f"Error in decode thread: {e}")
|
||||||
if not self._running:
|
if not self._running:
|
||||||
@@ -746,18 +736,10 @@ class SSTVDecoder:
|
|||||||
"""Emit progress update to callback."""
|
"""Emit progress update to callback."""
|
||||||
if self._callback:
|
if self._callback:
|
||||||
try:
|
try:
|
||||||
self._callback(progress.to_dict())
|
self._callback(progress)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error in progress callback: {e}")
|
logger.error(f"Error in progress callback: {e}")
|
||||||
|
|
||||||
def _emit_scope(self, rms: int, peak: int, tone: str | None = None) -> None:
|
|
||||||
"""Emit scope signal levels to callback."""
|
|
||||||
if self._callback:
|
|
||||||
try:
|
|
||||||
self._callback({'type': 'sstv_scope', 'rms': rms, 'peak': peak, 'tone': tone})
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def decode_file(self, audio_path: str | Path) -> list[SSTVImage]:
|
def decode_file(self, audio_path: str | Path) -> list[SSTVImage]:
|
||||||
"""Decode SSTV image(s) from an audio file.
|
"""Decode SSTV image(s) from an audio file.
|
||||||
|
|
||||||
|
|||||||
@@ -526,7 +526,6 @@ class BaselineDiff:
|
|||||||
def calculate_baseline_diff(
|
def calculate_baseline_diff(
|
||||||
baseline: dict,
|
baseline: dict,
|
||||||
current_wifi: list[dict],
|
current_wifi: list[dict],
|
||||||
current_wifi_clients: list[dict],
|
|
||||||
current_bt: list[dict],
|
current_bt: list[dict],
|
||||||
current_rf: list[dict],
|
current_rf: list[dict],
|
||||||
sweep_id: int
|
sweep_id: int
|
||||||
@@ -537,7 +536,6 @@ def calculate_baseline_diff(
|
|||||||
Args:
|
Args:
|
||||||
baseline: Baseline dict from database
|
baseline: Baseline dict from database
|
||||||
current_wifi: Current WiFi devices
|
current_wifi: Current WiFi devices
|
||||||
current_wifi_clients: Current WiFi clients
|
|
||||||
current_bt: Current Bluetooth devices
|
current_bt: Current Bluetooth devices
|
||||||
current_rf: Current RF signals
|
current_rf: Current RF signals
|
||||||
sweep_id: Current sweep ID
|
sweep_id: Current sweep ID
|
||||||
@@ -571,11 +569,6 @@ def calculate_baseline_diff(
|
|||||||
for d in baseline.get('wifi_networks', [])
|
for d in baseline.get('wifi_networks', [])
|
||||||
if d.get('bssid') or d.get('mac')
|
if d.get('bssid') or d.get('mac')
|
||||||
}
|
}
|
||||||
baseline_wifi_clients = {
|
|
||||||
d.get('mac', d.get('address', '')).upper(): d
|
|
||||||
for d in baseline.get('wifi_clients', [])
|
|
||||||
if d.get('mac') or d.get('address')
|
|
||||||
}
|
|
||||||
baseline_bt = {
|
baseline_bt = {
|
||||||
d.get('mac', d.get('address', '')).upper(): d
|
d.get('mac', d.get('address', '')).upper(): d
|
||||||
for d in baseline.get('bt_devices', [])
|
for d in baseline.get('bt_devices', [])
|
||||||
@@ -590,9 +583,6 @@ def calculate_baseline_diff(
|
|||||||
# Compare WiFi
|
# Compare WiFi
|
||||||
_compare_wifi(diff, baseline_wifi, current_wifi)
|
_compare_wifi(diff, baseline_wifi, current_wifi)
|
||||||
|
|
||||||
# Compare WiFi clients
|
|
||||||
_compare_wifi_clients(diff, baseline_wifi_clients, current_wifi_clients)
|
|
||||||
|
|
||||||
# Compare Bluetooth
|
# Compare Bluetooth
|
||||||
_compare_bluetooth(diff, baseline_bt, current_bt)
|
_compare_bluetooth(diff, baseline_bt, current_bt)
|
||||||
|
|
||||||
@@ -641,47 +631,6 @@ def _compare_wifi(diff: BaselineDiff, baseline: dict, current: list[dict]) -> No
|
|||||||
'rssi': device.get('power', device.get('signal')),
|
'rssi': device.get('power', device.get('signal')),
|
||||||
}
|
}
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|
||||||
def _compare_wifi_clients(diff: BaselineDiff, baseline: dict, current: list[dict]) -> None:
|
|
||||||
"""Compare WiFi clients between baseline and current."""
|
|
||||||
current_macs = {
|
|
||||||
d.get('mac', d.get('address', '')).upper(): d
|
|
||||||
for d in current
|
|
||||||
if d.get('mac') or d.get('address')
|
|
||||||
}
|
|
||||||
|
|
||||||
# Find new clients
|
|
||||||
for mac, device in current_macs.items():
|
|
||||||
if mac not in baseline:
|
|
||||||
name = device.get('vendor', 'WiFi Client')
|
|
||||||
diff.new_devices.append(DeviceChange(
|
|
||||||
identifier=mac,
|
|
||||||
protocol='wifi_client',
|
|
||||||
change_type='new',
|
|
||||||
description=f'New WiFi client: {name}',
|
|
||||||
expected=False,
|
|
||||||
details={
|
|
||||||
'vendor': name,
|
|
||||||
'rssi': device.get('rssi'),
|
|
||||||
'associated_bssid': device.get('associated_bssid'),
|
|
||||||
}
|
|
||||||
))
|
|
||||||
|
|
||||||
# Find missing clients
|
|
||||||
for mac, device in baseline.items():
|
|
||||||
if mac not in current_macs:
|
|
||||||
name = device.get('vendor', 'WiFi Client')
|
|
||||||
diff.missing_devices.append(DeviceChange(
|
|
||||||
identifier=mac,
|
|
||||||
protocol='wifi_client',
|
|
||||||
change_type='missing',
|
|
||||||
description=f'Missing WiFi client: {name}',
|
|
||||||
expected=True,
|
|
||||||
details={
|
|
||||||
'vendor': name,
|
|
||||||
}
|
|
||||||
))
|
|
||||||
else:
|
else:
|
||||||
# Check for changes
|
# Check for changes
|
||||||
baseline_dev = baseline[mac]
|
baseline_dev = baseline[mac]
|
||||||
@@ -849,7 +798,6 @@ def _calculate_baseline_health(diff: BaselineDiff, baseline: dict) -> None:
|
|||||||
# Device churn penalty
|
# Device churn penalty
|
||||||
total_baseline = (
|
total_baseline = (
|
||||||
len(baseline.get('wifi_networks', [])) +
|
len(baseline.get('wifi_networks', [])) +
|
||||||
len(baseline.get('wifi_clients', [])) +
|
|
||||||
len(baseline.get('bt_devices', [])) +
|
len(baseline.get('bt_devices', [])) +
|
||||||
len(baseline.get('rf_frequencies', []))
|
len(baseline.get('rf_frequencies', []))
|
||||||
)
|
)
|
||||||
|
|||||||
+1
-78
@@ -30,7 +30,6 @@ class BaselineRecorder:
|
|||||||
self.recording = False
|
self.recording = False
|
||||||
self.current_baseline_id: int | None = None
|
self.current_baseline_id: int | None = None
|
||||||
self.wifi_networks: dict[str, dict] = {} # BSSID -> network info
|
self.wifi_networks: dict[str, dict] = {} # BSSID -> network info
|
||||||
self.wifi_clients: dict[str, dict] = {} # MAC -> client info
|
|
||||||
self.bt_devices: dict[str, dict] = {} # MAC -> device info
|
self.bt_devices: dict[str, dict] = {} # MAC -> device info
|
||||||
self.rf_frequencies: dict[float, dict] = {} # Frequency -> signal info
|
self.rf_frequencies: dict[float, dict] = {} # Frequency -> signal info
|
||||||
|
|
||||||
@@ -53,7 +52,6 @@ class BaselineRecorder:
|
|||||||
"""
|
"""
|
||||||
self.recording = True
|
self.recording = True
|
||||||
self.wifi_networks = {}
|
self.wifi_networks = {}
|
||||||
self.wifi_clients = {}
|
|
||||||
self.bt_devices = {}
|
self.bt_devices = {}
|
||||||
self.rf_frequencies = {}
|
self.rf_frequencies = {}
|
||||||
|
|
||||||
@@ -81,7 +79,6 @@ class BaselineRecorder:
|
|||||||
|
|
||||||
# Convert to lists for storage
|
# Convert to lists for storage
|
||||||
wifi_list = list(self.wifi_networks.values())
|
wifi_list = list(self.wifi_networks.values())
|
||||||
wifi_client_list = list(self.wifi_clients.values())
|
|
||||||
bt_list = list(self.bt_devices.values())
|
bt_list = list(self.bt_devices.values())
|
||||||
rf_list = list(self.rf_frequencies.values())
|
rf_list = list(self.rf_frequencies.values())
|
||||||
|
|
||||||
@@ -89,7 +86,6 @@ class BaselineRecorder:
|
|||||||
update_tscm_baseline(
|
update_tscm_baseline(
|
||||||
self.current_baseline_id,
|
self.current_baseline_id,
|
||||||
wifi_networks=wifi_list,
|
wifi_networks=wifi_list,
|
||||||
wifi_clients=wifi_client_list,
|
|
||||||
bt_devices=bt_list,
|
bt_devices=bt_list,
|
||||||
rf_frequencies=rf_list
|
rf_frequencies=rf_list
|
||||||
)
|
)
|
||||||
@@ -97,7 +93,6 @@ class BaselineRecorder:
|
|||||||
summary = {
|
summary = {
|
||||||
'baseline_id': self.current_baseline_id,
|
'baseline_id': self.current_baseline_id,
|
||||||
'wifi_count': len(wifi_list),
|
'wifi_count': len(wifi_list),
|
||||||
'wifi_client_count': len(wifi_client_list),
|
|
||||||
'bt_count': len(bt_list),
|
'bt_count': len(bt_list),
|
||||||
'rf_count': len(rf_list),
|
'rf_count': len(rf_list),
|
||||||
}
|
}
|
||||||
@@ -165,33 +160,6 @@ class BaselineRecorder:
|
|||||||
'last_seen': datetime.now().isoformat(),
|
'last_seen': datetime.now().isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
def add_wifi_client(self, client: dict) -> None:
|
|
||||||
"""Add a WiFi client to the current baseline."""
|
|
||||||
if not self.recording:
|
|
||||||
return
|
|
||||||
|
|
||||||
mac = client.get('mac', client.get('address', '')).upper()
|
|
||||||
if not mac:
|
|
||||||
return
|
|
||||||
|
|
||||||
if mac in self.wifi_clients:
|
|
||||||
self.wifi_clients[mac].update({
|
|
||||||
'last_seen': datetime.now().isoformat(),
|
|
||||||
'rssi': client.get('rssi', self.wifi_clients[mac].get('rssi')),
|
|
||||||
'associated_bssid': client.get('associated_bssid', self.wifi_clients[mac].get('associated_bssid')),
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
self.wifi_clients[mac] = {
|
|
||||||
'mac': mac,
|
|
||||||
'vendor': client.get('vendor', ''),
|
|
||||||
'rssi': client.get('rssi'),
|
|
||||||
'associated_bssid': client.get('associated_bssid'),
|
|
||||||
'probed_ssids': client.get('probed_ssids', []),
|
|
||||||
'probe_count': client.get('probe_count', len(client.get('probed_ssids', []))),
|
|
||||||
'first_seen': datetime.now().isoformat(),
|
|
||||||
'last_seen': datetime.now().isoformat(),
|
|
||||||
}
|
|
||||||
|
|
||||||
def add_rf_signal(self, signal: dict) -> None:
|
def add_rf_signal(self, signal: dict) -> None:
|
||||||
"""Add an RF signal to the current baseline."""
|
"""Add an RF signal to the current baseline."""
|
||||||
if not self.recording:
|
if not self.recording:
|
||||||
@@ -229,7 +197,6 @@ class BaselineRecorder:
|
|||||||
'recording': self.recording,
|
'recording': self.recording,
|
||||||
'baseline_id': self.current_baseline_id,
|
'baseline_id': self.current_baseline_id,
|
||||||
'wifi_count': len(self.wifi_networks),
|
'wifi_count': len(self.wifi_networks),
|
||||||
'wifi_client_count': len(self.wifi_clients),
|
|
||||||
'bt_count': len(self.bt_devices),
|
'bt_count': len(self.bt_devices),
|
||||||
'rf_count': len(self.rf_frequencies),
|
'rf_count': len(self.rf_frequencies),
|
||||||
}
|
}
|
||||||
@@ -258,11 +225,6 @@ class BaselineComparator:
|
|||||||
for d in baseline.get('bt_devices', [])
|
for d in baseline.get('bt_devices', [])
|
||||||
if d.get('mac') or d.get('address')
|
if d.get('mac') or d.get('address')
|
||||||
}
|
}
|
||||||
self.baseline_wifi_clients = {
|
|
||||||
d.get('mac', d.get('address', '')).upper(): d
|
|
||||||
for d in baseline.get('wifi_clients', [])
|
|
||||||
if d.get('mac') or d.get('address')
|
|
||||||
}
|
|
||||||
self.baseline_rf = {
|
self.baseline_rf = {
|
||||||
round(d.get('frequency', 0), 1): d
|
round(d.get('frequency', 0), 1): d
|
||||||
for d in baseline.get('rf_frequencies', [])
|
for d in baseline.get('rf_frequencies', [])
|
||||||
@@ -338,37 +300,6 @@ class BaselineComparator:
|
|||||||
'matching_count': len(matching_devices),
|
'matching_count': len(matching_devices),
|
||||||
}
|
}
|
||||||
|
|
||||||
def compare_wifi_clients(self, current_devices: list[dict]) -> dict:
|
|
||||||
"""Compare current WiFi clients against baseline."""
|
|
||||||
current_macs = {
|
|
||||||
d.get('mac', d.get('address', '')).upper(): d
|
|
||||||
for d in current_devices
|
|
||||||
if d.get('mac') or d.get('address')
|
|
||||||
}
|
|
||||||
|
|
||||||
new_devices = []
|
|
||||||
missing_devices = []
|
|
||||||
matching_devices = []
|
|
||||||
|
|
||||||
for mac, device in current_macs.items():
|
|
||||||
if mac not in self.baseline_wifi_clients:
|
|
||||||
new_devices.append(device)
|
|
||||||
else:
|
|
||||||
matching_devices.append(device)
|
|
||||||
|
|
||||||
for mac, device in self.baseline_wifi_clients.items():
|
|
||||||
if mac not in current_macs:
|
|
||||||
missing_devices.append(device)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'new': new_devices,
|
|
||||||
'missing': missing_devices,
|
|
||||||
'matching': matching_devices,
|
|
||||||
'new_count': len(new_devices),
|
|
||||||
'missing_count': len(missing_devices),
|
|
||||||
'matching_count': len(matching_devices),
|
|
||||||
}
|
|
||||||
|
|
||||||
def compare_rf(self, current_signals: list[dict]) -> dict:
|
def compare_rf(self, current_signals: list[dict]) -> dict:
|
||||||
"""Compare current RF signals against baseline."""
|
"""Compare current RF signals against baseline."""
|
||||||
current_freqs = {
|
current_freqs = {
|
||||||
@@ -403,7 +334,6 @@ class BaselineComparator:
|
|||||||
def compare_all(
|
def compare_all(
|
||||||
self,
|
self,
|
||||||
wifi_devices: list[dict] | None = None,
|
wifi_devices: list[dict] | None = None,
|
||||||
wifi_clients: list[dict] | None = None,
|
|
||||||
bt_devices: list[dict] | None = None,
|
bt_devices: list[dict] | None = None,
|
||||||
rf_signals: list[dict] | None = None
|
rf_signals: list[dict] | None = None
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -415,7 +345,6 @@ class BaselineComparator:
|
|||||||
"""
|
"""
|
||||||
results = {
|
results = {
|
||||||
'wifi': None,
|
'wifi': None,
|
||||||
'wifi_clients': None,
|
|
||||||
'bluetooth': None,
|
'bluetooth': None,
|
||||||
'rf': None,
|
'rf': None,
|
||||||
'total_new': 0,
|
'total_new': 0,
|
||||||
@@ -427,11 +356,6 @@ class BaselineComparator:
|
|||||||
results['total_new'] += results['wifi']['new_count']
|
results['total_new'] += results['wifi']['new_count']
|
||||||
results['total_missing'] += results['wifi']['missing_count']
|
results['total_missing'] += results['wifi']['missing_count']
|
||||||
|
|
||||||
if wifi_clients is not None:
|
|
||||||
results['wifi_clients'] = self.compare_wifi_clients(wifi_clients)
|
|
||||||
results['total_new'] += results['wifi_clients']['new_count']
|
|
||||||
results['total_missing'] += results['wifi_clients']['missing_count']
|
|
||||||
|
|
||||||
if bt_devices is not None:
|
if bt_devices is not None:
|
||||||
results['bluetooth'] = self.compare_bluetooth(bt_devices)
|
results['bluetooth'] = self.compare_bluetooth(bt_devices)
|
||||||
results['total_new'] += results['bluetooth']['new_count']
|
results['total_new'] += results['bluetooth']['new_count']
|
||||||
@@ -447,7 +371,6 @@ class BaselineComparator:
|
|||||||
|
|
||||||
def get_comparison_for_active_baseline(
|
def get_comparison_for_active_baseline(
|
||||||
wifi_devices: list[dict] | None = None,
|
wifi_devices: list[dict] | None = None,
|
||||||
wifi_clients: list[dict] | None = None,
|
|
||||||
bt_devices: list[dict] | None = None,
|
bt_devices: list[dict] | None = None,
|
||||||
rf_signals: list[dict] | None = None
|
rf_signals: list[dict] | None = None
|
||||||
) -> dict | None:
|
) -> dict | None:
|
||||||
@@ -462,4 +385,4 @@ def get_comparison_for_active_baseline(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
comparator = BaselineComparator(baseline)
|
comparator = BaselineComparator(baseline)
|
||||||
return comparator.compare_all(wifi_devices, wifi_clients, bt_devices, rf_signals)
|
return comparator.compare_all(wifi_devices, bt_devices, rf_signals)
|
||||||
|
|||||||
+71
-209
@@ -122,11 +122,6 @@ class DeviceProfile:
|
|||||||
name: Optional[str] = None
|
name: Optional[str] = None
|
||||||
manufacturer: Optional[str] = None
|
manufacturer: Optional[str] = None
|
||||||
device_type: Optional[str] = None
|
device_type: Optional[str] = None
|
||||||
tracker_type: Optional[str] = None
|
|
||||||
tracker_name: Optional[str] = None
|
|
||||||
tracker_confidence: Optional[str] = None
|
|
||||||
tracker_confidence_score: Optional[float] = None
|
|
||||||
tracker_evidence: list[str] = field(default_factory=list)
|
|
||||||
|
|
||||||
# Bluetooth-specific
|
# Bluetooth-specific
|
||||||
services: list[str] = field(default_factory=list)
|
services: list[str] = field(default_factory=list)
|
||||||
@@ -244,11 +239,6 @@ class DeviceProfile:
|
|||||||
'name': self.name,
|
'name': self.name,
|
||||||
'manufacturer': self.manufacturer,
|
'manufacturer': self.manufacturer,
|
||||||
'device_type': self.device_type,
|
'device_type': self.device_type,
|
||||||
'tracker_type': self.tracker_type,
|
|
||||||
'tracker_name': self.tracker_name,
|
|
||||||
'tracker_confidence': self.tracker_confidence,
|
|
||||||
'tracker_confidence_score': self.tracker_confidence_score,
|
|
||||||
'tracker_evidence': self.tracker_evidence,
|
|
||||||
'ssid': self.ssid,
|
'ssid': self.ssid,
|
||||||
'frequency': self.frequency,
|
'frequency': self.frequency,
|
||||||
'first_seen': self.first_seen.isoformat() if self.first_seen else None,
|
'first_seen': self.first_seen.isoformat() if self.first_seen else None,
|
||||||
@@ -285,25 +275,6 @@ AUDIO_SERVICE_UUIDS = [
|
|||||||
'00001203-0000-1000-8000-00805f9b34fb', # Generic Audio
|
'00001203-0000-1000-8000-00805f9b34fb', # Generic Audio
|
||||||
]
|
]
|
||||||
|
|
||||||
_BT_BASE_UUID_SUFFIX = '-0000-1000-8000-00805f9b34fb'
|
|
||||||
|
|
||||||
|
|
||||||
def _normalize_bt_uuid(value: str) -> str:
|
|
||||||
"""Normalize BLE UUIDs to 16-bit where possible."""
|
|
||||||
if not value:
|
|
||||||
return ''
|
|
||||||
uuid = str(value).lower().strip()
|
|
||||||
if uuid.startswith('0x'):
|
|
||||||
uuid = uuid[2:]
|
|
||||||
if uuid.endswith(_BT_BASE_UUID_SUFFIX) and len(uuid) >= 8:
|
|
||||||
return uuid[4:8]
|
|
||||||
if len(uuid) == 4:
|
|
||||||
return uuid
|
|
||||||
return uuid
|
|
||||||
|
|
||||||
|
|
||||||
AUDIO_SERVICE_UUIDS_16 = {_normalize_bt_uuid(u) for u in AUDIO_SERVICE_UUIDS}
|
|
||||||
|
|
||||||
# Generic chipset vendors (often used in covert devices)
|
# Generic chipset vendors (often used in covert devices)
|
||||||
GENERIC_CHIPSET_VENDORS = [
|
GENERIC_CHIPSET_VENDORS = [
|
||||||
'espressif',
|
'espressif',
|
||||||
@@ -445,23 +416,9 @@ class CorrelationEngine:
|
|||||||
profile.name = device.get('name') or profile.name
|
profile.name = device.get('name') or profile.name
|
||||||
profile.manufacturer = device.get('manufacturer') or profile.manufacturer
|
profile.manufacturer = device.get('manufacturer') or profile.manufacturer
|
||||||
profile.device_type = device.get('type') or profile.device_type
|
profile.device_type = device.get('type') or profile.device_type
|
||||||
services = device.get('services')
|
profile.services = device.get('services', []) or profile.services
|
||||||
if not services:
|
|
||||||
services = device.get('service_uuids')
|
|
||||||
profile.services = services or profile.services
|
|
||||||
profile.company_id = device.get('company_id') or profile.company_id
|
profile.company_id = device.get('company_id') or profile.company_id
|
||||||
profile.advertising_interval = device.get('advertising_interval') or profile.advertising_interval
|
profile.advertising_interval = device.get('advertising_interval') or profile.advertising_interval
|
||||||
tracker_data = device.get('tracker') or {}
|
|
||||||
if tracker_data:
|
|
||||||
profile.tracker_type = tracker_data.get('type') or profile.tracker_type
|
|
||||||
profile.tracker_name = tracker_data.get('name') or profile.tracker_name
|
|
||||||
profile.tracker_confidence = tracker_data.get('confidence') or profile.tracker_confidence
|
|
||||||
profile.tracker_confidence_score = tracker_data.get('confidence_score') or profile.tracker_confidence_score
|
|
||||||
evidence = tracker_data.get('evidence')
|
|
||||||
if isinstance(evidence, list):
|
|
||||||
profile.tracker_evidence = evidence
|
|
||||||
elif evidence:
|
|
||||||
profile.tracker_evidence = [str(evidence)]
|
|
||||||
|
|
||||||
# Add RSSI sample
|
# Add RSSI sample
|
||||||
rssi = device.get('rssi', device.get('signal'))
|
rssi = device.get('rssi', device.get('signal'))
|
||||||
@@ -477,19 +434,6 @@ class CorrelationEngine:
|
|||||||
# === Detection Logic ===
|
# === Detection Logic ===
|
||||||
|
|
||||||
# 1. Unknown manufacturer or generic chipset
|
# 1. Unknown manufacturer or generic chipset
|
||||||
if not profile.manufacturer and mac and not device.get('is_randomized_mac'):
|
|
||||||
try:
|
|
||||||
first_octet = int(mac.split(':')[0], 16)
|
|
||||||
except (ValueError, IndexError):
|
|
||||||
first_octet = None
|
|
||||||
if first_octet is None or not (first_octet & 0x02):
|
|
||||||
try:
|
|
||||||
from data.oui import get_manufacturer
|
|
||||||
vendor = get_manufacturer(mac)
|
|
||||||
if vendor and vendor != 'Unknown':
|
|
||||||
profile.manufacturer = vendor
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if not profile.manufacturer:
|
if not profile.manufacturer:
|
||||||
profile.add_indicator(
|
profile.add_indicator(
|
||||||
IndicatorType.UNKNOWN_DEVICE,
|
IndicatorType.UNKNOWN_DEVICE,
|
||||||
@@ -513,8 +457,8 @@ class CorrelationEngine:
|
|||||||
|
|
||||||
# 3. Audio-capable services
|
# 3. Audio-capable services
|
||||||
if profile.services:
|
if profile.services:
|
||||||
normalized_services = {_normalize_bt_uuid(s) for s in profile.services if s}
|
audio_services = [s for s in profile.services
|
||||||
audio_services = [s for s in normalized_services if s in AUDIO_SERVICE_UUIDS_16]
|
if s.lower() in [u.lower() for u in AUDIO_SERVICE_UUIDS]]
|
||||||
if audio_services:
|
if audio_services:
|
||||||
profile.add_indicator(
|
profile.add_indicator(
|
||||||
IndicatorType.AUDIO_CAPABLE,
|
IndicatorType.AUDIO_CAPABLE,
|
||||||
@@ -577,38 +521,6 @@ class CorrelationEngine:
|
|||||||
# 9. Known tracker detection (AirTag, Tile, SmartTag, ESP32)
|
# 9. Known tracker detection (AirTag, Tile, SmartTag, ESP32)
|
||||||
mac_prefix = mac[:8] if len(mac) >= 8 else ''
|
mac_prefix = mac[:8] if len(mac) >= 8 else ''
|
||||||
tracker_detected = False
|
tracker_detected = False
|
||||||
tracker_data = device.get('tracker') or {}
|
|
||||||
|
|
||||||
if tracker_data.get('is_tracker'):
|
|
||||||
tracker_detected = True
|
|
||||||
tracker_label = tracker_data.get('name') or tracker_data.get('type')
|
|
||||||
if tracker_label:
|
|
||||||
label_lower = str(tracker_label).lower()
|
|
||||||
if 'airtag' in label_lower or 'find my' in label_lower:
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.AIRTAG_DETECTED,
|
|
||||||
f'Tracker detected: {tracker_label}',
|
|
||||||
{'mac': mac, 'tracker_type': tracker_label}
|
|
||||||
)
|
|
||||||
profile.device_type = 'AirTag'
|
|
||||||
elif 'tile' in label_lower:
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.TILE_DETECTED,
|
|
||||||
f'Tracker detected: {tracker_label}',
|
|
||||||
{'mac': mac, 'tracker_type': tracker_label}
|
|
||||||
)
|
|
||||||
profile.device_type = 'Tile Tracker'
|
|
||||||
elif 'smarttag' in label_lower or 'samsung' in label_lower:
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.SMARTTAG_DETECTED,
|
|
||||||
f'Tracker detected: {tracker_label}',
|
|
||||||
{'mac': mac, 'tracker_type': tracker_label}
|
|
||||||
)
|
|
||||||
profile.device_type = 'Samsung SmartTag'
|
|
||||||
else:
|
|
||||||
profile.device_type = tracker_label
|
|
||||||
elif not profile.device_type:
|
|
||||||
profile.device_type = 'Tracker'
|
|
||||||
|
|
||||||
# Check for tracker flags from BLE scanner (manufacturer ID detection)
|
# Check for tracker flags from BLE scanner (manufacturer ID detection)
|
||||||
if device.get('is_airtag'):
|
if device.get('is_airtag'):
|
||||||
@@ -762,25 +674,15 @@ class CorrelationEngine:
|
|||||||
"""
|
"""
|
||||||
bssid = device.get('bssid', device.get('mac', '')).upper()
|
bssid = device.get('bssid', device.get('mac', '')).upper()
|
||||||
profile = self.get_or_create_profile(bssid, 'wifi')
|
profile = self.get_or_create_profile(bssid, 'wifi')
|
||||||
is_client = bool(device.get('is_client') or device.get('role') == 'client')
|
|
||||||
|
|
||||||
# Update profile data
|
# Update profile data
|
||||||
ssid = device.get('ssid', device.get('essid', ''))
|
ssid = device.get('ssid', device.get('essid', ''))
|
||||||
if is_client:
|
profile.ssid = ssid if ssid else profile.ssid
|
||||||
profile.name = device.get('name') or device.get('vendor') or profile.name or f'Client ({bssid[-8:]})'
|
profile.name = ssid or f'Hidden Network ({bssid[-8:]})'
|
||||||
profile.device_type = 'client'
|
profile.channel = device.get('channel') or profile.channel
|
||||||
profile.ssid = profile.ssid # Clients are not SSIDs
|
profile.encryption = device.get('encryption', device.get('privacy')) or profile.encryption
|
||||||
profile.channel = device.get('channel') or profile.channel
|
profile.beacon_interval = device.get('beacon_interval') or profile.beacon_interval
|
||||||
profile.encryption = profile.encryption
|
profile.is_hidden = not ssid or ssid in ['', 'Hidden', '[Hidden]']
|
||||||
profile.beacon_interval = profile.beacon_interval
|
|
||||||
profile.is_hidden = False
|
|
||||||
else:
|
|
||||||
profile.ssid = ssid if ssid else profile.ssid
|
|
||||||
profile.name = ssid or f'Hidden Network ({bssid[-8:]})'
|
|
||||||
profile.channel = device.get('channel') or profile.channel
|
|
||||||
profile.encryption = device.get('encryption', device.get('privacy')) or profile.encryption
|
|
||||||
profile.beacon_interval = device.get('beacon_interval') or profile.beacon_interval
|
|
||||||
profile.is_hidden = not ssid or ssid in ['', 'Hidden', '[Hidden]']
|
|
||||||
|
|
||||||
# Extract manufacturer from OUI
|
# Extract manufacturer from OUI
|
||||||
if bssid and len(bssid) >= 8:
|
if bssid and len(bssid) >= 8:
|
||||||
@@ -798,118 +700,78 @@ class CorrelationEngine:
|
|||||||
profile.indicators = []
|
profile.indicators = []
|
||||||
|
|
||||||
# === Detection Logic ===
|
# === Detection Logic ===
|
||||||
if is_client:
|
|
||||||
if not profile.manufacturer:
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.UNKNOWN_DEVICE,
|
|
||||||
'Unknown client manufacturer',
|
|
||||||
{'mac': bssid}
|
|
||||||
)
|
|
||||||
|
|
||||||
if profile.detection_count >= 3:
|
# 1. Hidden or unnamed SSID
|
||||||
profile.add_indicator(
|
if profile.is_hidden:
|
||||||
IndicatorType.PERSISTENT,
|
profile.add_indicator(
|
||||||
f'Persistent client ({profile.detection_count} detections)',
|
IndicatorType.HIDDEN_IDENTITY,
|
||||||
{'count': profile.detection_count}
|
'Hidden or empty SSID',
|
||||||
)
|
{'ssid': ssid}
|
||||||
|
)
|
||||||
|
|
||||||
rssi_stability = profile.get_rssi_stability()
|
# 2. BSSID not in authorized list (would need baseline)
|
||||||
if rssi_stability > 0.7 and len(profile.rssi_samples) >= 5:
|
# For now, mark as unknown if no manufacturer
|
||||||
profile.add_indicator(
|
if not profile.manufacturer:
|
||||||
IndicatorType.STABLE_RSSI,
|
profile.add_indicator(
|
||||||
f'Stable client signal (stability: {rssi_stability:.0%})',
|
IndicatorType.UNKNOWN_DEVICE,
|
||||||
{'stability': rssi_stability}
|
'Unknown AP manufacturer',
|
||||||
)
|
{'bssid': bssid}
|
||||||
|
)
|
||||||
|
|
||||||
if self.is_during_meeting():
|
# 3. Consumer device OUI in restricted environment
|
||||||
profile.add_indicator(
|
consumer_ouis = ['tp-link', 'netgear', 'd-link', 'linksys', 'asus']
|
||||||
IndicatorType.MEETING_CORRELATED,
|
if profile.manufacturer and any(c in profile.manufacturer.lower() for c in consumer_ouis):
|
||||||
'Detected during sensitive period',
|
profile.add_indicator(
|
||||||
{'during_meeting': True}
|
IndicatorType.ROGUE_AP,
|
||||||
)
|
f'Consumer-grade AP detected: {profile.manufacturer}',
|
||||||
|
{'manufacturer': profile.manufacturer}
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
# 4. Camera device patterns
|
||||||
first_octet = int(bssid.split(':')[0], 16)
|
camera_keywords = ['cam', 'camera', 'ipcam', 'dvr', 'nvr', 'wyze',
|
||||||
if first_octet & 0x02:
|
'ring', 'arlo', 'nest', 'blink', 'eufy', 'yi']
|
||||||
profile.add_indicator(
|
if ssid and any(k in ssid.lower() for k in camera_keywords):
|
||||||
IndicatorType.MAC_ROTATION,
|
profile.add_indicator(
|
||||||
'Random/locally administered MAC detected',
|
IndicatorType.AUDIO_CAPABLE, # Cameras often have mics
|
||||||
{'mac': bssid}
|
f'Potential camera device: {ssid}',
|
||||||
)
|
{'ssid': ssid}
|
||||||
except (ValueError, IndexError):
|
)
|
||||||
pass
|
|
||||||
else:
|
|
||||||
# 1. Hidden or unnamed SSID
|
|
||||||
if profile.is_hidden:
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.HIDDEN_IDENTITY,
|
|
||||||
'Hidden or empty SSID',
|
|
||||||
{'ssid': ssid}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 2. BSSID not in authorized list (would need baseline)
|
# 5. Persistent presence
|
||||||
# For now, mark as unknown if no manufacturer
|
if profile.detection_count >= 3:
|
||||||
if not profile.manufacturer:
|
profile.add_indicator(
|
||||||
profile.add_indicator(
|
IndicatorType.PERSISTENT,
|
||||||
IndicatorType.UNKNOWN_DEVICE,
|
f'Persistent AP ({profile.detection_count} detections)',
|
||||||
'Unknown AP manufacturer',
|
{'count': profile.detection_count}
|
||||||
{'bssid': bssid}
|
)
|
||||||
)
|
|
||||||
|
|
||||||
# 3. Consumer device OUI in restricted environment
|
# 6. Stable RSSI (fixed placement)
|
||||||
consumer_ouis = ['tp-link', 'netgear', 'd-link', 'linksys', 'asus']
|
rssi_stability = profile.get_rssi_stability()
|
||||||
if profile.manufacturer and any(c in profile.manufacturer.lower() for c in consumer_ouis):
|
if rssi_stability > 0.7 and len(profile.rssi_samples) >= 5:
|
||||||
|
profile.add_indicator(
|
||||||
|
IndicatorType.STABLE_RSSI,
|
||||||
|
f'Stable signal (stability: {rssi_stability:.0%})',
|
||||||
|
{'stability': rssi_stability}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 7. Meeting correlation
|
||||||
|
if self.is_during_meeting():
|
||||||
|
profile.add_indicator(
|
||||||
|
IndicatorType.MEETING_CORRELATED,
|
||||||
|
'Detected during sensitive period',
|
||||||
|
{'during_meeting': True}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 8. Strong hidden AP (very suspicious)
|
||||||
|
if profile.is_hidden and profile.rssi_samples:
|
||||||
|
latest_rssi = profile.rssi_samples[-1][1]
|
||||||
|
if latest_rssi > -50:
|
||||||
profile.add_indicator(
|
profile.add_indicator(
|
||||||
IndicatorType.ROGUE_AP,
|
IndicatorType.ROGUE_AP,
|
||||||
f'Consumer-grade AP detected: {profile.manufacturer}',
|
f'Strong hidden AP (RSSI: {latest_rssi} dBm)',
|
||||||
{'manufacturer': profile.manufacturer}
|
{'rssi': latest_rssi}
|
||||||
)
|
)
|
||||||
|
|
||||||
# 4. Camera device patterns
|
|
||||||
camera_keywords = ['cam', 'camera', 'ipcam', 'dvr', 'nvr', 'wyze',
|
|
||||||
'ring', 'arlo', 'nest', 'blink', 'eufy', 'yi']
|
|
||||||
if ssid and any(k in ssid.lower() for k in camera_keywords):
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.AUDIO_CAPABLE, # Cameras often have mics
|
|
||||||
f'Potential camera device: {ssid}',
|
|
||||||
{'ssid': ssid}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 5. Persistent presence
|
|
||||||
if profile.detection_count >= 3:
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.PERSISTENT,
|
|
||||||
f'Persistent AP ({profile.detection_count} detections)',
|
|
||||||
{'count': profile.detection_count}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 6. Stable RSSI (fixed placement)
|
|
||||||
rssi_stability = profile.get_rssi_stability()
|
|
||||||
if rssi_stability > 0.7 and len(profile.rssi_samples) >= 5:
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.STABLE_RSSI,
|
|
||||||
f'Stable signal (stability: {rssi_stability:.0%})',
|
|
||||||
{'stability': rssi_stability}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 7. Meeting correlation
|
|
||||||
if self.is_during_meeting():
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.MEETING_CORRELATED,
|
|
||||||
'Detected during sensitive period',
|
|
||||||
{'during_meeting': True}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 8. Strong hidden AP (very suspicious)
|
|
||||||
if profile.is_hidden and profile.rssi_samples:
|
|
||||||
latest_rssi = profile.rssi_samples[-1][1]
|
|
||||||
if latest_rssi > -50:
|
|
||||||
profile.add_indicator(
|
|
||||||
IndicatorType.ROGUE_AP,
|
|
||||||
f'Strong hidden AP (RSSI: {latest_rssi} dBm)',
|
|
||||||
{'rssi': latest_rssi}
|
|
||||||
)
|
|
||||||
|
|
||||||
self._apply_known_device_modifier(profile, bssid, 'wifi')
|
self._apply_known_device_modifier(profile, bssid, 'wifi')
|
||||||
|
|
||||||
return profile
|
return profile
|
||||||
|
|||||||
+1
-19
@@ -122,10 +122,6 @@ class ThreatDetector:
|
|||||||
if 'mac' in client:
|
if 'mac' in client:
|
||||||
self.baseline_wifi_macs.add(client['mac'].upper())
|
self.baseline_wifi_macs.add(client['mac'].upper())
|
||||||
|
|
||||||
for client in baseline.get('wifi_clients', []):
|
|
||||||
if 'mac' in client:
|
|
||||||
self.baseline_wifi_macs.add(client['mac'].upper())
|
|
||||||
|
|
||||||
# Bluetooth devices
|
# Bluetooth devices
|
||||||
for device in baseline.get('bt_devices', []):
|
for device in baseline.get('bt_devices', []):
|
||||||
if 'mac' in device:
|
if 'mac' in device:
|
||||||
@@ -483,7 +479,6 @@ class ThreatDetector:
|
|||||||
manufacturer = device.get('manufacturer', '')
|
manufacturer = device.get('manufacturer', '')
|
||||||
device_type = device.get('type', '')
|
device_type = device.get('type', '')
|
||||||
manufacturer_data = device.get('manufacturer_data')
|
manufacturer_data = device.get('manufacturer_data')
|
||||||
tracker_data = device.get('tracker', {}) or {}
|
|
||||||
|
|
||||||
threats = []
|
threats = []
|
||||||
|
|
||||||
@@ -495,20 +490,7 @@ class ThreatDetector:
|
|||||||
'reason': 'Device not present in baseline',
|
'reason': 'Device not present in baseline',
|
||||||
})
|
})
|
||||||
|
|
||||||
# Check for known trackers (v2 tracker data if available)
|
# Check for known trackers
|
||||||
if tracker_data.get('is_tracker'):
|
|
||||||
tracker_label = tracker_data.get('name') or tracker_data.get('type') or 'Tracker'
|
|
||||||
confidence = str(tracker_data.get('confidence') or '').lower()
|
|
||||||
severity = 'high' if confidence in ('high', 'medium') else 'medium'
|
|
||||||
threats.append({
|
|
||||||
'type': 'tracker',
|
|
||||||
'severity': severity,
|
|
||||||
'reason': f"Tracker detected: {tracker_label}",
|
|
||||||
'tracker_type': tracker_label,
|
|
||||||
'details': tracker_data.get('evidence', []),
|
|
||||||
})
|
|
||||||
|
|
||||||
# Check for known trackers (legacy patterns)
|
|
||||||
tracker_info = is_known_tracker(name, manufacturer_data)
|
tracker_info = is_known_tracker(name, manufacturer_data)
|
||||||
if tracker_info:
|
if tracker_info:
|
||||||
threats.append({
|
threats.append({
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user