first commit
This commit is contained in:
commit
e39e5f491e
|
|
@ -0,0 +1,25 @@
|
|||
# MQTT broker
|
||||
WIFI_SPOOL_MQTT_HOST=95.142.38.109
|
||||
WIFI_SPOOL_MQTT_PORT=1883
|
||||
# Detect a broken MQTT connection within this keepalive interval
|
||||
WIFI_SPOOL_MQTT_KEEPALIVE=30
|
||||
WIFI_SPOOL_MQTT_TOPIC="wifi/vostok/44/#"
|
||||
WIFI_SPOOL_MQTT_USERNAME=admin
|
||||
WIFI_SPOOL_MQTT_PASSWORD=change-me
|
||||
WIFI_SPOOL_MOSQUITTO_BIN=mosquitto_sub
|
||||
|
||||
# Only scan results with this SSID are stored
|
||||
WIFI_SPOOL_TARGET_SSID=RONAVI_MCNS5
|
||||
|
||||
# PostgreSQL
|
||||
WIFI_SPOOL_POSTGRES_HOST=localhost
|
||||
WIFI_SPOOL_POSTGRES_PORT=5432
|
||||
WIFI_SPOOL_POSTGRES_DATABASE=wifi_spool
|
||||
WIFI_SPOOL_POSTGRES_USER=wifi_spool
|
||||
WIFI_SPOOL_POSTGRES_PASSWORD=change-me
|
||||
WIFI_SPOOL_POSTGRES_CONNECT_TIMEOUT=10
|
||||
|
||||
# Web heatmap service. Use 0.0.0.0 to listen on the network.
|
||||
WIFI_SPOOL_WEB_HOST=127.0.0.1
|
||||
WIFI_SPOOL_WEB_PORT=8080
|
||||
WIFI_SPOOL_WEB_DEFAULT_DATE_RANGE_MINUTES=60
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
.env
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
# Wi-Fi spool
|
||||
|
||||
Сервис читает вывод `mosquitto_sub`, выбирает из сообщений `scan_results`
|
||||
только точки с SSID `RONAVI_MCNS5` и сохраняет их в PostgreSQL.
|
||||
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
sudo apt install mosquitto-clients
|
||||
python3 -m pip install -r requirements.txt
|
||||
cp .env.example .env
|
||||
python3 wifi_spool.py
|
||||
```
|
||||
|
||||
Предварительно создайте пользователя и базу PostgreSQL:
|
||||
|
||||
```sql
|
||||
CREATE USER wifi_spool WITH PASSWORD 'change-me';
|
||||
CREATE DATABASE wifi_spool OWNER wifi_spool;
|
||||
```
|
||||
|
||||
Таблицы и индексы сервис создаёт автоматически. Скопируйте пример настроек и
|
||||
укажите в `.env` реальные пароли и параметры подключения:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Файл `.env` автоматически загружается при запуске и исключён из Git. Любую
|
||||
настройку также можно передать через окружение; значение из окружения имеет
|
||||
приоритет над `.env`:
|
||||
|
||||
```bash
|
||||
WIFI_SPOOL_MQTT_PASSWORD='secret' \
|
||||
WIFI_SPOOL_POSTGRES_HOST='localhost' \
|
||||
WIFI_SPOOL_POSTGRES_PORT='5432' \
|
||||
WIFI_SPOOL_POSTGRES_DATABASE='wifi_spool' \
|
||||
WIFI_SPOOL_POSTGRES_USER='wifi_spool' \
|
||||
WIFI_SPOOL_POSTGRES_PASSWORD='change-me' \
|
||||
python3 wifi_spool.py
|
||||
```
|
||||
|
||||
Доступные настройки находятся в `settings.py`; каждая переопределяется
|
||||
одноимённой переменной окружения с префиксом `WIFI_SPOOL_`.
|
||||
|
||||
Для проверки одной или нескольких заранее сохранённых строк:
|
||||
|
||||
```bash
|
||||
python3 wifi_spool.py --stdin < messages.txt
|
||||
```
|
||||
|
||||
## Структура БД
|
||||
|
||||
- `bssids`: уникальные BSSID (`id`, `bssid`);
|
||||
- `agents`: уникальные агенты (`id`, `agent_name`);
|
||||
- `scan_results`: ссылка `bssid_id`, целые `location_x`/`location_y`, целый
|
||||
`signal_level`, ссылка `agent_id` и дата сбора `collected_at` с часовым поясом.
|
||||
|
||||
`collected_at` заполняется автоматически текущим временем сервера PostgreSQL.
|
||||
|
||||
Повторное обнаружение BSSID не создаёт дубликат в `bssids`, но создаёт новую
|
||||
строку измерения в `scan_results`. Имена агентов также не дублируются: в
|
||||
`scan_results` хранится только числовой идентификатор агента.
|
||||
|
||||
## Установка как сервис Debian
|
||||
|
||||
На чистом Debian запустите установщик из корня проекта:
|
||||
|
||||
```bash
|
||||
chmod +x deploy/install.sh
|
||||
sudo ./deploy/install.sh
|
||||
```
|
||||
|
||||
Установщик:
|
||||
|
||||
- устанавливает `python3-venv` и `mosquitto-clients`;
|
||||
- создаёт системного пользователя `wifi-spool` без возможности входа;
|
||||
- устанавливает приложение и виртуальное окружение в `/opt/wifi-spool`;
|
||||
- создаёт настройки `/etc/wifi-spool/wifi-spool.env` с правами `0640`;
|
||||
- устанавливает и включает unit `wifi-spool.service`.
|
||||
|
||||
При потере MQTT-соединения keepalive обнаруживает разрыв, а `mosquitto_sub`
|
||||
переподключается. Если MQTT-клиент или Python-процесс завершится, `systemd`
|
||||
перезапустит сервис через 5 секунд без ограничения числа попыток. При потере
|
||||
PostgreSQL ошибка записи завершает процесс, после чего новый процесс заново
|
||||
подключается к базе. Поэтому восстановление работает и после длительного
|
||||
отключения сети или базы данных.
|
||||
|
||||
При первой установке сервис намеренно не запускается, пока не будут заменены
|
||||
пароли в конфигурации:
|
||||
|
||||
```bash
|
||||
sudo nano /etc/wifi-spool/wifi-spool.env
|
||||
sudo systemctl start wifi-spool
|
||||
```
|
||||
|
||||
У пользователя PostgreSQL должны быть права на создание и изменение таблиц в
|
||||
целевой базе. Основные команды управления:
|
||||
|
||||
```bash
|
||||
sudo systemctl status wifi-spool
|
||||
sudo systemctl restart wifi-spool
|
||||
sudo systemctl stop wifi-spool
|
||||
sudo journalctl -u wifi-spool -f
|
||||
```
|
||||
|
||||
Для обновления кода повторно запустите `sudo ./deploy/install.sh`. Существующий
|
||||
файл настроек не перезаписывается, сервис перезапускается автоматически.
|
||||
|
||||
## Веб-интерфейс тепловой карты
|
||||
|
||||
Второй сервис `wifi-spool-web` строит тепловую карту по локальным координатам
|
||||
`location_x` и `location_y`. Каждая координата отображается квадратом `1×1`,
|
||||
цвет которого соответствует максимальному `signal_level` за выбранный временной
|
||||
интервал. Границы сетки фиксируются по `min(x)`, `max(x)`, `min(y)`, `max(y)`
|
||||
для всего выбранного периода. На обеих осях используется единый масштаб:
|
||||
квадрат `1×1` имеет одинаковую ширину и высоту, а сетка растягивается на
|
||||
максимально доступную область. В интерфейсе можно:
|
||||
|
||||
- выбрать начальные дату и время;
|
||||
- выбрать конечные дату и время;
|
||||
- увидеть максимальный `signal_level` в каждой точке за весь выбранный период;
|
||||
- выбрать один или несколько BSSID либо показать все.
|
||||
|
||||
Настройки веб-сервиса находятся в `/etc/wifi-spool/wifi-spool.env`:
|
||||
|
||||
```dotenv
|
||||
# Для доступа с других компьютеров локальной сети
|
||||
WIFI_SPOOL_WEB_HOST=0.0.0.0
|
||||
WIFI_SPOOL_WEB_PORT=8080
|
||||
WIFI_SPOOL_WEB_DEFAULT_DATE_RANGE_MINUTES=60
|
||||
```
|
||||
|
||||
После изменения настроек:
|
||||
|
||||
```bash
|
||||
sudo systemctl restart wifi-spool-web
|
||||
```
|
||||
|
||||
Открыть панель можно по адресу `http://IP_СЕРВЕРА:8080`. Проверка состояния API:
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8080/health
|
||||
sudo systemctl status wifi-spool-web
|
||||
sudo journalctl -u wifi-spool-web -f
|
||||
```
|
||||
|
||||
Веб-интерфейс не содержит встроенной авторизации. При доступе не только из
|
||||
доверенной локальной сети рекомендуется закрыть порт файрволом либо поставить
|
||||
перед сервисом Nginx с HTTPS и авторизацией.
|
||||
|
||||
## Удаление сервисов
|
||||
|
||||
Удалить оба сервиса, каталог `/opt/wifi-spool` и системного пользователя:
|
||||
|
||||
```bash
|
||||
sudo ./deploy/uninstall.sh
|
||||
```
|
||||
|
||||
Конфигурация `/etc/wifi-spool/wifi-spool.env` по умолчанию сохраняется, чтобы
|
||||
её можно было использовать при повторной установке. Удалить также настройки:
|
||||
|
||||
```bash
|
||||
sudo ./deploy/uninstall.sh --purge
|
||||
```
|
||||
|
||||
Скрипт удаления не изменяет базу PostgreSQL и не удаляет таблицы с накопленными
|
||||
данными.
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
APP_NAME="wifi-spool"
|
||||
APP_USER="wifi-spool"
|
||||
APP_DIR="/opt/wifi-spool"
|
||||
CONFIG_DIR="/etc/wifi-spool"
|
||||
SERVICE_FILE="/etc/systemd/system/wifi-spool.service"
|
||||
WEB_SERVICE_FILE="/etc/systemd/system/wifi-spool-web.service"
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
echo "Run this installer as root: sudo ./deploy/install.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SOURCE_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
|
||||
MISSING_PACKAGES=""
|
||||
if ! command -v python3 >/dev/null 2>&1; then
|
||||
MISSING_PACKAGES="$MISSING_PACKAGES python3"
|
||||
fi
|
||||
if ! python3 -c "import venv" >/dev/null 2>&1; then
|
||||
MISSING_PACKAGES="$MISSING_PACKAGES python3-venv"
|
||||
fi
|
||||
if ! command -v mosquitto_sub >/dev/null 2>&1; then
|
||||
MISSING_PACKAGES="$MISSING_PACKAGES mosquitto-clients"
|
||||
fi
|
||||
|
||||
if [ -n "$MISSING_PACKAGES" ]; then
|
||||
echo "Installing missing packages:$MISSING_PACKAGES"
|
||||
if ! apt-get install -y $MISSING_PACKAGES; then
|
||||
echo "Failed to install required packages." >&2
|
||||
echo "Fix broken third-party APT repositories and run this installer again." >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "Required system packages are already installed; skipping apt update."
|
||||
fi
|
||||
|
||||
if ! getent passwd "$APP_USER" >/dev/null; then
|
||||
useradd --system --home-dir "$APP_DIR" --shell /usr/sbin/nologin "$APP_USER"
|
||||
fi
|
||||
|
||||
install -d -o root -g root -m 0755 "$APP_DIR"
|
||||
install -d -o root -g root -m 0755 "$APP_DIR/templates"
|
||||
install -d -o root -g root -m 0755 "$APP_DIR/static"
|
||||
install -d -o root -g "$APP_USER" -m 0750 "$CONFIG_DIR"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/wifi_spool.py" "$APP_DIR/wifi_spool.py"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/settings.py" "$APP_DIR/settings.py"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/web_app.py" "$APP_DIR/web_app.py"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/gunicorn.conf.py" "$APP_DIR/gunicorn.conf.py"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/templates/dashboard.html" "$APP_DIR/templates/dashboard.html"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/static/dashboard.css" "$APP_DIR/static/dashboard.css"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/static/dashboard.js" "$APP_DIR/static/dashboard.js"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/requirements.txt" "$APP_DIR/requirements.txt"
|
||||
install -o root -g root -m 0644 "$SOURCE_DIR/README.md" "$APP_DIR/README.md"
|
||||
|
||||
python3 -m venv "$APP_DIR/.venv"
|
||||
"$APP_DIR/.venv/bin/python" -m pip install --upgrade pip
|
||||
"$APP_DIR/.venv/bin/python" -m pip install -r "$APP_DIR/requirements.txt"
|
||||
|
||||
if [ ! -f "$CONFIG_DIR/wifi-spool.env" ]; then
|
||||
install -o root -g "$APP_USER" -m 0640 \
|
||||
"$SOURCE_DIR/.env.example" "$CONFIG_DIR/wifi-spool.env"
|
||||
echo "Created $CONFIG_DIR/wifi-spool.env"
|
||||
echo "Edit its passwords before starting the service."
|
||||
START_SERVICE=0
|
||||
else
|
||||
START_SERVICE=1
|
||||
fi
|
||||
|
||||
install -o root -g root -m 0644 \
|
||||
"$SOURCE_DIR/deploy/wifi-spool.service" "$SERVICE_FILE"
|
||||
install -o root -g root -m 0644 \
|
||||
"$SOURCE_DIR/deploy/wifi-spool-web.service" "$WEB_SERVICE_FILE"
|
||||
systemctl daemon-reload
|
||||
systemctl enable "$APP_NAME.service"
|
||||
systemctl enable "$APP_NAME-web.service"
|
||||
|
||||
if [ "$START_SERVICE" -eq 1 ]; then
|
||||
systemctl restart "$APP_NAME.service"
|
||||
systemctl restart "$APP_NAME-web.service"
|
||||
systemctl --no-pager --full status "$APP_NAME.service" || true
|
||||
systemctl --no-pager --full status "$APP_NAME-web.service" || true
|
||||
else
|
||||
echo "After editing the configuration, start the service with:"
|
||||
echo " sudo systemctl start $APP_NAME"
|
||||
echo " sudo systemctl start $APP_NAME-web"
|
||||
fi
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
PURGE_CONFIG=0
|
||||
|
||||
usage() {
|
||||
echo "Usage: sudo ./deploy/uninstall.sh [--purge]"
|
||||
echo " --purge also remove /etc/wifi-spool configuration"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
"") ;;
|
||||
--purge) PURGE_CONFIG=1 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) usage >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
if [ "$#" -gt 1 ]; then
|
||||
usage >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
echo "Run this uninstaller as root: sudo ./deploy/uninstall.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for service in wifi-spool.service wifi-spool-web.service; do
|
||||
systemctl disable --now "$service" 2>/dev/null || true
|
||||
done
|
||||
|
||||
rm -f /etc/systemd/system/wifi-spool.service
|
||||
rm -f /etc/systemd/system/wifi-spool-web.service
|
||||
systemctl daemon-reload
|
||||
systemctl reset-failed wifi-spool.service wifi-spool-web.service 2>/dev/null || true
|
||||
|
||||
if [ -d /opt/wifi-spool ]; then
|
||||
rm -rf /opt/wifi-spool
|
||||
fi
|
||||
|
||||
if getent passwd wifi-spool >/dev/null; then
|
||||
userdel wifi-spool
|
||||
fi
|
||||
|
||||
if [ "$PURGE_CONFIG" -eq 1 ]; then
|
||||
if [ -d /etc/wifi-spool ]; then
|
||||
rm -rf /etc/wifi-spool
|
||||
fi
|
||||
echo "Configuration /etc/wifi-spool removed."
|
||||
else
|
||||
echo "Configuration preserved in /etc/wifi-spool."
|
||||
fi
|
||||
|
||||
echo "Wi-Fi spool services and /opt/wifi-spool have been removed."
|
||||
echo "PostgreSQL tables and data were not changed."
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
[Unit]
|
||||
Description=Wi-Fi heatmap web dashboard
|
||||
Documentation=file:/opt/wifi-spool/README.md
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
StartLimitIntervalSec=0
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=wifi-spool
|
||||
Group=wifi-spool
|
||||
WorkingDirectory=/opt/wifi-spool
|
||||
EnvironmentFile=/etc/wifi-spool/wifi-spool.env
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
ExecStart=/opt/wifi-spool/.venv/bin/gunicorn --config /opt/wifi-spool/gunicorn.conf.py web_app:app
|
||||
Restart=always
|
||||
RestartSec=5s
|
||||
TimeoutStopSec=15s
|
||||
KillMode=control-group
|
||||
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
PrivateDevices=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectControlGroups=true
|
||||
RestrictSUIDSGID=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
[Unit]
|
||||
Description=Wi-Fi MQTT scan collector
|
||||
Documentation=file:/opt/wifi-spool/README.md
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
StartLimitIntervalSec=0
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=wifi-spool
|
||||
Group=wifi-spool
|
||||
WorkingDirectory=/opt/wifi-spool
|
||||
EnvironmentFile=/etc/wifi-spool/wifi-spool.env
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
ExecStart=/opt/wifi-spool/.venv/bin/python /opt/wifi-spool/wifi_spool.py
|
||||
Restart=always
|
||||
RestartSec=5s
|
||||
TimeoutStopSec=15s
|
||||
KillMode=control-group
|
||||
|
||||
# Service hardening
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
PrivateDevices=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectControlGroups=true
|
||||
RestrictSUIDSGID=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
"""Gunicorn configuration for the heatmap service."""
|
||||
|
||||
from settings import SETTINGS
|
||||
|
||||
bind = f"{SETTINGS.web_host}:{SETTINGS.web_port}"
|
||||
workers = 2
|
||||
threads = 2
|
||||
timeout = 30
|
||||
accesslog = "-"
|
||||
errorlog = "-"
|
||||
capture_output = True
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
sudo apt install mosquitto-clients
|
||||
mosquitto_sub -h 95.142.38.109 -t 'wifi/vostok/44/#' -u admin -P RonaviMqtt -v
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
psycopg[binary]>=3.2,<4
|
||||
python-dotenv>=1.0,<2
|
||||
Flask>=3.1,<4
|
||||
gunicorn>=23,<24
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
"""Application settings, overridable through environment variables."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
# Load local configuration before dataclass defaults are evaluated.
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def _env(name: str, default: str) -> str:
|
||||
return os.environ.get(name, default)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
mqtt_host: str = _env("WIFI_SPOOL_MQTT_HOST", "95.142.38.109")
|
||||
mqtt_port: int = int(_env("WIFI_SPOOL_MQTT_PORT", "1883"))
|
||||
mqtt_keepalive_seconds: int = int(_env("WIFI_SPOOL_MQTT_KEEPALIVE", "30"))
|
||||
mqtt_topic: str = _env("WIFI_SPOOL_MQTT_TOPIC", "wifi/vostok/44/#")
|
||||
mqtt_username: str = _env("WIFI_SPOOL_MQTT_USERNAME", "admin")
|
||||
mqtt_password: str = _env("WIFI_SPOOL_MQTT_PASSWORD", "RonaviMqtt")
|
||||
mosquitto_sub_bin: str = _env("WIFI_SPOOL_MOSQUITTO_BIN", "mosquitto_sub")
|
||||
target_ssid: str = _env("WIFI_SPOOL_TARGET_SSID", "RONAVI_MCNS5")
|
||||
postgres_host: str = _env("WIFI_SPOOL_POSTGRES_HOST", "localhost")
|
||||
postgres_port: int = int(_env("WIFI_SPOOL_POSTGRES_PORT", "5432"))
|
||||
postgres_database: str = _env("WIFI_SPOOL_POSTGRES_DATABASE", "wifi_spool")
|
||||
postgres_user: str = _env("WIFI_SPOOL_POSTGRES_USER", "wifi_spool")
|
||||
postgres_password: str = _env("WIFI_SPOOL_POSTGRES_PASSWORD", "wifi_spool")
|
||||
postgres_connect_timeout: int = int(
|
||||
_env("WIFI_SPOOL_POSTGRES_CONNECT_TIMEOUT", "10")
|
||||
)
|
||||
web_host: str = _env("WIFI_SPOOL_WEB_HOST", "127.0.0.1")
|
||||
web_port: int = int(_env("WIFI_SPOOL_WEB_PORT", "8080"))
|
||||
web_default_date_range_minutes: int = int(
|
||||
_env("WIFI_SPOOL_WEB_DEFAULT_DATE_RANGE_MINUTES", "60")
|
||||
)
|
||||
|
||||
|
||||
SETTINGS = Settings()
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
:root { color-scheme: dark; font-family: Inter, system-ui, sans-serif; background: #0b1220; color: #e5edf7; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100vh; background: radial-gradient(circle at 70% 0, #172a46, #0b1220 45%); }
|
||||
header { display: flex; justify-content: space-between; align-items: center; padding: 24px 32px 12px; }
|
||||
h1 { margin: 0; font-size: 25px; } header p { color: #8fa3ba; margin: 5px 0; }
|
||||
main { display: grid; grid-template-columns: 280px 1fr; gap: 18px; padding: 16px 32px 32px; }
|
||||
.panel { background: rgba(17, 29, 47, .92); border: 1px solid #273b55; border-radius: 12px; box-shadow: 0 14px 35px #0005; }
|
||||
.controls { padding: 18px; display: flex; flex-direction: column; gap: 16px; }
|
||||
label, legend { font-size: 13px; color: #aebdd0; }
|
||||
.input-row { display: flex; align-items: center; gap: 8px; margin-top: 7px; }
|
||||
input[type=number], input[type=datetime-local] { width: 100%; }
|
||||
input, button { border: 1px solid #38516d; border-radius: 7px; background: #111e30; color: #edf5ff; padding: 9px; }
|
||||
button { cursor: pointer; } button:hover { border-color: #5e89b7; }
|
||||
button.primary { background: #1570a6; border-color: #2992cf; font-weight: 700; }
|
||||
fieldset { border: 1px solid #31465f; border-radius: 8px; padding: 10px; min-width: 0; }
|
||||
.filter-actions { display: flex; gap: 6px; margin-bottom: 8px; } .filter-actions button { padding: 4px 8px; font-size: 12px; }
|
||||
.bssid-list { max-height: 230px; overflow: auto; font-family: monospace; font-size: 12px; }
|
||||
.bssid-list label { display: block; padding: 5px 2px; white-space: nowrap; }
|
||||
.check { display: flex; align-items: center; gap: 7px; }
|
||||
.workspace { min-width: 0; display: flex; flex-direction: column; gap: 12px; }
|
||||
.canvas-wrap { position: relative; min-height: 420px; overflow: hidden; background: #09111c; }
|
||||
canvas { display: block; width: 100%; min-height: 420px; }
|
||||
.empty { position: absolute; inset: 0; display: grid; place-items: center; color: #74879d; pointer-events: none; }
|
||||
.legend { position: absolute; right: 16px; bottom: 14px; display: flex; gap: 8px; align-items: center; font-size: 11px; background: #07101dcc; padding: 7px; border-radius: 6px; }
|
||||
.legend i { width: 120px; height: 9px; background: linear-gradient(90deg,#ec402f,#f3e33a,#43d35c,#1fc9d4,#1848ad); border-radius: 5px; }
|
||||
.summary { display: flex; gap: 20px; color: #8fa3ba; font-size: 13px; }
|
||||
.status { padding: 7px 11px; border-radius: 20px; background: #28384b; font-size: 12px; }.status.ok { background: #174b36; }.status.bad { background: #702d32; }
|
||||
.error { color: #ff9a9f; margin: 0; font-size: 12px; }
|
||||
@media (max-width: 800px) { main { grid-template-columns: 1fr; padding: 12px; } header { padding: 18px 14px 5px; } .canvas-wrap, canvas { min-height: 420px; } }
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
const state = { points: [], bounds: null };
|
||||
const $ = id => document.getElementById(id);
|
||||
const canvas = $('heatmap');
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
function initializeDates() {
|
||||
const dateTo = new Date();
|
||||
const rangeMinutes = Number(document.body.dataset.defaultDateRange) || 60;
|
||||
const dateFrom = new Date(dateTo.getTime() - rangeMinutes * 60_000);
|
||||
$('date-from').value = localDateTimeValue(dateFrom);
|
||||
$('date-to').value = localDateTimeValue(dateTo);
|
||||
}
|
||||
|
||||
async function loadBssids() {
|
||||
const response = await fetch('/api/bssids');
|
||||
if (!response.ok) throw new Error('Не удалось загрузить список BSSID');
|
||||
const items = await response.json();
|
||||
$('bssid-list').innerHTML = items.map(item =>
|
||||
`<label><input type="checkbox" value="${item.id}"> ${escapeHtml(item.bssid)} <small>(${item.samples})</small></label>`
|
||||
).join('') || 'BSSID пока отсутствуют';
|
||||
}
|
||||
|
||||
async function loadHeatmap() {
|
||||
const dateFrom = new Date($('date-from').value);
|
||||
const dateTo = new Date($('date-to').value);
|
||||
if (Number.isNaN(dateFrom.getTime()) || Number.isNaN(dateTo.getTime())) {
|
||||
showError('Укажите дату и время начала и окончания периода');
|
||||
return;
|
||||
}
|
||||
const params = new URLSearchParams({from: dateFrom.toISOString(), to: dateTo.toISOString()});
|
||||
document.querySelectorAll('#bssid-list input:checked').forEach(input => params.append('bssid', input.value));
|
||||
try {
|
||||
const response = await fetch('/api/heatmap?' + params);
|
||||
const payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error || 'Ошибка загрузки данных');
|
||||
state.points = payload.points;
|
||||
state.bounds = payload.bounds;
|
||||
$('selected-period').textContent = `${dateFrom.toLocaleString()} — ${dateTo.toLocaleString()}`;
|
||||
setStatus('Подключено', true);
|
||||
showError('');
|
||||
draw();
|
||||
} catch (error) {
|
||||
setStatus('Нет связи', false);
|
||||
showError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function draw() {
|
||||
resizeCanvas();
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
const points = state.points;
|
||||
$('empty').hidden = Boolean(points.length);
|
||||
if (!points.length || !state.bounds) {
|
||||
$('points-count').textContent = '0 точек';
|
||||
$('samples-count').textContent = '0 измерений';
|
||||
return;
|
||||
}
|
||||
const {min_x: minX, max_x: maxX, min_y: minY, max_y: maxY} = state.bounds;
|
||||
const padding = 55, width = canvas.width - padding * 2, height = canvas.height - padding * 2;
|
||||
const rangeX = maxX - minX + 1, rangeY = maxY - minY + 1;
|
||||
const cellSize = Math.min(width / rangeX, height / rangeY);
|
||||
const plotWidth = cellSize * rangeX, plotHeight = cellSize * rangeY;
|
||||
const originX = padding + (width - plotWidth) / 2;
|
||||
const originY = padding + (height - plotHeight) / 2;
|
||||
drawGrid(minX, maxX + 1, minY, maxY + 1, originX, originY, plotWidth, plotHeight);
|
||||
ctx.save();
|
||||
points.forEach(point => {
|
||||
const x = originX + (point.x - minX) * cellSize;
|
||||
const y = originY + (maxY - point.y) * cellSize;
|
||||
const strength = Math.max(.05, Math.min(1, (point.signal + 100) / 70));
|
||||
ctx.fillStyle = heatColor(strength);
|
||||
ctx.fillRect(x, y, Math.max(1, cellSize), Math.max(1, cellSize));
|
||||
if (cellSize >= 5) {
|
||||
ctx.strokeStyle = '#07101d66';
|
||||
ctx.strokeRect(x, y, cellSize, cellSize);
|
||||
}
|
||||
});
|
||||
ctx.restore();
|
||||
$('points-count').textContent = `${points.length} точек`;
|
||||
$('samples-count').textContent = `${points.reduce((sum, point) => sum + point.samples, 0)} измерений`;
|
||||
}
|
||||
|
||||
function drawGrid(minX, maxX, minY, maxY, originX, originY, width, height) {
|
||||
ctx.strokeStyle = '#1d3045'; ctx.fillStyle = '#688097'; ctx.font = '11px system-ui'; ctx.lineWidth = 1;
|
||||
for (let i = 0; i <= 5; i++) {
|
||||
const x = originX + width * i / 5, y = originY + height * i / 5;
|
||||
ctx.beginPath(); ctx.moveTo(x, originY); ctx.lineTo(x, originY + height); ctx.stroke();
|
||||
ctx.beginPath(); ctx.moveTo(originX, y); ctx.lineTo(originX + width, y); ctx.stroke();
|
||||
ctx.fillText((minX + (maxX - minX) * i / 5).toFixed(0), x - 8, originY + height + 20);
|
||||
ctx.fillText((maxY - (maxY - minY) * i / 5).toFixed(0), originX - 38, y + 4);
|
||||
}
|
||||
}
|
||||
|
||||
function heatColor(value) {
|
||||
const stops = [[236,64,47],[243,227,58],[67,211,92],[31,201,212],[24,72,173]];
|
||||
const scaled = value * (stops.length - 1), index = Math.min(stops.length - 2, Math.floor(scaled)), mix = scaled - index;
|
||||
const rgb = stops[index].map((component, i) => Math.round(component + (stops[index + 1][i] - component) * mix));
|
||||
return `rgba(${rgb.join(',')},1)`;
|
||||
}
|
||||
|
||||
function resizeCanvas() {
|
||||
const containerWidth = canvas.parentElement.clientWidth;
|
||||
const horizontalPadding = 110;
|
||||
let height = 560;
|
||||
if (state.bounds) {
|
||||
const cellsX = state.bounds.max_x - state.bounds.min_x + 1;
|
||||
const cellsY = state.bounds.max_y - state.bounds.min_y + 1;
|
||||
height = Math.round(Math.max(1, containerWidth - horizontalPadding) * cellsY / cellsX + horizontalPadding);
|
||||
height = Math.max(420, Math.min(900, height));
|
||||
}
|
||||
canvas.style.height = `${height}px`;
|
||||
canvas.width = Math.round(containerWidth);
|
||||
canvas.height = height;
|
||||
}
|
||||
|
||||
function localDateTimeValue(date) {
|
||||
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
|
||||
return local.toISOString().slice(0, 19);
|
||||
}
|
||||
function setStatus(text, ok) { $('connection-status').textContent = text; $('connection-status').className = `status ${ok ? 'ok' : 'bad'}`; }
|
||||
function showError(text) { $('error').textContent = text; $('error').hidden = !text; }
|
||||
function escapeHtml(value) { const node = document.createElement('span'); node.textContent = value; return node.innerHTML; }
|
||||
|
||||
$('apply').addEventListener('click', loadHeatmap);
|
||||
$('select-all').addEventListener('click', () => document.querySelectorAll('#bssid-list input').forEach(input => input.checked = true));
|
||||
$('select-none').addEventListener('click', () => document.querySelectorAll('#bssid-list input').forEach(input => input.checked = false));
|
||||
window.addEventListener('resize', draw);
|
||||
initializeDates();
|
||||
Promise.all([loadBssids(), loadHeatmap()]).catch(error => { setStatus('Нет связи', false); showError(error.message); });
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Wi-Fi — тепловая карта</title>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='dashboard.css') }}">
|
||||
</head>
|
||||
<body data-default-date-range="{{ default_date_range }}">
|
||||
<header>
|
||||
<div>
|
||||
<h1>Тепловая карта Wi-Fi</h1>
|
||||
<p>Максимальный уровень сигнала в локальных координатах</p>
|
||||
</div>
|
||||
<span id="connection-status" class="status">Загрузка…</span>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<aside class="panel controls">
|
||||
<label>Дата и время с
|
||||
<div class="input-row"><input id="date-from" type="datetime-local" step="1"></div>
|
||||
</label>
|
||||
<label>Дата и время по
|
||||
<div class="input-row"><input id="date-to" type="datetime-local" step="1"></div>
|
||||
</label>
|
||||
<fieldset>
|
||||
<legend>BSSID</legend>
|
||||
<div class="filter-actions"><button id="select-all" type="button">Все</button><button id="select-none" type="button">Сбросить</button></div>
|
||||
<div id="bssid-list" class="bssid-list">Загрузка…</div>
|
||||
</fieldset>
|
||||
<button id="apply" class="primary" type="button">Применить</button>
|
||||
<p id="error" class="error" hidden></p>
|
||||
</aside>
|
||||
|
||||
<section class="workspace">
|
||||
<div class="panel canvas-wrap">
|
||||
<canvas id="heatmap"></canvas>
|
||||
<div id="empty" class="empty">За выбранный период данных нет</div>
|
||||
<div class="legend"><span>−100 dBm</span><i></i><span>−30 dBm</span></div>
|
||||
</div>
|
||||
<div class="summary">
|
||||
<span id="selected-period">Период не выбран</span>
|
||||
<span id="points-count">0 точек</span>
|
||||
<span id="samples-count">0 измерений</span>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script src="{{ url_for('static', filename='dashboard.js') }}"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
{
|
||||
"data": {
|
||||
"schema_version": "1.1",
|
||||
"message_id": "3055aed4-9114-418f-b59b-6858d6541dd4",
|
||||
"message_kind": "scan_results",
|
||||
"agent_id": "h1500-09-01-00024",
|
||||
"robot_id": "h1500",
|
||||
"platform": "linux",
|
||||
"observed_at_unix_ms": 1788013132615,
|
||||
"sent_at_unix_ms": 1788013132620,
|
||||
"payload": {
|
||||
"scan_results": [
|
||||
{
|
||||
"bssid": "48:2f:6b:7a:b4:90(on",
|
||||
"frequency": "5300",
|
||||
"signal_level": "-81",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "f0:61:c0:85:a2:f0(on",
|
||||
"frequency": "5320",
|
||||
"signal_level": "-76",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:7a:a7:50(on",
|
||||
"frequency": "5660",
|
||||
"signal_level": "-79",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:7b:be:b0(on",
|
||||
"frequency": "5220",
|
||||
"signal_level": "-81",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:7a:bd:f0(on",
|
||||
"frequency": "5805",
|
||||
"signal_level": "-79",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:7b:03:b0(on",
|
||||
"frequency": "5805",
|
||||
"signal_level": "-80",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:79:05:c0(on",
|
||||
"frequency": "2432",
|
||||
"signal_level": "-66",
|
||||
"ssid": "vost-serv-new"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:7a:47:40(on",
|
||||
"frequency": "2472",
|
||||
"signal_level": "-78",
|
||||
"ssid": "vost-serv-new"
|
||||
},
|
||||
{
|
||||
"bssid": "dc:b7:ac:0d:04:c0(on",
|
||||
"frequency": "2472",
|
||||
"signal_level": "-85",
|
||||
"ssid": "vost-serv-new"
|
||||
},
|
||||
{
|
||||
"bssid": "94:64:24:6c:2a:91(on",
|
||||
"frequency": "5200",
|
||||
"signal_level": "-77",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:79:05:d0(on",
|
||||
"frequency": "5280",
|
||||
"signal_level": "-72",
|
||||
"ssid": "vost-serv-new"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:79:05:d1(on",
|
||||
"frequency": "5280",
|
||||
"signal_level": "-73",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "94:64:24:6c:a7:f0(on",
|
||||
"frequency": "5320",
|
||||
"signal_level": "-77",
|
||||
"ssid": "vost-serv-new"
|
||||
},
|
||||
{
|
||||
"bssid": "94:64:24:6c:a7:f1(on",
|
||||
"frequency": "5320",
|
||||
"signal_level": "-77",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "94:64:24:67:36:90(on",
|
||||
"frequency": "5680",
|
||||
"signal_level": "-78",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:78:f4:50(on",
|
||||
"frequency": "5700",
|
||||
"signal_level": "-78",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "94:64:24:6b:c2:b0(on",
|
||||
"frequency": "5720",
|
||||
"signal_level": "-79",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "94:64:24:67:4e:10(on",
|
||||
"frequency": "5720",
|
||||
"signal_level": "-64",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "94:64:24:67:60:30(on",
|
||||
"frequency": "5765",
|
||||
"signal_level": "-78",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
},
|
||||
{
|
||||
"bssid": "48:2f:6b:7b:0b:30(on",
|
||||
"frequency": "5825",
|
||||
"signal_level": "-74",
|
||||
"ssid": "RONAVI_MCNS5"
|
||||
}
|
||||
],
|
||||
"location": {
|
||||
"x": -73.2,
|
||||
"y": 59.4
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import unittest
|
||||
|
||||
from web_app import create_app, parse_bssid_ids
|
||||
|
||||
|
||||
class WebAppTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
app = create_app()
|
||||
app.config["TESTING"] = True
|
||||
self.client = app.test_client()
|
||||
|
||||
def test_dashboard_is_available_without_database_query(self):
|
||||
response = self.client.get("/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn("Тепловая карта".encode(), response.data)
|
||||
self.assertIn("Дата и время с".encode(), response.data)
|
||||
self.assertIn("Дата и время по".encode(), response.data)
|
||||
|
||||
def test_rejects_invalid_period_before_database_query(self):
|
||||
response = self.client.get(
|
||||
"/api/heatmap",
|
||||
query_string={
|
||||
"from": "2026-08-29T12:00:00+05:00",
|
||||
"to": "2026-08-29T11:00:00+05:00",
|
||||
},
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn("earlier than", response.get_json()["error"])
|
||||
|
||||
def test_parses_unique_bssid_filters(self):
|
||||
self.assertEqual(parse_bssid_ids(["1,2", "2", "3"]), [1, 2, 3])
|
||||
|
||||
def test_rejects_invalid_bssid_filter(self):
|
||||
with self.assertRaises(ValueError):
|
||||
parse_bssid_ids(["not-an-id"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import json
|
||||
import unittest
|
||||
|
||||
from settings import SETTINGS
|
||||
from wifi_spool import SCHEMA, mosquitto_command, parse_message
|
||||
|
||||
|
||||
class WifiSpoolTest(unittest.TestCase):
|
||||
def test_filters_and_normalizes_scan_results(self):
|
||||
data = {
|
||||
"message_kind": "scan_results",
|
||||
"agent_id": "agent-1",
|
||||
"payload": {
|
||||
"location": {"x": -110.2, "y": 93.7},
|
||||
"scan_results": [
|
||||
{"bssid": "aa:bb", "signal_level": "-67", "ssid": "RONAVI_MCNS5"},
|
||||
{"bssid": "cc:dd", "signal_level": "-71", "ssid": "OTHER"},
|
||||
],
|
||||
},
|
||||
}
|
||||
line = "wifi/vostok/44/scan_results " + json.dumps({"data": json.dumps(data)})
|
||||
|
||||
results = parse_message(line, SETTINGS.target_ssid)
|
||||
self.assertEqual(len(results), 1)
|
||||
self.assertEqual((results[0].location_x, results[0].location_y), (-110, 94))
|
||||
self.assertEqual(results[0].signal_level, -67)
|
||||
self.assertEqual(results[0].agent_id, "agent-1")
|
||||
|
||||
def test_ignores_other_message_kind(self):
|
||||
line = 'topic {"message_kind":"heartbeat"}'
|
||||
self.assertEqual(parse_message(line, SETTINGS.target_ssid), [])
|
||||
|
||||
def test_schema_contains_collection_timestamp(self):
|
||||
self.assertIn("collected_at TIMESTAMPTZ", SCHEMA)
|
||||
self.assertIn("DEFAULT CURRENT_TIMESTAMP", SCHEMA)
|
||||
|
||||
def test_schema_normalizes_agents(self):
|
||||
self.assertIn("CREATE TABLE IF NOT EXISTS agents", SCHEMA)
|
||||
self.assertIn("agent_id BIGINT NOT NULL", SCHEMA)
|
||||
self.assertIn("FOREIGN KEY (agent_id) REFERENCES agents(id)", SCHEMA)
|
||||
|
||||
def test_mqtt_command_uses_keepalive(self):
|
||||
command = mosquitto_command(SETTINGS)
|
||||
keepalive_index = command.index("-k")
|
||||
self.assertEqual(
|
||||
command[keepalive_index + 1], str(SETTINGS.mqtt_keepalive_seconds)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,160 @@
|
|||
"""Web dashboard for dynamic Wi-Fi signal heatmaps."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import psycopg
|
||||
from flask import Flask, jsonify, render_template, request
|
||||
|
||||
from settings import SETTINGS, Settings
|
||||
|
||||
MAX_BSSID_FILTERS = 100
|
||||
|
||||
|
||||
def create_app(settings: Settings = SETTINGS) -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.config["WIFI_SETTINGS"] = settings
|
||||
|
||||
@app.get("/")
|
||||
def dashboard() -> str:
|
||||
return render_template(
|
||||
"dashboard.html",
|
||||
default_date_range=settings.web_default_date_range_minutes,
|
||||
)
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
try:
|
||||
with connect(settings) as connection:
|
||||
connection.execute("SELECT 1").fetchone()
|
||||
return jsonify(status="ok")
|
||||
except psycopg.Error:
|
||||
return jsonify(status="error", database="unavailable"), 503
|
||||
|
||||
@app.get("/api/bssids")
|
||||
def bssids():
|
||||
with connect(settings) as connection:
|
||||
rows = connection.execute(
|
||||
"""SELECT b.id, b.bssid, COUNT(s.id) AS samples
|
||||
FROM bssids AS b
|
||||
LEFT JOIN scan_results AS s ON s.bssid_id = b.id
|
||||
GROUP BY b.id, b.bssid
|
||||
ORDER BY b.bssid"""
|
||||
).fetchall()
|
||||
return jsonify(
|
||||
[{"id": row[0], "bssid": row[1], "samples": row[2]} for row in rows]
|
||||
)
|
||||
|
||||
@app.get("/api/heatmap")
|
||||
def heatmap():
|
||||
try:
|
||||
date_from = datetime_parameter("from")
|
||||
date_to = datetime_parameter("to")
|
||||
if date_from >= date_to:
|
||||
raise ValueError("from must be earlier than to")
|
||||
bssid_ids = parse_bssid_ids(request.args.getlist("bssid"))
|
||||
except ValueError as error:
|
||||
return jsonify(error=str(error)), 400
|
||||
|
||||
where_filter = ""
|
||||
parameters: list[Any] = [date_from, date_to]
|
||||
if bssid_ids:
|
||||
where_filter = "AND scan.bssid_id = ANY(%s)"
|
||||
parameters.append(bssid_ids)
|
||||
|
||||
query = f"""
|
||||
SELECT
|
||||
scan.location_x,
|
||||
scan.location_y,
|
||||
MAX(scan.signal_level) AS maximum_signal,
|
||||
COUNT(*) AS samples
|
||||
FROM scan_results AS scan
|
||||
WHERE scan.collected_at >= %s
|
||||
AND scan.collected_at <= %s
|
||||
{where_filter}
|
||||
GROUP BY scan.location_x, scan.location_y
|
||||
ORDER BY scan.location_x, scan.location_y
|
||||
"""
|
||||
with connect(settings) as connection:
|
||||
rows = connection.execute(query, parameters).fetchall()
|
||||
|
||||
points: list[dict[str, Any]] = []
|
||||
bounds = None
|
||||
for x, y, signal, samples in rows:
|
||||
points.append(
|
||||
{"x": x, "y": y, "signal": float(signal), "samples": samples}
|
||||
)
|
||||
if bounds is None:
|
||||
bounds = {"min_x": x, "max_x": x, "min_y": y, "max_y": y}
|
||||
else:
|
||||
bounds["min_x"] = min(bounds["min_x"], x)
|
||||
bounds["max_x"] = max(bounds["max_x"], x)
|
||||
bounds["min_y"] = min(bounds["min_y"], y)
|
||||
bounds["max_y"] = max(bounds["max_y"], y)
|
||||
return jsonify(
|
||||
date_from=date_from.isoformat(),
|
||||
date_to=date_to.isoformat(),
|
||||
bssid_ids=bssid_ids,
|
||||
bounds=bounds,
|
||||
points=points,
|
||||
)
|
||||
|
||||
@app.errorhandler(psycopg.Error)
|
||||
def database_error(_error: psycopg.Error):
|
||||
app.logger.exception("PostgreSQL request failed")
|
||||
return jsonify(error="database is temporarily unavailable"), 503
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def connect(settings: Settings):
|
||||
return psycopg.connect(
|
||||
host=settings.postgres_host,
|
||||
port=settings.postgres_port,
|
||||
dbname=settings.postgres_database,
|
||||
user=settings.postgres_user,
|
||||
password=settings.postgres_password,
|
||||
connect_timeout=settings.postgres_connect_timeout,
|
||||
)
|
||||
|
||||
|
||||
def datetime_parameter(name: str) -> datetime:
|
||||
raw_value = request.args.get(name)
|
||||
if not raw_value:
|
||||
raise ValueError(f"{name} is required")
|
||||
try:
|
||||
value = datetime.fromisoformat(raw_value.replace("Z", "+00:00"))
|
||||
except ValueError as error:
|
||||
raise ValueError(f"{name} must be an ISO 8601 date and time") from error
|
||||
if value.tzinfo is None:
|
||||
raise ValueError(f"{name} must include a timezone")
|
||||
return value
|
||||
|
||||
|
||||
def parse_bssid_ids(raw_values: Sequence[str]) -> list[int]:
|
||||
values: list[int] = []
|
||||
for raw_value in raw_values:
|
||||
for item in raw_value.split(","):
|
||||
if not item:
|
||||
continue
|
||||
try:
|
||||
value = int(item)
|
||||
except ValueError as error:
|
||||
raise ValueError("bssid values must be integer ids") from error
|
||||
if value <= 0:
|
||||
raise ValueError("bssid values must be positive")
|
||||
if value not in values:
|
||||
values.append(value)
|
||||
if len(values) > MAX_BSSID_FILTERS:
|
||||
raise ValueError(f"no more than {MAX_BSSID_FILTERS} BSSID filters are allowed")
|
||||
return values
|
||||
|
||||
|
||||
app = create_app()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host=SETTINGS.web_host, port=SETTINGS.web_port)
|
||||
|
|
@ -0,0 +1,274 @@
|
|||
"""Collect selected Wi-Fi scan results from mosquitto_sub into PostgreSQL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import subprocess
|
||||
from collections.abc import Iterable, Iterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from settings import SETTINGS, Settings
|
||||
|
||||
LOGGER = logging.getLogger("wifi_spool")
|
||||
|
||||
SCHEMA_STATEMENTS = (
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS bssids (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
bssid TEXT NOT NULL UNIQUE
|
||||
)
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS agents (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
agent_name TEXT NOT NULL UNIQUE
|
||||
)
|
||||
""",
|
||||
"""
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scan_results (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
bssid_id BIGINT NOT NULL,
|
||||
location_x INTEGER NOT NULL,
|
||||
location_y INTEGER NOT NULL,
|
||||
signal_level INTEGER NOT NULL,
|
||||
agent_id BIGINT NOT NULL,
|
||||
collected_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (bssid_id) REFERENCES bssids(id),
|
||||
FOREIGN KEY (agent_id) REFERENCES agents(id)
|
||||
)
|
||||
""",
|
||||
"""
|
||||
|
||||
ALTER TABLE scan_results
|
||||
ADD COLUMN IF NOT EXISTS collected_at TIMESTAMPTZ
|
||||
NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
""",
|
||||
"""
|
||||
DO $$
|
||||
DECLARE
|
||||
current_agent_type TEXT;
|
||||
BEGIN
|
||||
SELECT data_type INTO current_agent_type
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = current_schema()
|
||||
AND table_name = 'scan_results'
|
||||
AND column_name = 'agent_id';
|
||||
|
||||
IF current_agent_type IN ('text', 'character varying') THEN
|
||||
INSERT INTO agents (agent_name)
|
||||
SELECT DISTINCT agent_id::TEXT FROM scan_results
|
||||
ON CONFLICT (agent_name) DO NOTHING;
|
||||
|
||||
ALTER TABLE scan_results
|
||||
ADD COLUMN agent_ref_id BIGINT REFERENCES agents(id);
|
||||
UPDATE scan_results AS scan
|
||||
SET agent_ref_id = agent.id
|
||||
FROM agents AS agent
|
||||
WHERE agent.agent_name = scan.agent_id::TEXT;
|
||||
ALTER TABLE scan_results ALTER COLUMN agent_ref_id SET NOT NULL;
|
||||
ALTER TABLE scan_results DROP COLUMN agent_id;
|
||||
ALTER TABLE scan_results RENAME COLUMN agent_ref_id TO agent_id;
|
||||
END IF;
|
||||
END $$
|
||||
""",
|
||||
"""
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_scan_results_bssid_id
|
||||
ON scan_results(bssid_id)
|
||||
""",
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_scan_results_agent_id
|
||||
ON scan_results(agent_id)
|
||||
""",
|
||||
)
|
||||
|
||||
SCHEMA = "\n;\n".join(statement.strip() for statement in SCHEMA_STATEMENTS)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScanResult:
|
||||
bssid: str
|
||||
location_x: int
|
||||
location_y: int
|
||||
signal_level: int
|
||||
agent_id: str
|
||||
|
||||
|
||||
def _integer_location(value: Any) -> int:
|
||||
"""Convert a numeric coordinate to the nearest integer."""
|
||||
if isinstance(value, bool):
|
||||
raise ValueError("boolean is not a coordinate")
|
||||
return round(float(value))
|
||||
|
||||
|
||||
def parse_message(line: str, target_ssid: str) -> list[ScanResult]:
|
||||
"""Parse one `mosquitto_sub -v` line and return matching scan rows."""
|
||||
try:
|
||||
_topic, raw_message = line.strip().split(maxsplit=1)
|
||||
envelope = json.loads(raw_message)
|
||||
data = envelope.get("data", envelope)
|
||||
if isinstance(data, str):
|
||||
data = json.loads(data)
|
||||
if data.get("message_kind") != "scan_results":
|
||||
return []
|
||||
|
||||
payload = data["payload"]
|
||||
location = payload["location"]
|
||||
agent_id = str(data["agent_id"])
|
||||
location_x = _integer_location(location["x"])
|
||||
location_y = _integer_location(location["y"])
|
||||
except (AttributeError, KeyError, TypeError, ValueError, json.JSONDecodeError) as error:
|
||||
raise ValueError(f"invalid MQTT message: {error}") from error
|
||||
|
||||
results: list[ScanResult] = []
|
||||
for item in payload.get("scan_results", []):
|
||||
if item.get("ssid") != target_ssid:
|
||||
continue
|
||||
try:
|
||||
results.append(
|
||||
ScanResult(
|
||||
bssid=str(item["bssid"]),
|
||||
location_x=location_x,
|
||||
location_y=location_y,
|
||||
signal_level=int(item["signal_level"]),
|
||||
agent_id=agent_id,
|
||||
)
|
||||
)
|
||||
except (KeyError, TypeError, ValueError) as error:
|
||||
LOGGER.warning("Skipping malformed scan result: %s", error)
|
||||
return results
|
||||
|
||||
|
||||
class Repository:
|
||||
def __init__(self, settings: Settings, connection: Any = None) -> None:
|
||||
if connection is None:
|
||||
try:
|
||||
import psycopg
|
||||
except ImportError as error:
|
||||
raise RuntimeError(
|
||||
"PostgreSQL driver is not installed; run: "
|
||||
"python3 -m pip install -r requirements.txt"
|
||||
) from error
|
||||
connection = psycopg.connect(
|
||||
host=settings.postgres_host,
|
||||
port=settings.postgres_port,
|
||||
dbname=settings.postgres_database,
|
||||
user=settings.postgres_user,
|
||||
password=settings.postgres_password,
|
||||
connect_timeout=settings.postgres_connect_timeout,
|
||||
)
|
||||
self.connection = connection
|
||||
with self.connection.transaction():
|
||||
for statement in SCHEMA_STATEMENTS:
|
||||
self.connection.execute(statement)
|
||||
|
||||
def close(self) -> None:
|
||||
self.connection.close()
|
||||
|
||||
def save(self, results: Iterable[ScanResult]) -> int:
|
||||
saved = 0
|
||||
with self.connection.transaction():
|
||||
for result in results:
|
||||
bssid_row = self.connection.execute(
|
||||
"""INSERT INTO bssids (bssid) VALUES (%s)
|
||||
ON CONFLICT (bssid) DO UPDATE SET bssid = EXCLUDED.bssid
|
||||
RETURNING id""",
|
||||
(result.bssid,),
|
||||
).fetchone()
|
||||
if bssid_row is None: # pragma: no cover - database invariant
|
||||
raise RuntimeError("failed to resolve bssid id")
|
||||
agent_row = self.connection.execute(
|
||||
"""INSERT INTO agents (agent_name) VALUES (%s)
|
||||
ON CONFLICT (agent_name)
|
||||
DO UPDATE SET agent_name = EXCLUDED.agent_name
|
||||
RETURNING id""",
|
||||
(result.agent_id,),
|
||||
).fetchone()
|
||||
if agent_row is None: # pragma: no cover - database invariant
|
||||
raise RuntimeError("failed to resolve agent id")
|
||||
self.connection.execute(
|
||||
"""INSERT INTO scan_results
|
||||
(bssid_id, location_x, location_y, signal_level, agent_id)
|
||||
VALUES (%s, %s, %s, %s, %s)""",
|
||||
(
|
||||
bssid_row[0],
|
||||
result.location_x,
|
||||
result.location_y,
|
||||
result.signal_level,
|
||||
agent_row[0],
|
||||
),
|
||||
)
|
||||
saved += 1
|
||||
return saved
|
||||
|
||||
|
||||
def mosquitto_command(settings: Settings) -> list[str]:
|
||||
return [
|
||||
settings.mosquitto_sub_bin,
|
||||
"-h", settings.mqtt_host,
|
||||
"-p", str(settings.mqtt_port),
|
||||
"-k", str(settings.mqtt_keepalive_seconds),
|
||||
"-t", settings.mqtt_topic,
|
||||
"-u", settings.mqtt_username,
|
||||
"-P", settings.mqtt_password,
|
||||
"-v",
|
||||
]
|
||||
|
||||
|
||||
def collect(lines: Iterable[str], repository: Repository, settings: Settings) -> None:
|
||||
for line in lines:
|
||||
try:
|
||||
saved = repository.save(parse_message(line, settings.target_ssid))
|
||||
if saved:
|
||||
LOGGER.info("Saved %d scan result(s)", saved)
|
||||
except ValueError as error:
|
||||
LOGGER.warning("Skipping message: %s", error)
|
||||
|
||||
|
||||
def subscribe(settings: Settings) -> Iterator[str]:
|
||||
command = mosquitto_command(settings)
|
||||
LOGGER.info("Subscribing to %s on %s", settings.mqtt_topic, settings.mqtt_host)
|
||||
with subprocess.Popen(
|
||||
command,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=None,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
) as process:
|
||||
if process.stdout is None: # pragma: no cover - defensive check
|
||||
raise RuntimeError("mosquitto_sub stdout is unavailable")
|
||||
yield from process.stdout
|
||||
if process.returncode not in (None, 0):
|
||||
raise RuntimeError(f"mosquitto_sub exited with code {process.returncode}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--stdin",
|
||||
action="store_true",
|
||||
help="read mosquitto_sub formatted messages from stdin",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
|
||||
repository = Repository(SETTINGS)
|
||||
try:
|
||||
if args.stdin:
|
||||
import sys
|
||||
|
||||
collect(sys.stdin, repository, SETTINGS)
|
||||
else:
|
||||
collect(subscribe(SETTINGS), repository, SETTINGS)
|
||||
except KeyboardInterrupt:
|
||||
LOGGER.info("Stopped")
|
||||
finally:
|
||||
repository.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in New Issue