Release WiFi GPS Mapper v2.3.0
This commit is contained in:
+2
-2
@@ -60,7 +60,7 @@ wifi-gps-mapper-releases-build/
|
|||||||
Перед установкой необходимо:
|
Перед установкой необходимо:
|
||||||
|
|
||||||
1. Подготовить компьютер под управлением Debian/Linux.
|
1. Подготовить компьютер под управлением Debian/Linux.
|
||||||
2. Скопировать на него релизную сборку WiFi GPS Mapper.
|
2. Клонировать на него релизную сборку WiFi GPS Mapper.
|
||||||
3. Убедиться, что пользователь имеет права на запись в каталог проекта.
|
3. Убедиться, что пользователь имеет права на запись в каталог проекта.
|
||||||
4. Обеспечить подключение к интернету для загрузки недостающих зависимостей и данных.
|
4. Обеспечить подключение к интернету для загрузки недостающих зависимостей и данных.
|
||||||
5. Убедиться в наличии Python 3 и возможности создания виртуального окружения.
|
5. Убедиться в наличии Python 3 и возможности создания виртуального окружения.
|
||||||
@@ -78,7 +78,7 @@ wifi-gps-mapper-releases-build/
|
|||||||
Перейдите в каталог релизной сборки:
|
Перейдите в каталог релизной сборки:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd ~/Projects/wifi-gps-mapper-releases-build
|
cd ~/Projects/wifi-gps-mapper-releases
|
||||||
```
|
```
|
||||||
|
|
||||||
Запустите установщик:
|
Запустите установщик:
|
||||||
|
|||||||
+632
-166
@@ -78,10 +78,15 @@ from reports.vendors import render_vendors_page
|
|||||||
from vendor_service import VendorService
|
from vendor_service import VendorService
|
||||||
from sudo import SudoChecker
|
from sudo import SudoChecker
|
||||||
from config import Config
|
from config import Config
|
||||||
|
from database import Database
|
||||||
|
from parser import CaptureParser
|
||||||
|
from session import Session
|
||||||
|
from reports.recovery import CAPTURES_DIR, _has_recoverable_capture
|
||||||
from gps_test import GPSTestService
|
from gps_test import GPSTestService
|
||||||
from auto_gps import AutoGPSService
|
from auto_gps import AutoGPSService
|
||||||
from auto_wifi_verification import AutoWiFiVerificationService
|
from auto_wifi_verification import AutoWiFiVerificationService
|
||||||
from wifi_connection import WiFiConnectionError, WiFiConnectionService
|
from wifi_connection import WiFiConnectionError, WiFiConnectionService
|
||||||
|
from gpsrelay_discovery import GPSRelayDiscoveryError, discover_gpsrelay
|
||||||
from gui.timezones import get_timezone_options
|
from gui.timezones import get_timezone_options
|
||||||
from logging_config import (
|
from logging_config import (
|
||||||
LOG_DATE_FORMAT,
|
LOG_DATE_FORMAT,
|
||||||
@@ -273,6 +278,8 @@ def scanner_navigation_guard():
|
|||||||
"api_wifi_verification_stop",
|
"api_wifi_verification_stop",
|
||||||
"api_wifi_verification_settings",
|
"api_wifi_verification_settings",
|
||||||
"api_wifi_verification_settings_save",
|
"api_wifi_verification_settings_save",
|
||||||
|
"api_wifi_verification_gpsrelay_discovery_start",
|
||||||
|
"api_wifi_verification_gpsrelay_discovery_status",
|
||||||
"api_wifi_verification_radius_apply",
|
"api_wifi_verification_radius_apply",
|
||||||
"static",
|
"static",
|
||||||
}
|
}
|
||||||
@@ -309,6 +316,8 @@ def scanner_navigation_guard():
|
|||||||
"scanner_stop",
|
"scanner_stop",
|
||||||
"api_gps_test",
|
"api_gps_test",
|
||||||
"gps_test_stop",
|
"gps_test_stop",
|
||||||
|
"api_wifi_verification_gpsrelay_discovery_start",
|
||||||
|
"api_wifi_verification_gpsrelay_discovery_status",
|
||||||
"static"
|
"static"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,6 +377,10 @@ auto_wifi_verification_service = None
|
|||||||
|
|
||||||
auto_wifi_verification_lock = threading.Lock()
|
auto_wifi_verification_lock = threading.Lock()
|
||||||
|
|
||||||
|
gpsrelay_discovery_job = None
|
||||||
|
gpsrelay_discovery_thread = None
|
||||||
|
gpsrelay_discovery_lock = threading.Lock()
|
||||||
|
|
||||||
# Shared GPS service for the Auto Verification map and Auto Verification worker.
|
# Shared GPS service for the Auto Verification map and Auto Verification worker.
|
||||||
wifi_verification_shared_gps_service = None
|
wifi_verification_shared_gps_service = None
|
||||||
wifi_verification_shared_gps_lock = threading.RLock()
|
wifi_verification_shared_gps_lock = threading.RLock()
|
||||||
@@ -642,35 +655,14 @@ def _stop_wifi_verification_shared_gps_locked():
|
|||||||
|
|
||||||
def acquire_wifi_verification_network_owner(owner, gps_service):
|
def acquire_wifi_verification_network_owner(owner, gps_service):
|
||||||
|
|
||||||
|
if owner == "MANUAL_WIFI_VERIFY":
|
||||||
|
with scanner_lock:
|
||||||
|
return _acquire_network_owner_locked(owner)
|
||||||
|
|
||||||
if owner != "AUTO_WIFI_VERIFY":
|
if owner != "AUTO_WIFI_VERIFY":
|
||||||
return acquire_network_owner(owner)
|
return acquire_network_owner(owner)
|
||||||
|
|
||||||
with wifi_verification_shared_gps_lock:
|
with wifi_verification_shared_gps_lock:
|
||||||
|
|
||||||
if wifi_verification_map_monitor_enabled:
|
|
||||||
|
|
||||||
thread = gps_service.thread
|
|
||||||
|
|
||||||
if thread is None or not thread.is_alive():
|
|
||||||
return False, (
|
|
||||||
"Map GPS monitor is enabled, "
|
|
||||||
"but its GPS service is not running."
|
|
||||||
)
|
|
||||||
|
|
||||||
with scanner_lock:
|
|
||||||
transferred = _transfer_network_owner_locked(
|
|
||||||
"MAP_GPS_MONITOR",
|
|
||||||
"AUTO_WIFI_VERIFY"
|
|
||||||
)
|
|
||||||
|
|
||||||
if not transferred:
|
|
||||||
return False, (
|
|
||||||
"Unable to transfer network ownership "
|
|
||||||
"from the map GPS monitor."
|
|
||||||
)
|
|
||||||
|
|
||||||
return True, None
|
|
||||||
|
|
||||||
with scanner_lock:
|
with scanner_lock:
|
||||||
acquired, error = _acquire_network_owner_locked(owner)
|
acquired, error = _acquire_network_owner_locked(owner)
|
||||||
|
|
||||||
@@ -678,6 +670,11 @@ def acquire_wifi_verification_network_owner(owner, gps_service):
|
|||||||
return False, error
|
return False, error
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if gps_service is None:
|
||||||
|
raise RuntimeError(
|
||||||
|
"Shared GPS service is not configured."
|
||||||
|
)
|
||||||
|
|
||||||
thread = gps_service.thread
|
thread = gps_service.thread
|
||||||
|
|
||||||
if thread is not None and thread.is_alive():
|
if thread is not None and thread.is_alive():
|
||||||
@@ -710,30 +707,19 @@ def acquire_wifi_verification_network_owner(owner, gps_service):
|
|||||||
|
|
||||||
def release_wifi_verification_network_owner(owner):
|
def release_wifi_verification_network_owner(owner):
|
||||||
|
|
||||||
|
if owner == "MANUAL_WIFI_VERIFY":
|
||||||
|
with scanner_lock:
|
||||||
|
if network_operation_owner == owner:
|
||||||
|
_release_network_owner_locked(owner)
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
if owner != "AUTO_WIFI_VERIFY":
|
if owner != "AUTO_WIFI_VERIFY":
|
||||||
release_network_owner(owner)
|
release_network_owner(owner)
|
||||||
return
|
return
|
||||||
|
|
||||||
with wifi_verification_shared_gps_lock:
|
with wifi_verification_shared_gps_lock:
|
||||||
|
|
||||||
if wifi_verification_map_monitor_enabled:
|
|
||||||
|
|
||||||
with scanner_lock:
|
|
||||||
transferred = _transfer_network_owner_locked(
|
|
||||||
"AUTO_WIFI_VERIFY",
|
|
||||||
"MAP_GPS_MONITOR"
|
|
||||||
)
|
|
||||||
|
|
||||||
if not transferred:
|
|
||||||
logger.warning(
|
|
||||||
"Could not return network ownership "
|
|
||||||
"to the map GPS monitor."
|
|
||||||
)
|
|
||||||
|
|
||||||
return
|
|
||||||
|
|
||||||
with scanner_lock:
|
with scanner_lock:
|
||||||
|
|
||||||
current_owner = network_operation_owner
|
current_owner = network_operation_owner
|
||||||
|
|
||||||
if current_owner == owner:
|
if current_owner == owner:
|
||||||
@@ -742,7 +728,8 @@ def release_wifi_verification_network_owner(owner):
|
|||||||
elif current_owner is not None:
|
elif current_owner is not None:
|
||||||
return
|
return
|
||||||
|
|
||||||
_stop_wifi_verification_shared_gps_locked()
|
if not wifi_verification_map_monitor_enabled:
|
||||||
|
_stop_wifi_verification_shared_gps_locked()
|
||||||
|
|
||||||
|
|
||||||
def network_actions_busy():
|
def network_actions_busy():
|
||||||
@@ -2388,6 +2375,261 @@ def reports_trips():
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route(
|
||||||
|
"/reports/recovery/<directory_name>",
|
||||||
|
methods=["POST"]
|
||||||
|
)
|
||||||
|
def reports_recovery_restore(directory_name):
|
||||||
|
|
||||||
|
captures_root = Path(
|
||||||
|
CAPTURES_DIR
|
||||||
|
).resolve()
|
||||||
|
|
||||||
|
session_path = (
|
||||||
|
captures_root / directory_name
|
||||||
|
).resolve()
|
||||||
|
|
||||||
|
if session_path.parent != captures_root:
|
||||||
|
abort(400)
|
||||||
|
|
||||||
|
if not session_path.is_dir():
|
||||||
|
abort(404)
|
||||||
|
|
||||||
|
capture_file = (
|
||||||
|
session_path / "capture.pcapng"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not capture_file.is_file():
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": "Capture file was not found."
|
||||||
|
}
|
||||||
|
), 400
|
||||||
|
|
||||||
|
if capture_file.stat().st_size <= 0:
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": "Capture file is empty."
|
||||||
|
}
|
||||||
|
), 400
|
||||||
|
|
||||||
|
if not _has_recoverable_capture(session_path):
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": (
|
||||||
|
"Capture duration is shorter than "
|
||||||
|
"the required 5 minutes."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
), 400
|
||||||
|
|
||||||
|
acquired, lock_error = acquire_network_owner(
|
||||||
|
"SESSION_RECOVERY"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not acquired:
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": (
|
||||||
|
lock_error
|
||||||
|
or "Network operation is currently busy."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
), 409
|
||||||
|
|
||||||
|
db = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
cfg = Config()
|
||||||
|
|
||||||
|
db = Database(
|
||||||
|
cfg.database
|
||||||
|
)
|
||||||
|
|
||||||
|
existing_sessions = db.conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
capture_file
|
||||||
|
FROM capture_sessions
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
for row in existing_sessions:
|
||||||
|
|
||||||
|
stored_capture_file = row["capture_file"]
|
||||||
|
|
||||||
|
if not stored_capture_file:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if Path(
|
||||||
|
stored_capture_file
|
||||||
|
).resolve() == capture_file.resolve():
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": (
|
||||||
|
"A database record already exists "
|
||||||
|
"for this capture."
|
||||||
|
),
|
||||||
|
"session_id": row["id"],
|
||||||
|
}
|
||||||
|
), 409
|
||||||
|
|
||||||
|
session = Session.from_existing(
|
||||||
|
session_path
|
||||||
|
)
|
||||||
|
|
||||||
|
session_id = db.create_session(
|
||||||
|
str(session.capture_file),
|
||||||
|
start_time=session.start_time
|
||||||
|
)
|
||||||
|
|
||||||
|
session.id = session_id
|
||||||
|
|
||||||
|
parser = CaptureParser(
|
||||||
|
cfg,
|
||||||
|
db
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.parse(
|
||||||
|
session,
|
||||||
|
session_id
|
||||||
|
)
|
||||||
|
|
||||||
|
db.flush_observations()
|
||||||
|
|
||||||
|
event_times = []
|
||||||
|
|
||||||
|
timestamp_sources = (
|
||||||
|
("gps_track", "timestamp"),
|
||||||
|
("access_point_observations", "observed_at"),
|
||||||
|
("handshakes", "captured_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
for table, column in timestamp_sources:
|
||||||
|
|
||||||
|
rows = db.conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT {column}
|
||||||
|
FROM {table}
|
||||||
|
WHERE session_id = ?
|
||||||
|
AND {column} IS NOT NULL
|
||||||
|
""",
|
||||||
|
(session_id,),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
|
||||||
|
try:
|
||||||
|
timestamp = datetime.fromisoformat(
|
||||||
|
str(row[0]).replace("Z", "+00:00")
|
||||||
|
)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if timestamp.tzinfo is None:
|
||||||
|
timestamp = timestamp.replace(
|
||||||
|
tzinfo=timezone.utc
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
timestamp = timestamp.astimezone(
|
||||||
|
timezone.utc
|
||||||
|
)
|
||||||
|
|
||||||
|
event_times.append(timestamp)
|
||||||
|
|
||||||
|
if event_times:
|
||||||
|
|
||||||
|
start_time = min(event_times)
|
||||||
|
|
||||||
|
end_time = max(event_times)
|
||||||
|
|
||||||
|
db.conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE capture_sessions
|
||||||
|
SET start_time = ?,
|
||||||
|
end_time = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
start_time.isoformat().replace("+00:00", "Z"),
|
||||||
|
end_time.isoformat().replace("+00:00", "Z"),
|
||||||
|
session_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
recovered = db.finalize_session(
|
||||||
|
session_id
|
||||||
|
)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
if not recovered:
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": (
|
||||||
|
"Parsing completed, but no GPS positions, "
|
||||||
|
"access points or handshakes were found. "
|
||||||
|
"The empty database record was removed."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
), 422
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Interrupted capture recovered: %s (session_id=%s)",
|
||||||
|
session_path,
|
||||||
|
session_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
return redirect(
|
||||||
|
url_for("reports_trips")
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
|
||||||
|
if db is not None:
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.rollback()
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"Failed to rollback session recovery."
|
||||||
|
)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
db.observation_buffer.clear()
|
||||||
|
|
||||||
|
logger.exception(
|
||||||
|
"Failed to recover interrupted capture: %s",
|
||||||
|
session_path,
|
||||||
|
)
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": "Failed to recover interrupted capture."
|
||||||
|
}
|
||||||
|
), 500
|
||||||
|
|
||||||
|
finally:
|
||||||
|
|
||||||
|
if db is not None:
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.close()
|
||||||
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"Failed to close database after session recovery."
|
||||||
|
)
|
||||||
|
|
||||||
|
release_network_owner(
|
||||||
|
"SESSION_RECOVERY"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/reports/trips/preview")
|
@app.route("/reports/trips/preview")
|
||||||
def reports_trips_preview():
|
def reports_trips_preview():
|
||||||
|
|
||||||
@@ -3183,6 +3425,232 @@ def api_gps_test():
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _run_gpsrelay_discovery(port):
|
||||||
|
global gpsrelay_discovery_job
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = discover_gpsrelay(port)
|
||||||
|
|
||||||
|
with gpsrelay_discovery_lock:
|
||||||
|
gpsrelay_discovery_job = {
|
||||||
|
"state": "SUCCEEDED",
|
||||||
|
"running": False,
|
||||||
|
"port": port,
|
||||||
|
"result": result,
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
except GPSRelayDiscoveryError as error:
|
||||||
|
|
||||||
|
with gpsrelay_discovery_lock:
|
||||||
|
gpsrelay_discovery_job = {
|
||||||
|
"state": "FAILED",
|
||||||
|
"running": False,
|
||||||
|
"port": port,
|
||||||
|
"result": None,
|
||||||
|
"error": str(error),
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
app.logger.exception(
|
||||||
|
"Unexpected GPSRelay discovery error"
|
||||||
|
)
|
||||||
|
|
||||||
|
with gpsrelay_discovery_lock:
|
||||||
|
gpsrelay_discovery_job = {
|
||||||
|
"state": "FAILED",
|
||||||
|
"running": False,
|
||||||
|
"port": port,
|
||||||
|
"result": None,
|
||||||
|
"error": "Unexpected GPSRelay discovery error.",
|
||||||
|
}
|
||||||
|
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
release_network_owner("GPSRELAY_DISCOVERY")
|
||||||
|
except Exception:
|
||||||
|
app.logger.exception(
|
||||||
|
"Could not release GPSRelay discovery network owner"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route(
|
||||||
|
"/api/wifi-verification/gpsrelay-discovery/start",
|
||||||
|
methods=["POST"]
|
||||||
|
)
|
||||||
|
def api_wifi_verification_gpsrelay_discovery_start():
|
||||||
|
global gpsrelay_discovery_job
|
||||||
|
global gpsrelay_discovery_thread
|
||||||
|
|
||||||
|
payload = request.get_json(silent=True)
|
||||||
|
|
||||||
|
if payload is None:
|
||||||
|
payload = {}
|
||||||
|
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": False,
|
||||||
|
"error": "Invalid request body.",
|
||||||
|
}
|
||||||
|
), 400
|
||||||
|
|
||||||
|
raw_port = payload.get("port", 5000)
|
||||||
|
|
||||||
|
if raw_port is None or raw_port == "":
|
||||||
|
raw_port = 5000
|
||||||
|
|
||||||
|
if isinstance(raw_port, bool):
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": False,
|
||||||
|
"error": "Port must be an integer between 1 and 65535.",
|
||||||
|
}
|
||||||
|
), 400
|
||||||
|
|
||||||
|
if isinstance(raw_port, int):
|
||||||
|
port = raw_port
|
||||||
|
elif isinstance(raw_port, str) and raw_port.strip().isdigit():
|
||||||
|
port = int(raw_port.strip())
|
||||||
|
else:
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": False,
|
||||||
|
"error": "Port must be an integer between 1 and 65535.",
|
||||||
|
}
|
||||||
|
), 400
|
||||||
|
|
||||||
|
if not 1 <= port <= 65535:
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": False,
|
||||||
|
"error": "Port must be between 1 and 65535.",
|
||||||
|
}
|
||||||
|
), 400
|
||||||
|
|
||||||
|
start_error = False
|
||||||
|
|
||||||
|
with auto_wifi_verification_lock:
|
||||||
|
|
||||||
|
current = auto_wifi_verification_service
|
||||||
|
|
||||||
|
if (
|
||||||
|
current is not None
|
||||||
|
and current.thread is not None
|
||||||
|
and current.thread.is_alive()
|
||||||
|
):
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": False,
|
||||||
|
"error": "Auto Verification is running.",
|
||||||
|
}
|
||||||
|
), 409
|
||||||
|
|
||||||
|
with gpsrelay_discovery_lock:
|
||||||
|
|
||||||
|
if (
|
||||||
|
gpsrelay_discovery_thread is not None
|
||||||
|
and gpsrelay_discovery_thread.is_alive()
|
||||||
|
):
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": False,
|
||||||
|
"error": "GPSRelay discovery is already running.",
|
||||||
|
}
|
||||||
|
), 409
|
||||||
|
|
||||||
|
acquired, error = acquire_network_owner(
|
||||||
|
"GPSRELAY_DISCOVERY"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not acquired:
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": False,
|
||||||
|
"error": error or "Network interface is busy.",
|
||||||
|
}
|
||||||
|
), 409
|
||||||
|
|
||||||
|
gpsrelay_discovery_job = {
|
||||||
|
"state": "RUNNING",
|
||||||
|
"running": True,
|
||||||
|
"port": port,
|
||||||
|
"result": None,
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
gpsrelay_discovery_thread = threading.Thread(
|
||||||
|
target=_run_gpsrelay_discovery,
|
||||||
|
args=(port,),
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
gpsrelay_discovery_thread.start()
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
app.logger.exception(
|
||||||
|
"Could not start GPSRelay discovery thread"
|
||||||
|
)
|
||||||
|
|
||||||
|
gpsrelay_discovery_thread = None
|
||||||
|
|
||||||
|
gpsrelay_discovery_job = {
|
||||||
|
"state": "FAILED",
|
||||||
|
"running": False,
|
||||||
|
"port": port,
|
||||||
|
"result": None,
|
||||||
|
"error": "Could not start GPSRelay discovery.",
|
||||||
|
}
|
||||||
|
|
||||||
|
start_error = True
|
||||||
|
|
||||||
|
if start_error:
|
||||||
|
release_network_owner("GPSRELAY_DISCOVERY")
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": False,
|
||||||
|
"error": "Could not start GPSRelay discovery.",
|
||||||
|
}
|
||||||
|
), 500
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": True,
|
||||||
|
"state": "RUNNING",
|
||||||
|
"port": port,
|
||||||
|
}
|
||||||
|
), 202
|
||||||
|
|
||||||
|
|
||||||
|
@app.route(
|
||||||
|
"/api/wifi-verification/gpsrelay-discovery/status",
|
||||||
|
methods=["GET"]
|
||||||
|
)
|
||||||
|
def api_wifi_verification_gpsrelay_discovery_status():
|
||||||
|
|
||||||
|
with gpsrelay_discovery_lock:
|
||||||
|
|
||||||
|
if gpsrelay_discovery_job is None:
|
||||||
|
job = {
|
||||||
|
"state": "IDLE",
|
||||||
|
"running": False,
|
||||||
|
"port": None,
|
||||||
|
"result": None,
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
job = dict(gpsrelay_discovery_job)
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"ok": True,
|
||||||
|
**job,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/wifi-verification/settings", methods=["GET"])
|
@app.route("/api/wifi-verification/settings", methods=["GET"])
|
||||||
def api_wifi_verification_settings():
|
def api_wifi_verification_settings():
|
||||||
conn = None
|
conn = None
|
||||||
@@ -3598,7 +4066,6 @@ def api_wifi_verification_map_gps_start():
|
|||||||
service = wifi_verification_shared_gps_service
|
service = wifi_verification_shared_gps_service
|
||||||
|
|
||||||
if wifi_verification_map_monitor_enabled:
|
if wifi_verification_map_monitor_enabled:
|
||||||
|
|
||||||
if (
|
if (
|
||||||
service is not None
|
service is not None
|
||||||
and service.thread is not None
|
and service.thread is not None
|
||||||
@@ -3613,42 +4080,45 @@ def api_wifi_verification_map_gps_start():
|
|||||||
wifi_verification_map_monitor_enabled = False
|
wifi_verification_map_monitor_enabled = False
|
||||||
|
|
||||||
if auto_running:
|
if auto_running:
|
||||||
|
if auto_service.verification_mode == "MANUAL":
|
||||||
|
settings = auto_service.settings
|
||||||
|
else:
|
||||||
|
if (
|
||||||
|
service is None
|
||||||
|
or service.thread is None
|
||||||
|
or not service.thread.is_alive()
|
||||||
|
):
|
||||||
|
return jsonify({
|
||||||
|
"ok": False,
|
||||||
|
"error": (
|
||||||
|
"GPS service used by Auto Verification "
|
||||||
|
"is not running."
|
||||||
|
)
|
||||||
|
}), 409
|
||||||
|
|
||||||
|
wifi_verification_map_monitor_enabled = True
|
||||||
|
|
||||||
if (
|
|
||||||
service is None
|
|
||||||
or service.thread is None
|
|
||||||
or not service.thread.is_alive()
|
|
||||||
):
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"ok": False,
|
"ok": True,
|
||||||
"error": (
|
"monitor_enabled": True,
|
||||||
"GPS service used by Auto Verification "
|
"gps": service.get_status()
|
||||||
"is not running."
|
})
|
||||||
)
|
|
||||||
}), 409
|
|
||||||
|
|
||||||
wifi_verification_map_monitor_enabled = True
|
else:
|
||||||
|
connection = connect_database()
|
||||||
|
|
||||||
return jsonify({
|
row = connection.execute(
|
||||||
"ok": True,
|
"""
|
||||||
"monitor_enabled": True,
|
SELECT *
|
||||||
"gps": service.get_status()
|
FROM wifi_verification_settings
|
||||||
})
|
WHERE id = 1
|
||||||
|
"""
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
connection = connect_database()
|
settings = dict(row) if row is not None else None
|
||||||
|
|
||||||
row = connection.execute(
|
close_database(connection)
|
||||||
"""
|
connection = None
|
||||||
SELECT *
|
|
||||||
FROM wifi_verification_settings
|
|
||||||
WHERE id = 1
|
|
||||||
"""
|
|
||||||
).fetchone()
|
|
||||||
|
|
||||||
settings = dict(row) if row is not None else None
|
|
||||||
|
|
||||||
close_database(connection)
|
|
||||||
connection = None
|
|
||||||
|
|
||||||
if settings is None:
|
if settings is None:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
@@ -3665,20 +4135,7 @@ def api_wifi_verification_map_gps_start():
|
|||||||
):
|
):
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"ok": False,
|
"ok": False,
|
||||||
"error": (
|
"error": "Select GPS source: gpsd or gpsrelay."
|
||||||
"Select GPS source: gpsd or gpsrelay."
|
|
||||||
)
|
|
||||||
}), 409
|
|
||||||
|
|
||||||
acquired, owner_error = acquire_network_owner(
|
|
||||||
"MAP_GPS_MONITOR"
|
|
||||||
)
|
|
||||||
|
|
||||||
if not acquired:
|
|
||||||
return jsonify({
|
|
||||||
"ok": False,
|
|
||||||
"error": owner_error,
|
|
||||||
"owner": network_operation_owner
|
|
||||||
}), 409
|
}), 409
|
||||||
|
|
||||||
service = _get_wifi_verification_shared_gps(
|
service = _get_wifi_verification_shared_gps(
|
||||||
@@ -3699,22 +4156,16 @@ def api_wifi_verification_map_gps_start():
|
|||||||
)
|
)
|
||||||
|
|
||||||
if not started:
|
if not started:
|
||||||
cleanup_ok = True
|
thread = service.thread
|
||||||
|
|
||||||
if started_service:
|
if thread is None or not thread.is_alive():
|
||||||
cleanup_ok = (
|
if started_service:
|
||||||
_stop_wifi_verification_shared_gps_locked()
|
_stop_wifi_verification_shared_gps_locked()
|
||||||
)
|
|
||||||
|
|
||||||
if cleanup_ok:
|
return jsonify({
|
||||||
release_network_owner(
|
"ok": False,
|
||||||
"MAP_GPS_MONITOR"
|
"error": "GPS service could not be started."
|
||||||
)
|
}), 409
|
||||||
|
|
||||||
return jsonify({
|
|
||||||
"ok": False,
|
|
||||||
"error": "GPS service could not be started."
|
|
||||||
}), 409
|
|
||||||
|
|
||||||
wifi_verification_map_monitor_enabled = True
|
wifi_verification_map_monitor_enabled = True
|
||||||
|
|
||||||
@@ -3732,20 +4183,8 @@ def api_wifi_verification_map_gps_start():
|
|||||||
|
|
||||||
with wifi_verification_shared_gps_lock:
|
with wifi_verification_shared_gps_lock:
|
||||||
|
|
||||||
cleanup_ok = True
|
|
||||||
|
|
||||||
if started_service and service is not None:
|
if started_service and service is not None:
|
||||||
cleanup_ok = (
|
_stop_wifi_verification_shared_gps_locked()
|
||||||
_stop_wifi_verification_shared_gps_locked()
|
|
||||||
)
|
|
||||||
|
|
||||||
if (
|
|
||||||
cleanup_ok
|
|
||||||
and network_operation_owner == "MAP_GPS_MONITOR"
|
|
||||||
):
|
|
||||||
release_network_owner(
|
|
||||||
"MAP_GPS_MONITOR"
|
|
||||||
)
|
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"ok": False,
|
"ok": False,
|
||||||
@@ -3769,12 +4208,9 @@ def api_wifi_verification_map_gps_stop():
|
|||||||
with auto_wifi_verification_lock:
|
with auto_wifi_verification_lock:
|
||||||
with wifi_verification_shared_gps_lock:
|
with wifi_verification_shared_gps_lock:
|
||||||
|
|
||||||
wifi_verification_map_monitor_enabled = False
|
|
||||||
|
|
||||||
owner = network_operation_owner
|
owner = network_operation_owner
|
||||||
|
|
||||||
if owner == "AUTO_WIFI_VERIFY":
|
if owner == "AUTO_WIFI_VERIFY":
|
||||||
|
|
||||||
service = wifi_verification_shared_gps_service
|
service = wifi_verification_shared_gps_service
|
||||||
|
|
||||||
gps_status = (
|
gps_status = (
|
||||||
@@ -3783,67 +4219,39 @@ def api_wifi_verification_map_gps_stop():
|
|||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
|
|
||||||
|
wifi_verification_map_monitor_enabled = False
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"ok": True,
|
"ok": True,
|
||||||
"monitor_enabled": False,
|
"monitor_enabled": False,
|
||||||
"stop_deferred": True,
|
"stop_deferred": True,
|
||||||
|
"owner": owner,
|
||||||
"gps": gps_status
|
"gps": gps_status
|
||||||
})
|
})
|
||||||
|
|
||||||
if owner == "MAP_GPS_MONITOR":
|
stopped = (
|
||||||
|
_stop_wifi_verification_shared_gps_locked()
|
||||||
stopped = (
|
)
|
||||||
_stop_wifi_verification_shared_gps_locked()
|
|
||||||
)
|
|
||||||
|
|
||||||
if not stopped:
|
|
||||||
return jsonify({
|
|
||||||
"ok": False,
|
|
||||||
"error": (
|
|
||||||
"GPS service did not stop. "
|
|
||||||
"Its state was preserved."
|
|
||||||
),
|
|
||||||
"monitor_enabled": False
|
|
||||||
}), 409
|
|
||||||
|
|
||||||
release_network_owner(
|
|
||||||
"MAP_GPS_MONITOR"
|
|
||||||
)
|
|
||||||
|
|
||||||
elif owner is not None:
|
|
||||||
|
|
||||||
|
if not stopped:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"ok": False,
|
"ok": False,
|
||||||
"error": (
|
"error": (
|
||||||
"GPS is owned by another operation."
|
"GPS service did not stop. "
|
||||||
|
"Its state was preserved."
|
||||||
),
|
),
|
||||||
"owner": owner,
|
"monitor_enabled": (
|
||||||
"monitor_enabled": False
|
wifi_verification_map_monitor_enabled
|
||||||
|
)
|
||||||
}), 409
|
}), 409
|
||||||
|
|
||||||
else:
|
wifi_verification_map_monitor_enabled = False
|
||||||
|
|
||||||
service = wifi_verification_shared_gps_service
|
|
||||||
|
|
||||||
if (
|
|
||||||
service is not None
|
|
||||||
and service.thread is not None
|
|
||||||
and service.thread.is_alive()
|
|
||||||
):
|
|
||||||
stopped = (
|
|
||||||
_stop_wifi_verification_shared_gps_locked()
|
|
||||||
)
|
|
||||||
|
|
||||||
if not stopped:
|
|
||||||
return jsonify({
|
|
||||||
"ok": False,
|
|
||||||
"error": "GPS service did not stop."
|
|
||||||
}), 409
|
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"ok": True,
|
"ok": True,
|
||||||
"monitor_enabled": False,
|
"monitor_enabled": False,
|
||||||
"stop_deferred": False
|
"stop_deferred": False,
|
||||||
|
"owner": owner
|
||||||
})
|
})
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -3919,6 +4327,51 @@ def api_wifi_verification_start():
|
|||||||
|
|
||||||
interface = interface.strip()
|
interface = interface.strip()
|
||||||
|
|
||||||
|
mode = data.get("mode", "AUTO")
|
||||||
|
|
||||||
|
if not isinstance(mode, str):
|
||||||
|
return jsonify({
|
||||||
|
"ok": False,
|
||||||
|
"error": "Invalid verification mode."
|
||||||
|
}), 400
|
||||||
|
|
||||||
|
mode = mode.strip().upper()
|
||||||
|
|
||||||
|
if mode not in ("AUTO", "MANUAL"):
|
||||||
|
return jsonify({
|
||||||
|
"ok": False,
|
||||||
|
"error": "Invalid verification mode."
|
||||||
|
}), 400
|
||||||
|
|
||||||
|
manual_center = None
|
||||||
|
|
||||||
|
if mode == "MANUAL":
|
||||||
|
coordinates = data.get("manual_center")
|
||||||
|
|
||||||
|
if (
|
||||||
|
not isinstance(coordinates, list)
|
||||||
|
or len(coordinates) != 2
|
||||||
|
or any(type(value) not in (int, float) for value in coordinates)
|
||||||
|
):
|
||||||
|
return jsonify({
|
||||||
|
"ok": False,
|
||||||
|
"error": "Manual center must contain numeric latitude and longitude."
|
||||||
|
}), 400
|
||||||
|
|
||||||
|
latitude = float(coordinates[0])
|
||||||
|
longitude = float(coordinates[1])
|
||||||
|
|
||||||
|
if not (
|
||||||
|
-90 <= latitude <= 90
|
||||||
|
and -180 <= longitude <= 180
|
||||||
|
):
|
||||||
|
return jsonify({
|
||||||
|
"ok": False,
|
||||||
|
"error": "Manual center coordinates are out of range."
|
||||||
|
}), 400
|
||||||
|
|
||||||
|
manual_center = (latitude, longitude)
|
||||||
|
|
||||||
device, error, status = validate_network_interface(
|
device, error, status = validate_network_interface(
|
||||||
interface
|
interface
|
||||||
)
|
)
|
||||||
@@ -3977,7 +4430,10 @@ def api_wifi_verification_start():
|
|||||||
}
|
}
|
||||||
), 409
|
), 409
|
||||||
|
|
||||||
if settings.get("gps_source") not in ("gpsd", "gpsrelay"):
|
if (
|
||||||
|
mode == "AUTO"
|
||||||
|
and settings.get("gps_source") not in ("gpsd", "gpsrelay")
|
||||||
|
):
|
||||||
|
|
||||||
return jsonify(
|
return jsonify(
|
||||||
{
|
{
|
||||||
@@ -4002,9 +4458,17 @@ def api_wifi_verification_start():
|
|||||||
}
|
}
|
||||||
), 409
|
), 409
|
||||||
|
|
||||||
shared_gps_service = (
|
if mode == "AUTO":
|
||||||
_get_wifi_verification_shared_gps(settings)
|
shared_gps_service = (
|
||||||
)
|
_get_wifi_verification_shared_gps(settings)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
with wifi_verification_shared_gps_lock:
|
||||||
|
shared_gps_service = (
|
||||||
|
wifi_verification_shared_gps_service
|
||||||
|
if wifi_verification_map_monitor_enabled
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
service = AutoWiFiVerificationService(
|
service = AutoWiFiVerificationService(
|
||||||
settings=settings,
|
settings=settings,
|
||||||
@@ -4019,7 +4483,9 @@ def api_wifi_verification_start():
|
|||||||
),
|
),
|
||||||
release_network_owner=(
|
release_network_owner=(
|
||||||
release_wifi_verification_network_owner
|
release_wifi_verification_network_owner
|
||||||
)
|
),
|
||||||
|
mode=mode,
|
||||||
|
manual_center=manual_center
|
||||||
)
|
)
|
||||||
|
|
||||||
auto_wifi_verification_service = service
|
auto_wifi_verification_service = service
|
||||||
|
|||||||
+58
-1
@@ -1444,7 +1444,7 @@ pre {
|
|||||||
font: inherit;
|
font: inherit;
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
cursor: default;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.capture-mode-button.active {
|
.capture-mode-button.active {
|
||||||
@@ -1835,6 +1835,24 @@ pre {
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.auto-verification-relay-discovery {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auto-verification-relay-discovery .button {
|
||||||
|
min-width: 190px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#auto-gpsrelay-discovery-status {
|
||||||
|
width: 100%;
|
||||||
|
text-align: center;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
.auto-verification-config .field {
|
.auto-verification-config .field {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: none;
|
max-width: none;
|
||||||
@@ -2238,6 +2256,21 @@ pre {
|
|||||||
box-shadow: 0 0 0 5px rgba(38, 136, 255, 0.25);
|
box-shadow: 0 0 0 5px rgba(38, 136, 255, 0.25);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.auto-manual-map-marker {
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
border: 3px solid #fff;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #a855f7;
|
||||||
|
box-shadow: 0 0 0 6px rgba(168, 85, 247, 0.25);
|
||||||
|
cursor: grab;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auto-manual-map-marker:active {
|
||||||
|
cursor: grabbing;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/* Auto Verification — map top row and layers */
|
/* Auto Verification — map top row and layers */
|
||||||
.capture-map-top-row {
|
.capture-map-top-row {
|
||||||
@@ -2819,3 +2852,27 @@ pre {
|
|||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#capture-map .auto-gps-follow-control button:disabled {
|
||||||
|
opacity: 0.35;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
#capture-map .auto-gps-follow-control .auto-manual-center-button svg {
|
||||||
|
fill: none;
|
||||||
|
stroke: currentColor;
|
||||||
|
stroke-width: 1.8;
|
||||||
|
stroke-linecap: round;
|
||||||
|
}
|
||||||
|
|
||||||
|
#capture-map .auto-gps-follow-control .auto-gps-follow-button.is-manual {
|
||||||
|
color: #2688ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
#capture-map .auto-gps-follow-control .auto-manual-center-button {
|
||||||
|
color: #e53935;
|
||||||
|
}
|
||||||
|
|
||||||
|
#capture-map .auto-gps-follow-control .auto-manual-center-button.active {
|
||||||
|
color: #a855f7;
|
||||||
|
}
|
||||||
|
|||||||
@@ -53,19 +53,18 @@
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
id="auto-mode-button"
|
||||||
class="capture-mode-button active"
|
class="capture-mode-button active"
|
||||||
aria-pressed="true"
|
aria-pressed="true"
|
||||||
disabled
|
|
||||||
>
|
>
|
||||||
Auto
|
Auto
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
id="manual-mode-button"
|
||||||
class="capture-mode-button"
|
class="capture-mode-button"
|
||||||
aria-pressed="false"
|
aria-pressed="false"
|
||||||
title="Будет доступен на следующем этапе"
|
|
||||||
disabled
|
|
||||||
>
|
>
|
||||||
Manual
|
Manual
|
||||||
</button>
|
</button>
|
||||||
@@ -395,9 +394,26 @@
|
|||||||
name="gpsrelay_port"
|
name="gpsrelay_port"
|
||||||
min="1"
|
min="1"
|
||||||
max="65535"
|
max="65535"
|
||||||
|
value="5000"
|
||||||
placeholder="1–65535"
|
placeholder="1–65535"
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="auto-verification-relay-discovery">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="button start"
|
||||||
|
id="auto-gpsrelay-discover"
|
||||||
|
>
|
||||||
|
Найти GPS Relay
|
||||||
|
</button>
|
||||||
|
<div
|
||||||
|
class="config-help"
|
||||||
|
id="auto-gpsrelay-discovery-status"
|
||||||
|
role="status"
|
||||||
|
aria-live="polite"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -505,6 +521,12 @@
|
|||||||
const relayFields = document.getElementById("auto-gpsrelay-fields");
|
const relayFields = document.getElementById("auto-gpsrelay-fields");
|
||||||
const relayHost = document.getElementById("auto-gpsrelay-host");
|
const relayHost = document.getElementById("auto-gpsrelay-host");
|
||||||
const relayPort = document.getElementById("auto-gpsrelay-port");
|
const relayPort = document.getElementById("auto-gpsrelay-port");
|
||||||
|
const relayDiscoverButton = document.getElementById(
|
||||||
|
"auto-gpsrelay-discover"
|
||||||
|
);
|
||||||
|
const relayDiscoveryStatus = document.getElementById(
|
||||||
|
"auto-gpsrelay-discovery-status"
|
||||||
|
);
|
||||||
|
|
||||||
const gnssMaxAge = document.getElementById("auto-gnss-max-age");
|
const gnssMaxAge = document.getElementById("auto-gnss-max-age");
|
||||||
const retryPasses = document.getElementById("auto-queue-retry-passes");
|
const retryPasses = document.getElementById("auto-queue-retry-passes");
|
||||||
@@ -525,6 +547,14 @@
|
|||||||
);
|
);
|
||||||
|
|
||||||
const settingsUrl = "/api/wifi-verification/settings";
|
const settingsUrl = "/api/wifi-verification/settings";
|
||||||
|
const relayDiscoveryStartUrl =
|
||||||
|
"/api/wifi-verification/gpsrelay-discovery/start";
|
||||||
|
const relayDiscoveryStatusUrl =
|
||||||
|
"/api/wifi-verification/gpsrelay-discovery/status";
|
||||||
|
|
||||||
|
let relayDiscoveryTimer = null;
|
||||||
|
let relayDiscoveryActive = false;
|
||||||
|
let relayDiscoveryApplyResult = false;
|
||||||
|
|
||||||
function updateGpsSourceFields() {
|
function updateGpsSourceFields() {
|
||||||
const useRelay = gpsSource.value === "gpsrelay";
|
const useRelay = gpsSource.value === "gpsrelay";
|
||||||
@@ -563,6 +593,150 @@
|
|||||||
radiusApplyStatus.classList.toggle("error", isError);
|
radiusApplyStatus.classList.toggle("error", isError);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function showRelayDiscoveryStatus(message, isError = false) {
|
||||||
|
relayDiscoveryStatus.textContent = message;
|
||||||
|
relayDiscoveryStatus.classList.toggle("error", isError);
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleRelayDiscoveryPoll() {
|
||||||
|
if (relayDiscoveryTimer !== null) {
|
||||||
|
window.clearTimeout(relayDiscoveryTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
relayDiscoveryTimer = window.setTimeout(() => {
|
||||||
|
relayDiscoveryTimer = null;
|
||||||
|
refreshRelayDiscoveryStatus();
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshRelayDiscoveryStatus() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(relayDiscoveryStatusUrl);
|
||||||
|
const job = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok || !job.ok) {
|
||||||
|
throw new Error(
|
||||||
|
job.error || "Не удалось получить состояние поиска."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (job.state === "RUNNING") {
|
||||||
|
relayDiscoveryActive = true;
|
||||||
|
relayDiscoveryApplyResult = true;
|
||||||
|
relayDiscoverButton.disabled = true;
|
||||||
|
|
||||||
|
showRelayDiscoveryStatus(
|
||||||
|
"Поиск GPSRelay и проверка потока NMEA…"
|
||||||
|
);
|
||||||
|
|
||||||
|
scheduleRelayDiscoveryPoll();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
relayDiscoveryActive = false;
|
||||||
|
relayDiscoverButton.disabled = false;
|
||||||
|
|
||||||
|
if (job.state === "SUCCEEDED" && job.result) {
|
||||||
|
if (relayDiscoveryApplyResult) {
|
||||||
|
const found = job.result;
|
||||||
|
const types = Array.isArray(found.sentence_types)
|
||||||
|
? found.sentence_types.join(", ")
|
||||||
|
: "";
|
||||||
|
|
||||||
|
relayHost.value = found.host || relayHost.value;
|
||||||
|
relayPort.value = found.port ?? relayPort.value;
|
||||||
|
|
||||||
|
showRelayDiscoveryStatus(
|
||||||
|
`Найден GPSRelay: ${found.host}:${found.port}. `
|
||||||
|
+ `Интерфейс: ${found.interface}. `
|
||||||
|
+ `Корректных NMEA-предложений: `
|
||||||
|
+ `${found.valid_sentences}. `
|
||||||
|
+ `Типы: ${types}. `
|
||||||
|
+ "Для сохранения нажмите SAVE."
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
showRelayDiscoveryStatus("");
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (job.state === "FAILED") {
|
||||||
|
if (relayDiscoveryApplyResult) {
|
||||||
|
showRelayDiscoveryStatus(
|
||||||
|
job.error || "GPSRelay не найден.",
|
||||||
|
true
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
showRelayDiscoveryStatus("");
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
showRelayDiscoveryStatus("");
|
||||||
|
}
|
||||||
|
|
||||||
|
relayDiscoveryApplyResult = false;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
if (relayDiscoveryActive) {
|
||||||
|
relayDiscoverButton.disabled = true;
|
||||||
|
showRelayDiscoveryStatus(
|
||||||
|
`Не удалось обновить состояние поиска: ${error.message}`
|
||||||
|
);
|
||||||
|
scheduleRelayDiscoveryPoll();
|
||||||
|
} else {
|
||||||
|
relayDiscoverButton.disabled = false;
|
||||||
|
showRelayDiscoveryStatus(error.message, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startRelayDiscovery() {
|
||||||
|
const rawPort = relayPort.value.trim();
|
||||||
|
const port = rawPort === "" ? 5000 : Number(rawPort);
|
||||||
|
|
||||||
|
if (
|
||||||
|
!Number.isInteger(port)
|
||||||
|
|| port < 1
|
||||||
|
|| port > 65535
|
||||||
|
) {
|
||||||
|
showRelayDiscoveryStatus(
|
||||||
|
"Укажите корректный порт от 1 до 65535.",
|
||||||
|
true
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
relayDiscoverButton.disabled = true;
|
||||||
|
relayDiscoveryActive = true;
|
||||||
|
relayDiscoveryApplyResult = true;
|
||||||
|
|
||||||
|
showRelayDiscoveryStatus("Запуск поиска GPSRelay…");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(relayDiscoveryStartUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ port: port })
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok || !result.ok) {
|
||||||
|
throw new Error(
|
||||||
|
result.error || "Не удалось запустить поиск GPSRelay."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await refreshRelayDiscoveryStatus();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
relayDiscoveryActive = false;
|
||||||
|
relayDiscoveryApplyResult = false;
|
||||||
|
relayDiscoverButton.disabled = false;
|
||||||
|
showRelayDiscoveryStatus(error.message, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function applyRadius() {
|
async function applyRadius() {
|
||||||
const radius = getSelectedRadius();
|
const radius = getSelectedRadius();
|
||||||
|
|
||||||
@@ -598,6 +772,11 @@
|
|||||||
: `Радиус ${radius} м сохранён и будет использован при следующем запуске.`
|
: `Радиус ${radius} м сохранён и будет использован при следующем запуске.`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
window.dispatchEvent(new CustomEvent(
|
||||||
|
"wifi-verification-radius-applied",
|
||||||
|
{ detail: { radius_m: radius } }
|
||||||
|
));
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showRadiusStatus(error.message, true);
|
showRadiusStatus(error.message, true);
|
||||||
|
|
||||||
@@ -611,7 +790,7 @@
|
|||||||
gpsSource.value = settings.gps_source || "";
|
gpsSource.value = settings.gps_source || "";
|
||||||
|
|
||||||
relayHost.value = settings.gpsrelay_host || "";
|
relayHost.value = settings.gpsrelay_host || "";
|
||||||
relayPort.value = settings.gpsrelay_port ?? "";
|
relayPort.value = settings.gpsrelay_port ?? "5000";
|
||||||
|
|
||||||
gnssMaxAge.value = settings.gnss_max_age_seconds;
|
gnssMaxAge.value = settings.gnss_max_age_seconds;
|
||||||
retryPasses.value = settings.queue_retry_passes;
|
retryPasses.value = settings.queue_retry_passes;
|
||||||
@@ -642,6 +821,7 @@
|
|||||||
|
|
||||||
loadSettings(result.settings);
|
loadSettings(result.settings);
|
||||||
showStatus("Настройки загружены.");
|
showStatus("Настройки загружены.");
|
||||||
|
refreshRelayDiscoveryStatus();
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showStatus(error.message, true);
|
showStatus(error.message, true);
|
||||||
@@ -724,6 +904,10 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
saveButton.addEventListener("click", saveSettings);
|
saveButton.addEventListener("click", saveSettings);
|
||||||
|
relayDiscoverButton.addEventListener(
|
||||||
|
"click",
|
||||||
|
startRelayDiscovery
|
||||||
|
);
|
||||||
radiusApplyButton.addEventListener("click", applyRadius);
|
radiusApplyButton.addEventListener("click", applyRadius);
|
||||||
mapRadiusApplyButton.addEventListener("click", applyRadius);
|
mapRadiusApplyButton.addEventListener("click", applyRadius);
|
||||||
|
|
||||||
@@ -734,7 +918,8 @@
|
|||||||
gpsSource.selectedIndex = 0;
|
gpsSource.selectedIndex = 0;
|
||||||
|
|
||||||
relayHost.value = "";
|
relayHost.value = "";
|
||||||
relayPort.value = "";
|
relayPort.value = "5000";
|
||||||
|
showRelayDiscoveryStatus("");
|
||||||
|
|
||||||
gnssMaxAge.value = "5";
|
gnssMaxAge.value = "5";
|
||||||
retryPasses.value = "1";
|
retryPasses.value = "1";
|
||||||
@@ -767,6 +952,8 @@
|
|||||||
const count = document.getElementById("capture-map-count");
|
const count = document.getElementById("capture-map-count");
|
||||||
const startButton = document.getElementById("auto-start");
|
const startButton = document.getElementById("auto-start");
|
||||||
const stopButton = document.getElementById("auto-stop");
|
const stopButton = document.getElementById("auto-stop");
|
||||||
|
const autoModeButton = document.getElementById("auto-mode-button");
|
||||||
|
const manualModeButton = document.getElementById("manual-mode-button");
|
||||||
const interfaceSelect = document.getElementById("auto-interface");
|
const interfaceSelect = document.getElementById("auto-interface");
|
||||||
const statusText = document.getElementById("header-scanner-status");
|
const statusText = document.getElementById("header-scanner-status");
|
||||||
const statusIndicator = document.getElementById("auto-status-indicator");
|
const statusIndicator = document.getElementById("auto-status-indicator");
|
||||||
@@ -797,6 +984,8 @@
|
|||||||
const gpsValue = document.querySelector(".auto-position-gps");
|
const gpsValue = document.querySelector(".auto-position-gps");
|
||||||
const coordinatesInput = document.getElementById("auto-position-coordinates");
|
const coordinatesInput = document.getElementById("auto-position-coordinates");
|
||||||
const radiusText = document.getElementById("auto-position-radius");
|
const radiusText = document.getElementById("auto-position-radius");
|
||||||
|
let manualCenterButton = null;
|
||||||
|
const mapRadiusSelect = document.getElementById("auto-map-radius-select");
|
||||||
|
|
||||||
const filters = {
|
const filters = {
|
||||||
green: true,
|
green: true,
|
||||||
@@ -815,6 +1004,10 @@
|
|||||||
let gpsLastRadius = null;
|
let gpsLastRadius = null;
|
||||||
let latestGpsPosition = null;
|
let latestGpsPosition = null;
|
||||||
let autoRunning = false;
|
let autoRunning = false;
|
||||||
|
let verificationMode = "AUTO";
|
||||||
|
let manualCenter = null;
|
||||||
|
let manualMarker = null;
|
||||||
|
let manualPlacementEnabled = false;
|
||||||
|
|
||||||
const map = new maplibregl.Map({
|
const map = new maplibregl.Map({
|
||||||
container: "capture-map",
|
container: "capture-map",
|
||||||
@@ -855,8 +1048,6 @@
|
|||||||
const button = document.createElement("button");
|
const button = document.createElement("button");
|
||||||
button.type = "button";
|
button.type = "button";
|
||||||
button.className = "auto-gps-follow-button";
|
button.className = "auto-gps-follow-button";
|
||||||
button.title = "Вернуться к GPS";
|
|
||||||
button.setAttribute("aria-label", "Вернуться к GPS");
|
|
||||||
button.setAttribute("aria-pressed", "true");
|
button.setAttribute("aria-pressed", "true");
|
||||||
button.innerHTML = `
|
button.innerHTML = `
|
||||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
@@ -867,6 +1058,47 @@
|
|||||||
gpsFollowButton = button;
|
gpsFollowButton = button;
|
||||||
|
|
||||||
button.addEventListener("click", () => {
|
button.addEventListener("click", () => {
|
||||||
|
if (verificationMode === "MANUAL") {
|
||||||
|
if (!manualCenter) {
|
||||||
|
setMessage("Сначала установите ручной центр проверки.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const radius = Number(mapRadiusSelect.value);
|
||||||
|
const cameraOptions = {
|
||||||
|
center: [
|
||||||
|
manualCenter.longitude,
|
||||||
|
manualCenter.latitude
|
||||||
|
],
|
||||||
|
duration: 500
|
||||||
|
};
|
||||||
|
|
||||||
|
if (Number.isFinite(radius) && radius > 0) {
|
||||||
|
const extent = buildGpsCircle(
|
||||||
|
manualCenter.latitude,
|
||||||
|
manualCenter.longitude,
|
||||||
|
radius * 2
|
||||||
|
);
|
||||||
|
|
||||||
|
const bounds = new maplibregl.LngLatBounds();
|
||||||
|
|
||||||
|
extent.geometry.coordinates[0].forEach(point => {
|
||||||
|
bounds.extend(point);
|
||||||
|
});
|
||||||
|
|
||||||
|
const camera = map.cameraForBounds(bounds, {
|
||||||
|
padding: 0
|
||||||
|
});
|
||||||
|
|
||||||
|
if (camera && Number.isFinite(camera.zoom)) {
|
||||||
|
cameraOptions.zoom = camera.zoom;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
map.easeTo(cameraOptions);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setGpsFollowing(true);
|
setGpsFollowing(true);
|
||||||
|
|
||||||
if (latestGpsPosition) {
|
if (latestGpsPosition) {
|
||||||
@@ -882,16 +1114,59 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
container.appendChild(button);
|
container.appendChild(button);
|
||||||
|
|
||||||
|
const manualButton = document.createElement("button");
|
||||||
|
manualButton.type = "button";
|
||||||
|
manualButton.className = "auto-manual-center-button";
|
||||||
|
manualButton.title = "Установить центр проверки";
|
||||||
|
manualButton.setAttribute(
|
||||||
|
"aria-label",
|
||||||
|
"Установить центр проверки"
|
||||||
|
);
|
||||||
|
manualButton.disabled = true;
|
||||||
|
manualButton.innerHTML = `
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<circle cx="12" cy="12" r="7"/>
|
||||||
|
<circle cx="12" cy="12" r="2"/>
|
||||||
|
<path d="M12 2v3M12 19v3M2 12h3M19 12h3"/>
|
||||||
|
</svg>
|
||||||
|
`;
|
||||||
|
|
||||||
|
manualCenterButton = manualButton;
|
||||||
|
|
||||||
|
manualButton.addEventListener("click", () => {
|
||||||
|
if (verificationMode !== "MANUAL" || autoRunning) return;
|
||||||
|
|
||||||
|
manualPlacementEnabled = !manualPlacementEnabled;
|
||||||
|
|
||||||
|
map.getCanvas().style.cursor = (
|
||||||
|
manualPlacementEnabled ? "crosshair" : ""
|
||||||
|
);
|
||||||
|
|
||||||
|
manualButton.classList.toggle(
|
||||||
|
"active",
|
||||||
|
manualPlacementEnabled
|
||||||
|
);
|
||||||
|
|
||||||
|
setMessage(
|
||||||
|
manualPlacementEnabled
|
||||||
|
? "Выберите центр проверки щелчком на карте."
|
||||||
|
: "Установка центра отменена."
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
container.appendChild(manualButton);
|
||||||
|
|
||||||
return container;
|
return container;
|
||||||
},
|
},
|
||||||
|
|
||||||
onRemove() {
|
onRemove() {
|
||||||
gpsFollowButton = null;
|
gpsFollowButton = null;
|
||||||
|
manualCenterButton = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
map.addControl(gpsFollowControl, "top-right");
|
map.addControl(gpsFollowControl, "top-right");
|
||||||
|
|
||||||
map.on("dragstart", pauseGpsFollowing);
|
map.on("dragstart", pauseGpsFollowing);
|
||||||
map.on("dblclick", pauseGpsFollowing);
|
map.on("dblclick", pauseGpsFollowing);
|
||||||
|
|
||||||
@@ -969,8 +1244,38 @@
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renderModeButtons() {
|
||||||
|
const isAuto = verificationMode === "AUTO";
|
||||||
|
|
||||||
|
autoModeButton.classList.toggle("active", isAuto);
|
||||||
|
autoModeButton.setAttribute("aria-pressed", String(isAuto));
|
||||||
|
|
||||||
|
manualModeButton.classList.toggle("active", !isAuto);
|
||||||
|
manualModeButton.setAttribute("aria-pressed", String(!isAuto));
|
||||||
|
|
||||||
|
autoModeButton.disabled = autoRunning;
|
||||||
|
manualModeButton.disabled = autoRunning;
|
||||||
|
|
||||||
|
updateManualModeUI();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setVerificationMode(mode) {
|
||||||
|
if (autoRunning) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
verificationMode = mode === "MANUAL" ? "MANUAL" : "AUTO";
|
||||||
|
|
||||||
|
renderModeButtons();
|
||||||
|
updateStartButton();
|
||||||
|
}
|
||||||
|
|
||||||
function updateStartButton() {
|
function updateStartButton() {
|
||||||
startButton.disabled = autoRunning || !interfaceSelect.value;
|
startButton.disabled = (
|
||||||
|
autoRunning ||
|
||||||
|
!interfaceSelect.value ||
|
||||||
|
(verificationMode === "MANUAL" && !manualCenter)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function createMonitorElement(tag, className, text) {
|
function createMonitorElement(tag, className, text) {
|
||||||
@@ -1265,6 +1570,26 @@
|
|||||||
const running = Boolean(status.running);
|
const running = Boolean(status.running);
|
||||||
autoRunning = running;
|
autoRunning = running;
|
||||||
|
|
||||||
|
if (running && status.verification_mode) {
|
||||||
|
verificationMode = status.verification_mode === "MANUAL"
|
||||||
|
? "MANUAL"
|
||||||
|
: "AUTO";
|
||||||
|
}
|
||||||
|
|
||||||
|
renderModeButtons();
|
||||||
|
|
||||||
|
if (
|
||||||
|
running &&
|
||||||
|
verificationMode === "MANUAL" &&
|
||||||
|
Array.isArray(status.manual_center) &&
|
||||||
|
status.manual_center.length === 2
|
||||||
|
) {
|
||||||
|
setManualCenter(
|
||||||
|
Number(status.manual_center[0]),
|
||||||
|
Number(status.manual_center[1])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const stateLabels = {
|
const stateLabels = {
|
||||||
STOPPED: "остановлен",
|
STOPPED: "остановлен",
|
||||||
WAITING_GPS: "ожидание GPS",
|
WAITING_GPS: "ожидание GPS",
|
||||||
@@ -1278,7 +1603,7 @@
|
|||||||
);
|
);
|
||||||
|
|
||||||
statusText.textContent =
|
statusText.textContent =
|
||||||
`Auto: ${stateLabels[actualState] || actualState}`;
|
`${verificationMode === "MANUAL" ? "Manual" : "Auto"}: ${stateLabels[actualState] || actualState}`;
|
||||||
|
|
||||||
monitorState.textContent =
|
monitorState.textContent =
|
||||||
stateLabels[actualState] || actualState;
|
stateLabels[actualState] || actualState;
|
||||||
@@ -1367,6 +1692,149 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function updateManualCircle() {
|
||||||
|
const source = map.getSource("manual-search-radius");
|
||||||
|
|
||||||
|
if (!source) return;
|
||||||
|
|
||||||
|
if (verificationMode !== "MANUAL" || !manualCenter) {
|
||||||
|
source.setData(emptyGpsFeatureCollection());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const radius = Number(mapRadiusSelect.value);
|
||||||
|
|
||||||
|
if (!Number.isFinite(radius) || radius <= 0) {
|
||||||
|
source.setData(emptyGpsFeatureCollection());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
source.setData({
|
||||||
|
type: "FeatureCollection",
|
||||||
|
features: [
|
||||||
|
buildGpsCircle(
|
||||||
|
manualCenter.latitude,
|
||||||
|
manualCenter.longitude,
|
||||||
|
radius
|
||||||
|
)
|
||||||
|
]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateManualModeUI() {
|
||||||
|
const manualMode = verificationMode === "MANUAL";
|
||||||
|
|
||||||
|
if (manualMode) {
|
||||||
|
gpsPositionActive = false;
|
||||||
|
gpsCenterKey = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (gpsFollowButton) {
|
||||||
|
gpsFollowButton.title = manualMode
|
||||||
|
? "К центру проверки"
|
||||||
|
: "Вернуться к GPS";
|
||||||
|
gpsFollowButton.setAttribute(
|
||||||
|
"aria-label",
|
||||||
|
gpsFollowButton.title
|
||||||
|
);
|
||||||
|
gpsFollowButton.classList.toggle(
|
||||||
|
"is-active",
|
||||||
|
!manualMode && gpsFollowEnabled
|
||||||
|
);
|
||||||
|
gpsFollowButton.classList.toggle(
|
||||||
|
"is-manual",
|
||||||
|
manualMode
|
||||||
|
);
|
||||||
|
gpsFollowButton.setAttribute(
|
||||||
|
"aria-pressed",
|
||||||
|
String(!manualMode && gpsFollowEnabled)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (manualCenterButton) {
|
||||||
|
manualCenterButton.style.display = manualMode ? "" : "none";
|
||||||
|
manualCenterButton.disabled = !manualMode || autoRunning;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!manualMode || autoRunning) {
|
||||||
|
manualPlacementEnabled = false;
|
||||||
|
map.getCanvas().style.cursor = "";
|
||||||
|
|
||||||
|
if (manualCenterButton) {
|
||||||
|
manualCenterButton.classList.remove("active");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (manualMarker) {
|
||||||
|
manualMarker.setDraggable(!autoRunning);
|
||||||
|
manualMarker.getElement().style.display = (
|
||||||
|
manualMode ? "" : "none"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateManualCircle();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setManualCenter(latitude, longitude) {
|
||||||
|
if (
|
||||||
|
!Number.isFinite(latitude) ||
|
||||||
|
!Number.isFinite(longitude) ||
|
||||||
|
latitude < -90 ||
|
||||||
|
latitude > 90 ||
|
||||||
|
longitude < -180 ||
|
||||||
|
longitude > 180
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
manualCenter = { latitude, longitude };
|
||||||
|
|
||||||
|
if (!manualMarker) {
|
||||||
|
const element = document.createElement("div");
|
||||||
|
element.className = "auto-manual-map-marker";
|
||||||
|
|
||||||
|
manualMarker = new maplibregl.Marker({
|
||||||
|
element,
|
||||||
|
draggable: !autoRunning
|
||||||
|
})
|
||||||
|
.setLngLat([longitude, latitude])
|
||||||
|
.addTo(map);
|
||||||
|
|
||||||
|
manualMarker.on("dragend", () => {
|
||||||
|
if (autoRunning) return;
|
||||||
|
|
||||||
|
const position = manualMarker.getLngLat();
|
||||||
|
|
||||||
|
manualCenter = {
|
||||||
|
latitude: position.lat,
|
||||||
|
longitude: position.lng
|
||||||
|
};
|
||||||
|
|
||||||
|
coordinatesInput.value = (
|
||||||
|
`${position.lat.toFixed(6)}, ${position.lng.toFixed(6)}`
|
||||||
|
);
|
||||||
|
|
||||||
|
updateManualCircle();
|
||||||
|
updateStartButton();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
manualMarker
|
||||||
|
.setLngLat([longitude, latitude])
|
||||||
|
.setDraggable(!autoRunning);
|
||||||
|
|
||||||
|
manualMarker.getElement().style.display = (
|
||||||
|
verificationMode === "MANUAL" ? "" : "none"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
coordinatesInput.value = (
|
||||||
|
`${latitude.toFixed(6)}, ${longitude.toFixed(6)}`
|
||||||
|
);
|
||||||
|
|
||||||
|
updateManualCircle();
|
||||||
|
updateStartButton();
|
||||||
|
}
|
||||||
|
|
||||||
function updateGpsMap(latitude, longitude, radiusMeters) {
|
function updateGpsMap(latitude, longitude, radiusMeters) {
|
||||||
const source = map.getSource("auto-gps-radius");
|
const source = map.getSource("auto-gps-radius");
|
||||||
|
|
||||||
@@ -1383,7 +1851,9 @@
|
|||||||
gpsMarker.setLngLat([longitude, latitude]);
|
gpsMarker.setLngLat([longitude, latitude]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Number.isFinite(radiusMeters) && radiusMeters > 0) {
|
if (verificationMode === "MANUAL") {
|
||||||
|
source.setData(emptyGpsFeatureCollection());
|
||||||
|
} else if (Number.isFinite(radiusMeters) && radiusMeters > 0) {
|
||||||
source.setData({
|
source.setData({
|
||||||
type: "FeatureCollection",
|
type: "FeatureCollection",
|
||||||
features: [
|
features: [
|
||||||
@@ -1402,6 +1872,10 @@
|
|||||||
radiusMeters
|
radiusMeters
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (verificationMode === "MANUAL") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const validRadius = (
|
const validRadius = (
|
||||||
Number.isFinite(radiusMeters) && radiusMeters > 0
|
Number.isFinite(radiusMeters) && radiusMeters > 0
|
||||||
);
|
);
|
||||||
@@ -1469,7 +1943,10 @@
|
|||||||
gpsCenterKey = null;
|
gpsCenterKey = null;
|
||||||
gpsLastRadius = null;
|
gpsLastRadius = null;
|
||||||
latestGpsPosition = null;
|
latestGpsPosition = null;
|
||||||
setGpsFollowing(true);
|
|
||||||
|
if (verificationMode !== "MANUAL") {
|
||||||
|
setGpsFollowing(true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateGpsStatus(data) {
|
function updateGpsStatus(data) {
|
||||||
@@ -1477,7 +1954,7 @@
|
|||||||
const monitorEnabled = Boolean(data.monitor_enabled);
|
const monitorEnabled = Boolean(data.monitor_enabled);
|
||||||
const running = Boolean(gps.running);
|
const running = Boolean(gps.running);
|
||||||
const hasFix = (
|
const hasFix = (
|
||||||
(monitorEnabled || data.owner === "AUTO_WIFI_VERIFY") &&
|
monitorEnabled &&
|
||||||
running &&
|
running &&
|
||||||
Boolean(gps.has_fresh_fix) &&
|
Boolean(gps.has_fresh_fix) &&
|
||||||
gps.latitude !== null &&
|
gps.latitude !== null &&
|
||||||
@@ -1508,11 +1985,18 @@
|
|||||||
gpsValue.classList.add("is-searching");
|
gpsValue.classList.add("is-searching");
|
||||||
gpsDetail.textContent = (
|
gpsDetail.textContent = (
|
||||||
running
|
running
|
||||||
? "GPS используется другой операцией; монитор карты выключен"
|
? (
|
||||||
|
data.owner === "AUTO_WIFI_VERIFY"
|
||||||
|
? "GPS продолжает работать для Auto Verification; монитор карты выключен"
|
||||||
|
: "GPS работает, монитор карты выключен"
|
||||||
|
)
|
||||||
: "GPS-монитор карты остановлен"
|
: "GPS-монитор карты остановлен"
|
||||||
);
|
);
|
||||||
|
|
||||||
coordinatesInput.value = "";
|
if (verificationMode !== "MANUAL") {
|
||||||
|
coordinatesInput.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
clearGpsMap();
|
clearGpsMap();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1525,9 +2009,11 @@
|
|||||||
const latitude = Number(gps.latitude);
|
const latitude = Number(gps.latitude);
|
||||||
const longitude = Number(gps.longitude);
|
const longitude = Number(gps.longitude);
|
||||||
|
|
||||||
coordinatesInput.value = (
|
if (verificationMode !== "MANUAL") {
|
||||||
`${latitude.toFixed(6)}, ${longitude.toFixed(6)}`
|
coordinatesInput.value = (
|
||||||
);
|
`${latitude.toFixed(6)}, ${longitude.toFixed(6)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const age = Number(gps.fix_age_seconds);
|
const age = Number(gps.fix_age_seconds);
|
||||||
const ageText = Number.isFinite(age)
|
const ageText = Number.isFinite(age)
|
||||||
@@ -1542,7 +2028,10 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
coordinatesInput.value = "";
|
if (verificationMode !== "MANUAL") {
|
||||||
|
coordinatesInput.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
clearGpsMap();
|
clearGpsMap();
|
||||||
|
|
||||||
if (gps.state === "ERROR") {
|
if (gps.state === "ERROR") {
|
||||||
@@ -1637,7 +2126,11 @@
|
|||||||
visibleCoordinates.push(coordinates);
|
visibleCoordinates.push(coordinates);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (visibleCoordinates.length && !gpsPositionActive) {
|
if (
|
||||||
|
visibleCoordinates.length &&
|
||||||
|
!gpsPositionActive &&
|
||||||
|
!(verificationMode === "MANUAL" && manualCenter)
|
||||||
|
) {
|
||||||
const bounds = new maplibregl.LngLatBounds();
|
const bounds = new maplibregl.LngLatBounds();
|
||||||
visibleCoordinates.forEach(point => bounds.extend(point));
|
visibleCoordinates.forEach(point => bounds.extend(point));
|
||||||
map.fitBounds(bounds, { padding: 45, maxZoom: 15 });
|
map.fitBounds(bounds, { padding: 45, maxZoom: 15 });
|
||||||
@@ -1666,6 +2159,37 @@
|
|||||||
|
|
||||||
interfaceSelect.addEventListener("change", updateStartButton);
|
interfaceSelect.addEventListener("change", updateStartButton);
|
||||||
|
|
||||||
|
map.on("click", event => {
|
||||||
|
if (
|
||||||
|
verificationMode !== "MANUAL" ||
|
||||||
|
autoRunning ||
|
||||||
|
!manualPlacementEnabled
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setManualCenter(event.lngLat.lat, event.lngLat.lng);
|
||||||
|
|
||||||
|
manualPlacementEnabled = false;
|
||||||
|
map.getCanvas().style.cursor = "";
|
||||||
|
manualCenterButton.classList.remove("active");
|
||||||
|
|
||||||
|
setMessage("Ручной центр установлен.");
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener(
|
||||||
|
"wifi-verification-radius-applied",
|
||||||
|
updateManualCircle
|
||||||
|
);
|
||||||
|
|
||||||
|
autoModeButton.addEventListener("click", () => {
|
||||||
|
setVerificationMode("AUTO");
|
||||||
|
});
|
||||||
|
|
||||||
|
manualModeButton.addEventListener("click", () => {
|
||||||
|
setVerificationMode("MANUAL");
|
||||||
|
});
|
||||||
|
|
||||||
startButton.addEventListener("click", async () => {
|
startButton.addEventListener("click", async () => {
|
||||||
const interfaceName = interfaceSelect.value;
|
const interfaceName = interfaceSelect.value;
|
||||||
|
|
||||||
@@ -1675,22 +2199,46 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (verificationMode === "MANUAL" && !manualCenter) {
|
||||||
|
setMessage("Сначала установите ручной центр проверки.");
|
||||||
|
updateStartButton();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
interface: interfaceName,
|
||||||
|
mode: verificationMode
|
||||||
|
};
|
||||||
|
|
||||||
|
if (verificationMode === "MANUAL") {
|
||||||
|
payload.manual_center = [
|
||||||
|
manualCenter.latitude,
|
||||||
|
manualCenter.longitude
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
startButton.disabled = true;
|
startButton.disabled = true;
|
||||||
setMessage("Запуск Auto Verification…");
|
setMessage(
|
||||||
|
verificationMode === "MANUAL"
|
||||||
|
? "Запуск Manual Verification…"
|
||||||
|
: "Запуск Auto Verification…"
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await requestJson(startUrl, {
|
await requestJson(startUrl, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(payload)
|
||||||
interface: interfaceName
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await refreshStatus();
|
await refreshStatus();
|
||||||
setMessage("Auto Verification запущен.");
|
setMessage(
|
||||||
|
verificationMode === "MANUAL"
|
||||||
|
? "Manual Verification запущен."
|
||||||
|
: "Auto Verification запущен."
|
||||||
|
);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setMessage(`Не удалось запустить Auto Verification: ${error.message}`);
|
setMessage(`Не удалось запустить проверку: ${error.message}`);
|
||||||
await refreshStatus();
|
await refreshStatus();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -1756,6 +2304,33 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
map.addSource("manual-search-radius", {
|
||||||
|
type: "geojson",
|
||||||
|
data: emptyGpsFeatureCollection()
|
||||||
|
});
|
||||||
|
|
||||||
|
map.addLayer({
|
||||||
|
id: "manual-search-radius-fill",
|
||||||
|
type: "fill",
|
||||||
|
source: "manual-search-radius",
|
||||||
|
paint: {
|
||||||
|
"fill-color": "#a855f7",
|
||||||
|
"fill-opacity": 0.12
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
map.addLayer({
|
||||||
|
id: "manual-search-radius-line",
|
||||||
|
type: "line",
|
||||||
|
source: "manual-search-radius",
|
||||||
|
paint: {
|
||||||
|
"line-color": "#a855f7",
|
||||||
|
"line-width": 2,
|
||||||
|
"line-opacity": 0.9
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
updateManualCircle();
|
||||||
refreshMap();
|
refreshMap();
|
||||||
refreshGpsStatus();
|
refreshGpsStatus();
|
||||||
});
|
});
|
||||||
|
|||||||
+80
@@ -62,6 +62,82 @@ fail() {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
package_installed() {
|
||||||
|
dpkg-query -W -f='${db:Status-Status}' "$1" 2>/dev/null | grep -qx installed
|
||||||
|
}
|
||||||
|
|
||||||
|
install_gpsrelay_system_dependencies() {
|
||||||
|
local -a packages=(iproute2 nmap netcat-openbsd)
|
||||||
|
local -a commands=(ip nmap nc)
|
||||||
|
local -a missing_packages=()
|
||||||
|
local -a reinstall_packages=()
|
||||||
|
local -a sudo_cmd=()
|
||||||
|
local package executable
|
||||||
|
local index
|
||||||
|
|
||||||
|
echo "Проверка системных зависимостей GPSRelay..."
|
||||||
|
|
||||||
|
for index in "${!packages[@]}"; do
|
||||||
|
package="${packages[$index]}"
|
||||||
|
executable="${commands[$index]}"
|
||||||
|
|
||||||
|
if command -v "$executable" >/dev/null 2>&1; then
|
||||||
|
if package_installed "$package"; then
|
||||||
|
echo "[OK] $executable доступна, пакет $package установлен."
|
||||||
|
else
|
||||||
|
echo "[OK] $executable доступна; пакет $package не зарегистрирован, установка не требуется."
|
||||||
|
fi
|
||||||
|
elif package_installed "$package"; then
|
||||||
|
echo "[FIX] Пакет $package установлен, но команда $executable отсутствует."
|
||||||
|
reinstall_packages+=("$package")
|
||||||
|
else
|
||||||
|
echo "[MISSING] Не найдена команда $executable (пакет $package)."
|
||||||
|
missing_packages+=("$package")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if (( ${#missing_packages[@]} == 0 && ${#reinstall_packages[@]} == 0 )); then
|
||||||
|
echo "[OK] Все системные зависимости GPSRelay доступны."
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
command -v apt-get >/dev/null 2>&1 ||
|
||||||
|
fail "Для установки системных зависимостей GPSRelay требуется apt-get."
|
||||||
|
|
||||||
|
if (( EUID != 0 )); then
|
||||||
|
command -v sudo >/dev/null 2>&1 ||
|
||||||
|
fail "Для установки системных зависимостей GPSRelay необходим root или sudo."
|
||||||
|
|
||||||
|
sudo_cmd=(sudo)
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "ОБНОВЛЕНИЕ СПИСКА ПАКЕТОВ GPSRELAY"
|
||||||
|
|
||||||
|
"${sudo_cmd[@]}" apt-get update ||
|
||||||
|
fail "Не удалось обновить список пакетов для GPSRelay."
|
||||||
|
|
||||||
|
if (( ${#missing_packages[@]} > 0 )); then
|
||||||
|
log "УСТАНОВКА СИСТЕМНЫХ ЗАВИСИМОСТЕЙ GPSRELAY"
|
||||||
|
|
||||||
|
"${sudo_cmd[@]}" apt-get install -y "${missing_packages[@]}" ||
|
||||||
|
fail "Не удалось установить системные зависимости GPSRelay."
|
||||||
|
fi
|
||||||
|
|
||||||
|
if (( ${#reinstall_packages[@]} > 0 )); then
|
||||||
|
log "ВОССТАНОВЛЕНИЕ СИСТЕМНЫХ ЗАВИСИМОСТЕЙ GPSRELAY"
|
||||||
|
|
||||||
|
"${sudo_cmd[@]}" apt-get install -y --reinstall "${reinstall_packages[@]}" ||
|
||||||
|
fail "Не удалось восстановить системные зависимости GPSRelay."
|
||||||
|
fi
|
||||||
|
|
||||||
|
for executable in "${commands[@]}"; do
|
||||||
|
command -v "$executable" >/dev/null 2>&1 ||
|
||||||
|
fail "После установки не найдена необходимая команда GPSRelay: $executable"
|
||||||
|
|
||||||
|
echo "[OK] Команда $executable доступна."
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
log "ПРОВЕРКА ФАЙЛОВ ПРОЕКТА"
|
log "ПРОВЕРКА ФАЙЛОВ ПРОЕКТА"
|
||||||
|
|
||||||
[[ -f "$CONFIG_EXAMPLE" ]] || fail "Не найден $CONFIG_EXAMPLE"
|
[[ -f "$CONFIG_EXAMPLE" ]] || fail "Не найден $CONFIG_EXAMPLE"
|
||||||
@@ -69,6 +145,9 @@ log "ПРОВЕРКА ФАЙЛОВ ПРОЕКТА"
|
|||||||
[[ -f "$PROJECT_ROOT/src/database.py" ]] || fail "Не найден src/database.py"
|
[[ -f "$PROJECT_ROOT/src/database.py" ]] || fail "Не найден src/database.py"
|
||||||
[[ -f "$PROJECT_ROOT/cracklab/server/db/migrations.py" ]] || fail "Не найдены миграции CrackLab"
|
[[ -f "$PROJECT_ROOT/cracklab/server/db/migrations.py" ]] || fail "Не найдены миграции CrackLab"
|
||||||
|
|
||||||
|
log "ПРОВЕРКА СИСТЕМНЫХ ЗАВИСИМОСТЕЙ GPSRELAY"
|
||||||
|
install_gpsrelay_system_dependencies
|
||||||
|
|
||||||
log "ПОДГОТОВКА КАТАЛОГОВ ПРОЕКТА"
|
log "ПОДГОТОВКА КАТАЛОГОВ ПРОЕКТА"
|
||||||
|
|
||||||
prepare_directory() {
|
prepare_directory() {
|
||||||
@@ -155,6 +234,7 @@ log "УСТАНОВКА PYTHON-ЗАВИСИМОСТЕЙ"
|
|||||||
"$PYTHON" -m pip install -r "$PROJECT_ROOT/requirements.txt"
|
"$PYTHON" -m pip install -r "$PROJECT_ROOT/requirements.txt"
|
||||||
|
|
||||||
"$PYTHON" -c "import flask, yaml, pynmea2, scapy"
|
"$PYTHON" -c "import flask, yaml, pynmea2, scapy"
|
||||||
|
echo "[OK] Python-модуль pynmea2 доступен в виртуальном окружении."
|
||||||
|
|
||||||
log "ПОДГОТОВКА КОНФИГУРАЦИИ"
|
log "ПОДГОТОВКА КОНФИГУРАЦИИ"
|
||||||
|
|
||||||
|
|||||||
@@ -786,6 +786,14 @@ def generate_dashboard(
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# --------------------------------------------------------
|
||||||
|
# Recovery
|
||||||
|
# --------------------------------------------------------
|
||||||
|
|
||||||
|
html += recovery_block(
|
||||||
|
conn
|
||||||
|
)
|
||||||
|
|
||||||
# --------------------------------------------------------
|
# --------------------------------------------------------
|
||||||
# Sessions
|
# Sessions
|
||||||
# --------------------------------------------------------
|
# --------------------------------------------------------
|
||||||
@@ -795,14 +803,6 @@ def generate_dashboard(
|
|||||||
context,
|
context,
|
||||||
)
|
)
|
||||||
|
|
||||||
# --------------------------------------------------------
|
|
||||||
# Recovery
|
|
||||||
# --------------------------------------------------------
|
|
||||||
|
|
||||||
html += recovery_block(
|
|
||||||
conn
|
|
||||||
)
|
|
||||||
|
|
||||||
# --------------------------------------------------------
|
# --------------------------------------------------------
|
||||||
# Footer
|
# Footer
|
||||||
# --------------------------------------------------------
|
# --------------------------------------------------------
|
||||||
|
|||||||
+252
-5
@@ -2,13 +2,60 @@ from datetime import datetime, timedelta, timezone
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from scapy.all import PcapNgReader
|
||||||
|
|
||||||
from .config import CAPTURES_DIR, get_timezone
|
from .config import CAPTURES_DIR, get_timezone
|
||||||
from .template import card
|
from .template import card
|
||||||
from .utils import esc
|
from .utils import esc
|
||||||
|
|
||||||
|
|
||||||
|
def _capture_duration_seconds(capture_file):
|
||||||
|
reader = None
|
||||||
|
first_timestamp = None
|
||||||
|
last_timestamp = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
reader = PcapNgReader(str(capture_file))
|
||||||
|
|
||||||
|
for packet in reader:
|
||||||
|
try:
|
||||||
|
timestamp = float(packet.time)
|
||||||
|
except (AttributeError, TypeError, ValueError, OverflowError):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if first_timestamp is None or timestamp < first_timestamp:
|
||||||
|
first_timestamp = timestamp
|
||||||
|
|
||||||
|
if last_timestamp is None or timestamp > last_timestamp:
|
||||||
|
last_timestamp = timestamp
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if reader is not None:
|
||||||
|
reader.close()
|
||||||
|
|
||||||
|
if first_timestamp is None or last_timestamp is None:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
return max(0, last_timestamp - first_timestamp)
|
||||||
|
|
||||||
|
|
||||||
|
def _has_recoverable_capture(session_dir):
|
||||||
|
minimum_duration = MIN_RECOVERY_DURATION.total_seconds()
|
||||||
|
|
||||||
|
return (
|
||||||
|
_capture_duration_seconds(
|
||||||
|
session_dir / "capture.pcapng"
|
||||||
|
) >= minimum_duration
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
MIN_RECOVERY_DURATION = timedelta(minutes=5)
|
||||||
|
|
||||||
|
|
||||||
MIN_STALE_AGE = timedelta(minutes=15)
|
MIN_STALE_AGE = timedelta(minutes=15)
|
||||||
MAX_STALE_AGE = timedelta(hours=24)
|
|
||||||
|
|
||||||
SESSION_FILES = (
|
SESSION_FILES = (
|
||||||
"capture.pcapng",
|
"capture.pcapng",
|
||||||
@@ -42,9 +89,7 @@ def _file_is_stale(path, now):
|
|||||||
|
|
||||||
age = now - modified
|
age = now - modified
|
||||||
|
|
||||||
return (
|
return age >= MIN_STALE_AGE
|
||||||
MIN_STALE_AGE <= age <= MAX_STALE_AGE
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _capture_is_interrupted(path, end_time, now):
|
def _capture_is_interrupted(path, end_time, now):
|
||||||
@@ -106,6 +151,32 @@ def _parser_was_interrupted(parser_log):
|
|||||||
return last_started >= 0 and last_started > last_finished
|
return last_started >= 0 and last_started > last_finished
|
||||||
|
|
||||||
|
|
||||||
|
def _parser_was_completed(parser_log):
|
||||||
|
last_started = -1
|
||||||
|
last_finished = -1
|
||||||
|
|
||||||
|
try:
|
||||||
|
with parser_log.open(
|
||||||
|
"r",
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
) as file:
|
||||||
|
for index, line in enumerate(file):
|
||||||
|
if "Parser started" in line:
|
||||||
|
last_started = index
|
||||||
|
|
||||||
|
if "Parser finished" in line:
|
||||||
|
last_finished = index
|
||||||
|
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return (
|
||||||
|
last_started >= 0
|
||||||
|
and last_finished > last_started
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _session_counts(conn, session_id):
|
def _session_counts(conn, session_id):
|
||||||
counts = {}
|
counts = {}
|
||||||
|
|
||||||
@@ -179,6 +250,34 @@ def _collect_files(session_dir):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _session_sources_are_stale(session_dir, now):
|
||||||
|
source_paths = [
|
||||||
|
session_dir / filename
|
||||||
|
for filename in SESSION_FILES
|
||||||
|
]
|
||||||
|
|
||||||
|
existing_paths = []
|
||||||
|
|
||||||
|
for source_path in source_paths:
|
||||||
|
try:
|
||||||
|
if source_path.is_file():
|
||||||
|
existing_paths.append(source_path.stat().st_mtime)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not existing_paths:
|
||||||
|
return False
|
||||||
|
|
||||||
|
latest_modified = max(existing_paths)
|
||||||
|
|
||||||
|
modified = datetime.fromtimestamp(
|
||||||
|
latest_modified,
|
||||||
|
tz=timezone.utc,
|
||||||
|
)
|
||||||
|
|
||||||
|
return now - modified >= MIN_STALE_AGE
|
||||||
|
|
||||||
|
|
||||||
def find_recovery_candidates(
|
def find_recovery_candidates(
|
||||||
conn,
|
conn,
|
||||||
captures_dir=None,
|
captures_dir=None,
|
||||||
@@ -209,6 +308,7 @@ def find_recovery_candidates(
|
|||||||
""").fetchall()
|
""").fetchall()
|
||||||
|
|
||||||
candidates = []
|
candidates = []
|
||||||
|
known_session_dirs = set()
|
||||||
|
|
||||||
for row in rows:
|
for row in rows:
|
||||||
session_id = row[0]
|
session_id = row[0]
|
||||||
@@ -224,9 +324,19 @@ def find_recovery_candidates(
|
|||||||
if session_dir is None or not session_dir.is_dir():
|
if session_dir is None or not session_dir.is_dir():
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
known_session_dirs.add(
|
||||||
|
session_dir.resolve()
|
||||||
|
)
|
||||||
|
|
||||||
capture_path = session_dir / "capture.pcapng"
|
capture_path = session_dir / "capture.pcapng"
|
||||||
parser_log = session_dir / "parser.log"
|
parser_log = session_dir / "parser.log"
|
||||||
|
|
||||||
|
if (
|
||||||
|
parser_log.is_file()
|
||||||
|
and _parser_was_completed(parser_log)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
capture_interrupted = _capture_is_interrupted(
|
capture_interrupted = _capture_is_interrupted(
|
||||||
capture_path,
|
capture_path,
|
||||||
end_time,
|
end_time,
|
||||||
@@ -247,6 +357,9 @@ def find_recovery_candidates(
|
|||||||
session_id,
|
session_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if not _has_recoverable_capture(session_dir):
|
||||||
|
continue
|
||||||
|
|
||||||
reasons = []
|
reasons = []
|
||||||
|
|
||||||
if capture_interrupted:
|
if capture_interrupted:
|
||||||
@@ -295,6 +408,81 @@ def find_recovery_candidates(
|
|||||||
),
|
),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
captures_root = Path(captures_dir).resolve()
|
||||||
|
|
||||||
|
try:
|
||||||
|
session_directories = captures_root.iterdir()
|
||||||
|
except OSError:
|
||||||
|
session_directories = ()
|
||||||
|
|
||||||
|
for entry in session_directories:
|
||||||
|
if not entry.is_dir():
|
||||||
|
continue
|
||||||
|
|
||||||
|
session_dir = entry.resolve()
|
||||||
|
|
||||||
|
if session_dir.parent != captures_root:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if session_dir in known_session_dirs:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
start_time = datetime.strptime(
|
||||||
|
session_dir.name,
|
||||||
|
"%Y%m%d_%H%M%S",
|
||||||
|
).replace(
|
||||||
|
tzinfo=timezone.utc
|
||||||
|
)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
parser_log = session_dir / "parser.log"
|
||||||
|
|
||||||
|
if (
|
||||||
|
parser_log.is_file()
|
||||||
|
and _parser_was_completed(parser_log)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not _session_sources_are_stale(
|
||||||
|
session_dir,
|
||||||
|
now,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not _has_recoverable_capture(session_dir):
|
||||||
|
continue
|
||||||
|
|
||||||
|
candidates.append({
|
||||||
|
"id": None,
|
||||||
|
"title": (
|
||||||
|
f"Каталог {session_dir.name} "
|
||||||
|
"(запись в БД отсутствует)"
|
||||||
|
),
|
||||||
|
"session_dir": str(session_dir),
|
||||||
|
"start_time": _format_datetime(
|
||||||
|
start_time.isoformat(),
|
||||||
|
display_timezone,
|
||||||
|
),
|
||||||
|
"kind": "capture",
|
||||||
|
"counts": {
|
||||||
|
"gps": 0,
|
||||||
|
"access_points": 0,
|
||||||
|
"handshakes": 0,
|
||||||
|
},
|
||||||
|
"files": _collect_files(session_dir),
|
||||||
|
"reasons": [
|
||||||
|
"Найдены исходные файлы поездки, "
|
||||||
|
"которые не обновлялись более 15 минут. "
|
||||||
|
"Запись этой поездки в capture_sessions отсутствует."
|
||||||
|
],
|
||||||
|
"actions": (
|
||||||
|
"Проверить исходные файлы и восстановить "
|
||||||
|
"запись поездки в базе данных."
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
return candidates
|
return candidates
|
||||||
|
|
||||||
|
|
||||||
@@ -309,6 +497,11 @@ def recovery_block(conn):
|
|||||||
for candidate in candidates:
|
for candidate in candidates:
|
||||||
counts = candidate["counts"]
|
counts = candidate["counts"]
|
||||||
|
|
||||||
|
title = candidate.get(
|
||||||
|
"title",
|
||||||
|
f"Поездка #{candidate['id']}",
|
||||||
|
)
|
||||||
|
|
||||||
files_html = "".join(
|
files_html = "".join(
|
||||||
"<li>{} — {} байт</li>".format(
|
"<li>{} — {} байт</li>".format(
|
||||||
esc(item["name"]),
|
esc(item["name"]),
|
||||||
@@ -322,9 +515,61 @@ def recovery_block(conn):
|
|||||||
for reason in candidate["reasons"]
|
for reason in candidate["reasons"]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
recovery_html = ""
|
||||||
|
|
||||||
|
if candidate.get("id") is None:
|
||||||
|
|
||||||
|
directory_name = Path(
|
||||||
|
candidate["session_dir"]
|
||||||
|
).name
|
||||||
|
|
||||||
|
recovery_html = f"""
|
||||||
|
<form method="post"
|
||||||
|
action="/reports/recovery/{esc(directory_name)}">
|
||||||
|
<button type="submit" class="button">
|
||||||
|
Восстановить поездку
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Если восстановление не требуется, каталог можно удалить вручную:
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p class="recovery-directory">
|
||||||
|
<code>{esc(candidate["session_dir"])}</code>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="recovery-copy-button"
|
||||||
|
data-copy-path="{esc(candidate["session_dir"])}"
|
||||||
|
onclick="copyRecoveryPath(this)"
|
||||||
|
title="Копировать путь"
|
||||||
|
aria-label="Копировать путь"
|
||||||
|
><svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="1.8"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<rect x="8" y="8" width="13" height="13" rx="2"/>
|
||||||
|
<path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>
|
||||||
|
</svg></button>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Удаление безвозвратно уничтожит файлы поездки.
|
||||||
|
Приложение автоматически файлы не удаляет.
|
||||||
|
</p>
|
||||||
|
"""
|
||||||
|
|
||||||
html.append(f"""
|
html.append(f"""
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>Поездка #{candidate["id"]}</h3>
|
<h3>{esc(title)}</h3>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
<strong>Дата начала:</strong>
|
<strong>Дата начала:</strong>
|
||||||
@@ -357,6 +602,8 @@ def recovery_block(conn):
|
|||||||
<strong>Возможное дальнейшее действие:</strong>
|
<strong>Возможное дальнейшее действие:</strong>
|
||||||
{esc(candidate["actions"])}
|
{esc(candidate["actions"])}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
{recovery_html}
|
||||||
</div>
|
</div>
|
||||||
""")
|
""")
|
||||||
|
|
||||||
|
|||||||
@@ -1916,3 +1916,32 @@ body .maplibregl-popup-close-button:hover {
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.recovery-directory {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recovery-directory code {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recovery-copy-button {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 32px;
|
||||||
|
min-height: 32px;
|
||||||
|
padding: 4px 7px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--text);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recovery-copy-button:hover {
|
||||||
|
border-color: var(--accent);
|
||||||
|
}
|
||||||
|
|||||||
@@ -199,6 +199,40 @@ function filterTable(id,value)
|
|||||||
}}
|
}}
|
||||||
}}
|
}}
|
||||||
|
|
||||||
|
async function copyRecoveryPath(button)
|
||||||
|
{{
|
||||||
|
const path = button.dataset.copyPath;
|
||||||
|
|
||||||
|
if (!path)
|
||||||
|
return;
|
||||||
|
|
||||||
|
const originalHTML = button.innerHTML;
|
||||||
|
|
||||||
|
try
|
||||||
|
{{
|
||||||
|
if (!navigator.clipboard || !navigator.clipboard.writeText)
|
||||||
|
throw new Error("Clipboard API unavailable");
|
||||||
|
|
||||||
|
await navigator.clipboard.writeText(path);
|
||||||
|
|
||||||
|
button.textContent = "✓";
|
||||||
|
|
||||||
|
setTimeout(() =>
|
||||||
|
{{
|
||||||
|
button.innerHTML = originalHTML;
|
||||||
|
}}, 1500);
|
||||||
|
}}
|
||||||
|
catch (error)
|
||||||
|
{{
|
||||||
|
button.textContent = "✕";
|
||||||
|
|
||||||
|
setTimeout(() =>
|
||||||
|
{{
|
||||||
|
button.innerHTML = originalHTML;
|
||||||
|
}}, 2000);
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
|
||||||
async function copyMapCoordinates(button)
|
async function copyMapCoordinates(button)
|
||||||
{{
|
{{
|
||||||
const coordinates = button.dataset.coordinates;
|
const coordinates = button.dataset.coordinates;
|
||||||
|
|||||||
+12
-1
@@ -211,7 +211,18 @@ class AutoGPSService:
|
|||||||
logger.info
|
logger.info
|
||||||
)
|
)
|
||||||
|
|
||||||
log_method(message)
|
if code in (
|
||||||
|
"GPS_STARTED",
|
||||||
|
"GPS_CONNECTED",
|
||||||
|
"GPS_CONNECTION_LOST",
|
||||||
|
"GPS_SERVICE_ERROR",
|
||||||
|
"GPS_STOPPED",
|
||||||
|
):
|
||||||
|
log_method(
|
||||||
|
"%s: %s",
|
||||||
|
code,
|
||||||
|
message
|
||||||
|
)
|
||||||
|
|
||||||
if self.callback is not None:
|
if self.callback is not None:
|
||||||
try:
|
try:
|
||||||
|
|||||||
+296
-62
@@ -13,6 +13,7 @@ from auto_gps import AutoGPSService
|
|||||||
from wifi_connection import (
|
from wifi_connection import (
|
||||||
APNotFoundError,
|
APNotFoundError,
|
||||||
NetworkCleanupError,
|
NetworkCleanupError,
|
||||||
|
NetworkCommandCancelled,
|
||||||
NetworkCommandError,
|
NetworkCommandError,
|
||||||
NetworkRestoreError,
|
NetworkRestoreError,
|
||||||
WiFiConnectionError
|
WiFiConnectionError
|
||||||
@@ -23,6 +24,14 @@ logger = logging.getLogger(
|
|||||||
"wifi-gps-mapper.auto-verification"
|
"wifi-gps-mapper.auto-verification"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
LOGGED_MONITOR_EVENTS = frozenset({
|
||||||
|
"STATE",
|
||||||
|
"RADIUS_UPDATED",
|
||||||
|
"SERVICE_STARTED",
|
||||||
|
"AP_MISSING_FROM_SCAN",
|
||||||
|
"SERVICE_STOPPED",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
def _utc_now():
|
def _utc_now():
|
||||||
return datetime.now(
|
return datetime.now(
|
||||||
@@ -97,10 +106,47 @@ class AutoWiFiVerificationService:
|
|||||||
callback=None,
|
callback=None,
|
||||||
acquire_network_owner=None,
|
acquire_network_owner=None,
|
||||||
release_network_owner=None,
|
release_network_owner=None,
|
||||||
gps_service=None
|
gps_service=None,
|
||||||
|
mode="AUTO",
|
||||||
|
manual_center=None
|
||||||
):
|
):
|
||||||
self.settings = dict(settings or {})
|
self.settings = dict(settings or {})
|
||||||
self.interface = interface
|
self.interface = interface
|
||||||
|
|
||||||
|
self.verification_mode = str(mode or "AUTO").upper()
|
||||||
|
|
||||||
|
if self.verification_mode not in ("AUTO", "MANUAL"):
|
||||||
|
raise ValueError("Invalid verification mode.")
|
||||||
|
|
||||||
|
self.manual_center = None
|
||||||
|
|
||||||
|
if self.verification_mode == "MANUAL":
|
||||||
|
if (
|
||||||
|
not isinstance(manual_center, (tuple, list))
|
||||||
|
or len(manual_center) != 2
|
||||||
|
or any(type(value) is bool for value in manual_center)
|
||||||
|
):
|
||||||
|
raise ValueError("Manual center coordinates are required.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
latitude = float(manual_center[0])
|
||||||
|
longitude = float(manual_center[1])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("Invalid manual center coordinates.")
|
||||||
|
|
||||||
|
if not (
|
||||||
|
-90 <= latitude <= 90
|
||||||
|
and -180 <= longitude <= 180
|
||||||
|
):
|
||||||
|
raise ValueError("Manual center coordinates are out of range.")
|
||||||
|
|
||||||
|
self.manual_center = (latitude, longitude)
|
||||||
|
|
||||||
|
self.network_owner = (
|
||||||
|
"MANUAL_WIFI_VERIFY"
|
||||||
|
if self.verification_mode == "MANUAL"
|
||||||
|
else "AUTO_WIFI_VERIFY"
|
||||||
|
)
|
||||||
self.wifi_connection_service = wifi_connection_service
|
self.wifi_connection_service = wifi_connection_service
|
||||||
self.callback = callback
|
self.callback = callback
|
||||||
self.acquire_network_owner = acquire_network_owner
|
self.acquire_network_owner = acquire_network_owner
|
||||||
@@ -127,9 +173,14 @@ class AutoWiFiVerificationService:
|
|||||||
self._pending_radius_update = None
|
self._pending_radius_update = None
|
||||||
self._radius_update_event = threading.Event()
|
self._radius_update_event = threading.Event()
|
||||||
|
|
||||||
self.manage_gps_service = gps_service is None
|
self.manage_gps_service = (
|
||||||
|
gps_service is None
|
||||||
|
and self.verification_mode == "AUTO"
|
||||||
|
)
|
||||||
|
|
||||||
if gps_service is None:
|
if self.verification_mode == "MANUAL":
|
||||||
|
self.gps_service = None
|
||||||
|
elif gps_service is None:
|
||||||
self.gps_service = AutoGPSService(
|
self.gps_service = AutoGPSService(
|
||||||
self.settings,
|
self.settings,
|
||||||
callback=self._gps_callback,
|
callback=self._gps_callback,
|
||||||
@@ -180,6 +231,9 @@ class AutoWiFiVerificationService:
|
|||||||
self._notify()
|
self._notify()
|
||||||
|
|
||||||
def _gps_fix_callback(self, gps):
|
def _gps_fix_callback(self, gps):
|
||||||
|
if self.verification_mode != "AUTO":
|
||||||
|
return
|
||||||
|
|
||||||
with self._gps_fix_condition:
|
with self._gps_fix_condition:
|
||||||
self._gps_fix_generation += 1
|
self._gps_fix_generation += 1
|
||||||
self._gps_fix_condition.notify_all()
|
self._gps_fix_condition.notify_all()
|
||||||
@@ -227,6 +281,18 @@ class AutoWiFiVerificationService:
|
|||||||
-self.monitor_event_limit:
|
-self.monitor_event_limit:
|
||||||
]
|
]
|
||||||
|
|
||||||
|
if event in LOGGED_MONITOR_EVENTS:
|
||||||
|
log_method = getattr(
|
||||||
|
logger,
|
||||||
|
level.lower(),
|
||||||
|
logger.info
|
||||||
|
)
|
||||||
|
log_method(
|
||||||
|
"%s: %s",
|
||||||
|
event,
|
||||||
|
message
|
||||||
|
)
|
||||||
|
|
||||||
def _update_monitor_candidates(self, candidates):
|
def _update_monitor_candidates(self, candidates):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
strengths = {
|
strengths = {
|
||||||
@@ -288,6 +354,20 @@ class AutoWiFiVerificationService:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _sort_work_queue_by_signal(self, work_queue):
|
||||||
|
with self.lock:
|
||||||
|
strengths = {
|
||||||
|
candidate["bssid"].lower(): candidate["strength"]
|
||||||
|
for candidate in self.monitor_candidates
|
||||||
|
}
|
||||||
|
|
||||||
|
work_queue.sort(
|
||||||
|
key=lambda job: (
|
||||||
|
strengths.get(job[1].lower()) is None,
|
||||||
|
-(strengths.get(job[1].lower()) or 0)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
def _update_monitor_queue(self, work_queue):
|
def _update_monitor_queue(self, work_queue):
|
||||||
grouped = {}
|
grouped = {}
|
||||||
|
|
||||||
@@ -320,7 +400,11 @@ class AutoWiFiVerificationService:
|
|||||||
|
|
||||||
def get_status(self):
|
def get_status(self):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
gps_status = self.gps_service.get_status()
|
gps_status = (
|
||||||
|
self.gps_service.get_status()
|
||||||
|
if self.gps_service is not None
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"running": self.running,
|
"running": self.running,
|
||||||
@@ -328,6 +412,8 @@ class AutoWiFiVerificationService:
|
|||||||
"error": self.error,
|
"error": self.error,
|
||||||
"session_id": self.session_id,
|
"session_id": self.session_id,
|
||||||
"interface": self.interface,
|
"interface": self.interface,
|
||||||
|
"verification_mode": self.verification_mode,
|
||||||
|
"manual_center": self.manual_center,
|
||||||
"radius_m": self.radius_m,
|
"radius_m": self.radius_m,
|
||||||
"gps": gps_status,
|
"gps": gps_status,
|
||||||
"access_points_total": self.access_points_total,
|
"access_points_total": self.access_points_total,
|
||||||
@@ -375,7 +461,7 @@ class AutoWiFiVerificationService:
|
|||||||
|
|
||||||
if self.acquire_network_owner is not None:
|
if self.acquire_network_owner is not None:
|
||||||
acquired, error = self.acquire_network_owner(
|
acquired, error = self.acquire_network_owner(
|
||||||
"AUTO_WIFI_VERIFY"
|
self.network_owner
|
||||||
)
|
)
|
||||||
|
|
||||||
if not acquired:
|
if not acquired:
|
||||||
@@ -386,9 +472,17 @@ class AutoWiFiVerificationService:
|
|||||||
self.network_owner_acquired = True
|
self.network_owner_acquired = True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
self.wifi_connection_service.disconnect_active_connection(
|
||||||
|
self.interface
|
||||||
|
)
|
||||||
|
|
||||||
gps_generation = 0
|
gps_generation = 0
|
||||||
|
|
||||||
if not self.manage_gps_service:
|
if (
|
||||||
|
self.verification_mode == "AUTO"
|
||||||
|
and not self.manage_gps_service
|
||||||
|
and self.gps_service is not None
|
||||||
|
):
|
||||||
gps_status = self.gps_service.get_status()
|
gps_status = self.gps_service.get_status()
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -406,13 +500,23 @@ class AutoWiFiVerificationService:
|
|||||||
self.stop_event.clear()
|
self.stop_event.clear()
|
||||||
|
|
||||||
with self._gps_fix_condition:
|
with self._gps_fix_condition:
|
||||||
self._gps_fix_generation = gps_generation
|
if (
|
||||||
self._gps_fix_consumed_generation = 0
|
gps_generation
|
||||||
|
and self._gps_fix_generation
|
||||||
|
<= self._gps_fix_consumed_generation
|
||||||
|
):
|
||||||
|
self._gps_fix_generation = (
|
||||||
|
self._gps_fix_consumed_generation + 1
|
||||||
|
)
|
||||||
|
|
||||||
self._bssid_states.clear()
|
self._bssid_states.clear()
|
||||||
self._missing_scan_bssids.clear()
|
self._missing_scan_bssids.clear()
|
||||||
self.running = True
|
self.running = True
|
||||||
self.state = "WAITING_GPS"
|
self.state = (
|
||||||
|
"WAITING_GPS"
|
||||||
|
if self.verification_mode == "AUTO"
|
||||||
|
else "STARTING"
|
||||||
|
)
|
||||||
self.error = None
|
self.error = None
|
||||||
|
|
||||||
self.thread = threading.Thread(
|
self.thread = threading.Thread(
|
||||||
@@ -450,11 +554,11 @@ class AutoWiFiVerificationService:
|
|||||||
|
|
||||||
if self.release_network_owner is None:
|
if self.release_network_owner is None:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"AUTO_WIFI_VERIFY network owner cannot be released: "
|
f"{self.network_owner} network owner cannot be released: "
|
||||||
"release callback is not configured."
|
"release callback is not configured."
|
||||||
)
|
)
|
||||||
|
|
||||||
self.release_network_owner("AUTO_WIFI_VERIFY")
|
self.release_network_owner(self.network_owner)
|
||||||
|
|
||||||
with self.lock:
|
with self.lock:
|
||||||
self.network_owner_acquired = False
|
self.network_owner_acquired = False
|
||||||
@@ -481,7 +585,7 @@ class AutoWiFiVerificationService:
|
|||||||
and thread.is_alive()
|
and thread.is_alive()
|
||||||
and thread is not threading.current_thread()
|
and thread is not threading.current_thread()
|
||||||
):
|
):
|
||||||
thread.join(timeout=15)
|
thread.join()
|
||||||
|
|
||||||
self._notify()
|
self._notify()
|
||||||
|
|
||||||
@@ -594,11 +698,12 @@ class AutoWiFiVerificationService:
|
|||||||
error_code,
|
error_code,
|
||||||
error_message
|
error_message
|
||||||
)
|
)
|
||||||
VALUES (?, ?, 'AUTO', ?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
credential_id,
|
credential_id,
|
||||||
self.session_id,
|
self.session_id,
|
||||||
|
self.verification_mode,
|
||||||
status,
|
status,
|
||||||
_utc_now(),
|
_utc_now(),
|
||||||
_utc_now(),
|
_utc_now(),
|
||||||
@@ -639,6 +744,27 @@ class AutoWiFiVerificationService:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
attempt_log = (
|
||||||
|
logger.info
|
||||||
|
if status == "SUCCESS"
|
||||||
|
else logger.warning
|
||||||
|
if status in ("INVALID_PASSWORD", "AP_NOT_FOUND")
|
||||||
|
else logger.error
|
||||||
|
)
|
||||||
|
|
||||||
|
attempt_log(
|
||||||
|
"Wi-Fi verification attempt: "
|
||||||
|
"session_id=%s mode=%s interface=%s "
|
||||||
|
"bssid=%s credential_id=%s status=%s error_code=%s",
|
||||||
|
self.session_id,
|
||||||
|
self.verification_mode,
|
||||||
|
self.interface,
|
||||||
|
bssid,
|
||||||
|
credential_id,
|
||||||
|
status,
|
||||||
|
error_code or "-"
|
||||||
|
)
|
||||||
|
|
||||||
self._update_session_counters(connection)
|
self._update_session_counters(connection)
|
||||||
|
|
||||||
def _update_session_counters(self, connection):
|
def _update_session_counters(self, connection):
|
||||||
@@ -672,6 +798,9 @@ class AutoWiFiVerificationService:
|
|||||||
connection.commit()
|
connection.commit()
|
||||||
|
|
||||||
def _get_gps_fix(self):
|
def _get_gps_fix(self):
|
||||||
|
if self.gps_service is None:
|
||||||
|
return None
|
||||||
|
|
||||||
status = self.gps_service.get_status()
|
status = self.gps_service.get_status()
|
||||||
|
|
||||||
if not status.get("has_fresh_fix"):
|
if not status.get("has_fresh_fix"):
|
||||||
@@ -818,7 +947,11 @@ class AutoWiFiVerificationService:
|
|||||||
if command is None:
|
if command is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
self._set_state("WAITING_GPS")
|
self._set_state(
|
||||||
|
"WAITING_GPS"
|
||||||
|
if self.verification_mode == "AUTO"
|
||||||
|
else "RUNNING"
|
||||||
|
)
|
||||||
|
|
||||||
while not self.stop_event.is_set():
|
while not self.stop_event.is_set():
|
||||||
with self._radius_update_lock:
|
with self._radius_update_lock:
|
||||||
@@ -829,27 +962,31 @@ class AutoWiFiVerificationService:
|
|||||||
|
|
||||||
after_generation = command["after_generation"]
|
after_generation = command["after_generation"]
|
||||||
|
|
||||||
with self._gps_fix_condition:
|
if self.verification_mode == "MANUAL":
|
||||||
generation = self._gps_fix_generation
|
generation = after_generation
|
||||||
|
fix = self.manual_center
|
||||||
|
else:
|
||||||
|
with self._gps_fix_condition:
|
||||||
|
generation = self._gps_fix_generation
|
||||||
|
|
||||||
|
if generation <= after_generation:
|
||||||
|
self._gps_fix_condition.wait()
|
||||||
|
continue
|
||||||
|
|
||||||
|
self._gps_fix_consumed_generation = max(
|
||||||
|
self._gps_fix_consumed_generation,
|
||||||
|
generation
|
||||||
|
)
|
||||||
|
|
||||||
|
fix = self._get_gps_fix()
|
||||||
|
|
||||||
|
if fix is None:
|
||||||
|
with self._radius_update_lock:
|
||||||
|
if self._pending_radius_update is command:
|
||||||
|
command["after_generation"] = generation
|
||||||
|
|
||||||
if generation <= after_generation:
|
|
||||||
self._gps_fix_condition.wait()
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
self._gps_fix_consumed_generation = max(
|
|
||||||
self._gps_fix_consumed_generation,
|
|
||||||
generation
|
|
||||||
)
|
|
||||||
|
|
||||||
fix = self._get_gps_fix()
|
|
||||||
|
|
||||||
if fix is None:
|
|
||||||
with self._radius_update_lock:
|
|
||||||
if self._pending_radius_update is command:
|
|
||||||
command["after_generation"] = generation
|
|
||||||
|
|
||||||
continue
|
|
||||||
|
|
||||||
with self._radius_update_lock:
|
with self._radius_update_lock:
|
||||||
if self._pending_radius_update is not command:
|
if self._pending_radius_update is not command:
|
||||||
break
|
break
|
||||||
@@ -988,11 +1125,15 @@ class AutoWiFiVerificationService:
|
|||||||
self.interface,
|
self.interface,
|
||||||
bssid,
|
bssid,
|
||||||
password,
|
password,
|
||||||
restore_connection=True,
|
restore_connection=False,
|
||||||
keep_profile=False,
|
keep_profile=False,
|
||||||
access_point=access_point["scan_result"]
|
access_point=access_point["scan_result"],
|
||||||
|
cancel_event=self.stop_event
|
||||||
)
|
)
|
||||||
|
|
||||||
|
except NetworkCommandCancelled:
|
||||||
|
raise
|
||||||
|
|
||||||
except APNotFoundError as error:
|
except APNotFoundError as error:
|
||||||
self._record_attempt(
|
self._record_attempt(
|
||||||
connection,
|
connection,
|
||||||
@@ -1250,7 +1391,6 @@ class AutoWiFiVerificationService:
|
|||||||
|
|
||||||
elif outcome == "AP_NOT_FOUND":
|
elif outcome == "AP_NOT_FOUND":
|
||||||
result["ap_not_found"] = True
|
result["ap_not_found"] = True
|
||||||
retry_queue.append(job)
|
|
||||||
|
|
||||||
elif outcome in ("INVALID_PASSWORD", "TECHNICAL_ERROR"):
|
elif outcome in ("INVALID_PASSWORD", "TECHNICAL_ERROR"):
|
||||||
retry_queue.append(job)
|
retry_queue.append(job)
|
||||||
@@ -1278,11 +1418,74 @@ class AutoWiFiVerificationService:
|
|||||||
# (access_point_id, bssid, essid, credential, retry_count)
|
# (access_point_id, bssid, essid, credential, retry_count)
|
||||||
work_queue = []
|
work_queue = []
|
||||||
|
|
||||||
|
if self.verification_mode == "MANUAL":
|
||||||
|
candidates = self._get_candidates(
|
||||||
|
connection,
|
||||||
|
self.manual_center
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.lock:
|
||||||
|
self.access_points_total = len(candidates)
|
||||||
|
|
||||||
|
self._update_monitor_candidates(candidates)
|
||||||
|
|
||||||
|
self._add_monitor_event(
|
||||||
|
"CANDIDATES_REFRESHED",
|
||||||
|
f"Обновлён список кандидатов: {len(candidates)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
for access_point in candidates:
|
||||||
|
bssid = access_point["bssid"]
|
||||||
|
bssid_key = bssid.lower()
|
||||||
|
|
||||||
|
state = self._bssid_states.setdefault(
|
||||||
|
bssid_key,
|
||||||
|
{
|
||||||
|
"status": "NEW",
|
||||||
|
"processed_credentials": set()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if state["status"] == "VERIFIED":
|
||||||
|
continue
|
||||||
|
|
||||||
|
for credential in access_point["credentials"]:
|
||||||
|
credential_id = credential["credential_id"]
|
||||||
|
|
||||||
|
if credential_id in state["processed_credentials"]:
|
||||||
|
continue
|
||||||
|
|
||||||
|
work_queue.append(
|
||||||
|
(
|
||||||
|
access_point["access_point_id"],
|
||||||
|
bssid,
|
||||||
|
access_point["essid"],
|
||||||
|
credential,
|
||||||
|
0
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if access_point["credentials"]:
|
||||||
|
state["status"] = "QUEUED"
|
||||||
|
|
||||||
|
self._add_monitor_event(
|
||||||
|
"MANUAL_CENTER_SET",
|
||||||
|
(
|
||||||
|
"Центр ручной проверки: "
|
||||||
|
f"{self.manual_center[0]:.6f}, "
|
||||||
|
f"{self.manual_center[1]:.6f}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
self._update_monitor_queue(work_queue)
|
self._update_monitor_queue(work_queue)
|
||||||
self._set_monitor_active()
|
self._set_monitor_active()
|
||||||
self._add_monitor_event(
|
self._add_monitor_event(
|
||||||
"SERVICE_STARTED",
|
"SERVICE_STARTED",
|
||||||
"Сервис автоматической проверки запущен"
|
(
|
||||||
|
"Сервис ручной проверки запущен"
|
||||||
|
if self.verification_mode == "MANUAL"
|
||||||
|
else "Сервис автоматической проверки запущен"
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
gps_refresh_deferred = False
|
gps_refresh_deferred = False
|
||||||
@@ -1297,16 +1500,17 @@ class AutoWiFiVerificationService:
|
|||||||
|
|
||||||
gps_update = False
|
gps_update = False
|
||||||
|
|
||||||
# Забираем последнее необработанное GPS-поколение.
|
# GPS-поколения используются только в Auto.
|
||||||
with self._gps_fix_condition:
|
if self.verification_mode == "AUTO":
|
||||||
if (
|
with self._gps_fix_condition:
|
||||||
self._gps_fix_generation
|
if (
|
||||||
> self._gps_fix_consumed_generation
|
|
||||||
):
|
|
||||||
self._gps_fix_consumed_generation = (
|
|
||||||
self._gps_fix_generation
|
self._gps_fix_generation
|
||||||
)
|
> self._gps_fix_consumed_generation
|
||||||
gps_update = True
|
):
|
||||||
|
self._gps_fix_consumed_generation = (
|
||||||
|
self._gps_fix_generation
|
||||||
|
)
|
||||||
|
gps_update = True
|
||||||
|
|
||||||
# GPS FIX добавляет новые задания.
|
# GPS FIX добавляет новые задания.
|
||||||
# Потеря GPS не очищает существующую очередь.
|
# Потеря GPS не очищает существующую очередь.
|
||||||
@@ -1382,18 +1586,28 @@ class AutoWiFiVerificationService:
|
|||||||
if self.stop_event.is_set():
|
if self.stop_event.is_set():
|
||||||
break
|
break
|
||||||
|
|
||||||
# Пустая очередь — ожидаем новый GPS FIX.
|
# Пустая очередь: Auto ждёт GPS, Manual — изменения радиуса.
|
||||||
if not work_queue:
|
if not work_queue:
|
||||||
self._set_state("WAITING_GPS")
|
if self.verification_mode == "MANUAL":
|
||||||
|
self._set_state("WAITING_RADIUS")
|
||||||
|
|
||||||
with self._gps_fix_condition:
|
with self._gps_fix_condition:
|
||||||
while (
|
while (
|
||||||
not self.stop_event.is_set()
|
not self.stop_event.is_set()
|
||||||
and not self._radius_update_event.is_set()
|
and not self._radius_update_event.is_set()
|
||||||
and self._gps_fix_generation
|
):
|
||||||
<= self._gps_fix_consumed_generation
|
self._gps_fix_condition.wait()
|
||||||
):
|
else:
|
||||||
self._gps_fix_condition.wait()
|
self._set_state("WAITING_GPS")
|
||||||
|
|
||||||
|
with self._gps_fix_condition:
|
||||||
|
while (
|
||||||
|
not self.stop_event.is_set()
|
||||||
|
and not self._radius_update_event.is_set()
|
||||||
|
and self._gps_fix_generation
|
||||||
|
<= self._gps_fix_consumed_generation
|
||||||
|
):
|
||||||
|
self._gps_fix_condition.wait()
|
||||||
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -1413,11 +1627,12 @@ class AutoWiFiVerificationService:
|
|||||||
|
|
||||||
gps_update_pending = False
|
gps_update_pending = False
|
||||||
|
|
||||||
with self._gps_fix_condition:
|
if self.verification_mode == "AUTO":
|
||||||
gps_update_pending = (
|
with self._gps_fix_condition:
|
||||||
self._gps_fix_generation
|
gps_update_pending = (
|
||||||
> self._gps_fix_consumed_generation
|
self._gps_fix_generation
|
||||||
)
|
> self._gps_fix_consumed_generation
|
||||||
|
)
|
||||||
|
|
||||||
if gps_update_pending and not gps_refresh_deferred:
|
if gps_update_pending and not gps_refresh_deferred:
|
||||||
gps_refresh_deferred = True
|
gps_refresh_deferred = True
|
||||||
@@ -1453,6 +1668,7 @@ class AutoWiFiVerificationService:
|
|||||||
"warning"
|
"warning"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
self._sort_work_queue_by_signal(work_queue)
|
||||||
self._update_monitor_queue(work_queue)
|
self._update_monitor_queue(work_queue)
|
||||||
|
|
||||||
if self.stop_event.is_set():
|
if self.stop_event.is_set():
|
||||||
@@ -1583,6 +1799,19 @@ class AutoWiFiVerificationService:
|
|||||||
final_status = "STOPPED"
|
final_status = "STOPPED"
|
||||||
|
|
||||||
|
|
||||||
|
except NetworkCommandCancelled as error:
|
||||||
|
if self.stop_event.is_set():
|
||||||
|
final_status = "STOPPED"
|
||||||
|
else:
|
||||||
|
final_status = "ERROR"
|
||||||
|
self._set_state(
|
||||||
|
"ERROR",
|
||||||
|
str(error)
|
||||||
|
)
|
||||||
|
logger.exception(
|
||||||
|
"Wi-Fi verification was cancelled unexpectedly."
|
||||||
|
)
|
||||||
|
|
||||||
except (NetworkRestoreError, NetworkCleanupError) as error:
|
except (NetworkRestoreError, NetworkCleanupError) as error:
|
||||||
final_status = "ERROR"
|
final_status = "ERROR"
|
||||||
self._set_state(
|
self._set_state(
|
||||||
@@ -1600,7 +1829,8 @@ class AutoWiFiVerificationService:
|
|||||||
str(error)
|
str(error)
|
||||||
)
|
)
|
||||||
logger.exception(
|
logger.exception(
|
||||||
"Auto Wi-Fi verification failed."
|
"%s Wi-Fi verification failed.",
|
||||||
|
self.verification_mode.title()
|
||||||
)
|
)
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
@@ -1666,7 +1896,11 @@ class AutoWiFiVerificationService:
|
|||||||
(
|
(
|
||||||
"Сервис завершил работу с ошибкой"
|
"Сервис завершил работу с ошибкой"
|
||||||
if final_status == "ERROR"
|
if final_status == "ERROR"
|
||||||
else "Сервис автоматической проверки остановлен"
|
else (
|
||||||
|
"Сервис ручной проверки остановлен"
|
||||||
|
if self.verification_mode == "MANUAL"
|
||||||
|
else "Сервис автоматической проверки остановлен"
|
||||||
|
)
|
||||||
),
|
),
|
||||||
"error" if final_status == "ERROR" else "info"
|
"error" if final_status == "ERROR" else "info"
|
||||||
)
|
)
|
||||||
|
|||||||
+7
-4
@@ -1023,10 +1023,15 @@ class Database:
|
|||||||
|
|
||||||
def create_session(
|
def create_session(
|
||||||
self,
|
self,
|
||||||
capture_file
|
capture_file,
|
||||||
|
start_time=None
|
||||||
):
|
):
|
||||||
|
|
||||||
|
|
||||||
|
session_start = start_time or datetime.now(
|
||||||
|
timezone.utc
|
||||||
|
)
|
||||||
|
|
||||||
cursor = self.conn.execute(
|
cursor = self.conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO capture_sessions
|
INSERT INTO capture_sessions
|
||||||
@@ -1039,9 +1044,7 @@ class Database:
|
|||||||
""",
|
""",
|
||||||
|
|
||||||
(
|
(
|
||||||
datetime.now(
|
session_start.isoformat().replace(
|
||||||
timezone.utc
|
|
||||||
).isoformat().replace(
|
|
||||||
"+00:00",
|
"+00:00",
|
||||||
"Z"
|
"Z"
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1,642 @@
|
|||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pynmea2
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_PORT = 5000
|
||||||
|
|
||||||
|
IP_TIMEOUT_SECONDS = 5
|
||||||
|
NMAP_TIMEOUT_SECONDS = 35
|
||||||
|
NMEA_TIMEOUT_SECONDS = 5
|
||||||
|
|
||||||
|
MIN_VALID_NMEA_SENTENCES = 2
|
||||||
|
|
||||||
|
MAX_NETWORK_PREFIX_LENGTH = 16
|
||||||
|
MIN_NETWORK_PREFIX_LENGTH = 30
|
||||||
|
|
||||||
|
PRIVATE_IPV4_NETWORKS = (
|
||||||
|
ipaddress.ip_network("10.0.0.0/8"),
|
||||||
|
ipaddress.ip_network("172.16.0.0/12"),
|
||||||
|
ipaddress.ip_network("192.168.0.0/16"),
|
||||||
|
)
|
||||||
|
|
||||||
|
EXCLUDED_INTERFACE_PREFIXES = (
|
||||||
|
"lo",
|
||||||
|
"docker",
|
||||||
|
"br-",
|
||||||
|
"virbr",
|
||||||
|
"veth",
|
||||||
|
"tun",
|
||||||
|
"tap",
|
||||||
|
"wg",
|
||||||
|
"tailscale",
|
||||||
|
"podman",
|
||||||
|
"cni",
|
||||||
|
"flannel",
|
||||||
|
"zt",
|
||||||
|
"vmnet",
|
||||||
|
"vboxnet",
|
||||||
|
"dummy",
|
||||||
|
"ppp",
|
||||||
|
"sit",
|
||||||
|
"gre",
|
||||||
|
)
|
||||||
|
|
||||||
|
VALID_NMEA_TYPES = {
|
||||||
|
"GGA",
|
||||||
|
"GLL",
|
||||||
|
"GNS",
|
||||||
|
"GSA",
|
||||||
|
"GSV",
|
||||||
|
"RMC",
|
||||||
|
"VTG",
|
||||||
|
"ZDA",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class GPSRelayDiscoveryError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _require_tools():
|
||||||
|
|
||||||
|
packages = {
|
||||||
|
"ip": "iproute2",
|
||||||
|
"nmap": "nmap",
|
||||||
|
"nc": "netcat-openbsd",
|
||||||
|
}
|
||||||
|
|
||||||
|
missing = [
|
||||||
|
f"{tool} (пакет {package})"
|
||||||
|
for tool, package in packages.items()
|
||||||
|
if shutil.which(tool) is None
|
||||||
|
]
|
||||||
|
|
||||||
|
if missing:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Для поиска GPSRelay необходимо установить:\n"
|
||||||
|
+ "\n".join(missing)
|
||||||
|
+ "\nУстановка: sudo apt install "
|
||||||
|
+ " ".join(
|
||||||
|
package
|
||||||
|
for tool, package in packages.items()
|
||||||
|
if shutil.which(tool) is None
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_physical_interface(interface):
|
||||||
|
|
||||||
|
device_path = (
|
||||||
|
Path("/sys/class/net")
|
||||||
|
/ interface
|
||||||
|
/ "device"
|
||||||
|
)
|
||||||
|
|
||||||
|
return device_path.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def _is_excluded_interface(interface):
|
||||||
|
|
||||||
|
return interface.startswith(
|
||||||
|
EXCLUDED_INTERFACE_PREFIXES
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _interface_priority(interface):
|
||||||
|
|
||||||
|
if interface.startswith("enx"):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if interface.startswith((
|
||||||
|
"enp",
|
||||||
|
"eno",
|
||||||
|
"eth",
|
||||||
|
)):
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if interface.startswith((
|
||||||
|
"wl",
|
||||||
|
"wlan",
|
||||||
|
)):
|
||||||
|
return 2
|
||||||
|
|
||||||
|
return 3
|
||||||
|
|
||||||
|
|
||||||
|
def _get_local_networks(ip_binary):
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
ip_binary,
|
||||||
|
"-j",
|
||||||
|
"-4",
|
||||||
|
"addr",
|
||||||
|
"show"
|
||||||
|
],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=IP_TIMEOUT_SECONDS,
|
||||||
|
check=True
|
||||||
|
)
|
||||||
|
|
||||||
|
except (
|
||||||
|
subprocess.SubprocessError,
|
||||||
|
OSError
|
||||||
|
) as error:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
f"Не удалось получить сетевые интерфейсы: {error}"
|
||||||
|
) from error
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
interfaces = json.loads(
|
||||||
|
result.stdout
|
||||||
|
)
|
||||||
|
|
||||||
|
except json.JSONDecodeError as error:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Команда ip вернула некорректные данные."
|
||||||
|
) from error
|
||||||
|
|
||||||
|
networks = {}
|
||||||
|
|
||||||
|
for item in interfaces:
|
||||||
|
|
||||||
|
interface = item.get("ifname", "")
|
||||||
|
|
||||||
|
if not interface:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if _is_excluded_interface(interface):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not _is_physical_interface(interface):
|
||||||
|
continue
|
||||||
|
|
||||||
|
flags = item.get("flags", [])
|
||||||
|
|
||||||
|
if "UP" not in flags:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if item.get("operstate") == "DOWN":
|
||||||
|
continue
|
||||||
|
|
||||||
|
for address in item.get("addr_info", []):
|
||||||
|
|
||||||
|
if address.get("family") != "inet":
|
||||||
|
continue
|
||||||
|
|
||||||
|
if address.get("scope") != "global":
|
||||||
|
continue
|
||||||
|
|
||||||
|
local = address.get("local")
|
||||||
|
prefixlen = address.get("prefixlen")
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
network = ipaddress.ip_interface(
|
||||||
|
f"{local}/{prefixlen}"
|
||||||
|
).network
|
||||||
|
|
||||||
|
except (
|
||||||
|
TypeError,
|
||||||
|
ValueError
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not (
|
||||||
|
MAX_NETWORK_PREFIX_LENGTH
|
||||||
|
<= network.prefixlen
|
||||||
|
<= MIN_NETWORK_PREFIX_LENGTH
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not any(
|
||||||
|
network.subnet_of(private_network)
|
||||||
|
for private_network in PRIVATE_IPV4_NETWORKS
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if (
|
||||||
|
network.network_address.is_loopback
|
||||||
|
or network.network_address.is_link_local
|
||||||
|
or network.network_address.is_multicast
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
key = str(network)
|
||||||
|
|
||||||
|
candidate = {
|
||||||
|
"network": key,
|
||||||
|
"interface": interface,
|
||||||
|
"priority": _interface_priority(interface)
|
||||||
|
}
|
||||||
|
|
||||||
|
previous = networks.get(key)
|
||||||
|
|
||||||
|
if (
|
||||||
|
previous is None
|
||||||
|
or candidate["priority"] < previous["priority"]
|
||||||
|
):
|
||||||
|
networks[key] = candidate
|
||||||
|
|
||||||
|
return sorted(
|
||||||
|
networks.values(),
|
||||||
|
key=lambda item: (
|
||||||
|
item["priority"],
|
||||||
|
item["network"]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_network(
|
||||||
|
nmap_binary,
|
||||||
|
network,
|
||||||
|
port
|
||||||
|
):
|
||||||
|
|
||||||
|
command = [
|
||||||
|
nmap_binary,
|
||||||
|
"--unprivileged",
|
||||||
|
"-n",
|
||||||
|
"-Pn",
|
||||||
|
"-sT",
|
||||||
|
"-T4",
|
||||||
|
"--max-retries",
|
||||||
|
"1",
|
||||||
|
"--host-timeout",
|
||||||
|
"8s",
|
||||||
|
"--open",
|
||||||
|
"-p",
|
||||||
|
str(port),
|
||||||
|
"-oX",
|
||||||
|
"-",
|
||||||
|
network
|
||||||
|
]
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=NMAP_TIMEOUT_SECONDS,
|
||||||
|
check=False
|
||||||
|
)
|
||||||
|
|
||||||
|
except subprocess.TimeoutExpired as error:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
f"Истекло время сканирования сети {network}."
|
||||||
|
) from error
|
||||||
|
|
||||||
|
except OSError as error:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
f"Не удалось запустить nmap: {error}"
|
||||||
|
) from error
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
f"Ошибка nmap при сканировании {network}: "
|
||||||
|
f"{result.stderr.strip()}"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
root = ET.fromstring(
|
||||||
|
result.stdout
|
||||||
|
)
|
||||||
|
|
||||||
|
except ET.ParseError as error:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
f"Не удалось разобрать результат nmap для {network}."
|
||||||
|
) from error
|
||||||
|
|
||||||
|
candidates = []
|
||||||
|
|
||||||
|
for host in root.findall("host"):
|
||||||
|
|
||||||
|
status = host.find("status")
|
||||||
|
|
||||||
|
if (
|
||||||
|
status is None
|
||||||
|
or status.get("state") != "up"
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
ports = host.find("ports")
|
||||||
|
|
||||||
|
if ports is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
port_is_open = any(
|
||||||
|
item.get("portid") == str(port)
|
||||||
|
and item.find("state") is not None
|
||||||
|
and item.find("state").get("state") == "open"
|
||||||
|
for item in ports.findall("port")
|
||||||
|
)
|
||||||
|
|
||||||
|
if not port_is_open:
|
||||||
|
continue
|
||||||
|
|
||||||
|
address = next(
|
||||||
|
(
|
||||||
|
item.get("addr")
|
||||||
|
for item in host.findall("address")
|
||||||
|
if item.get("addrtype") == "ipv4"
|
||||||
|
),
|
||||||
|
None
|
||||||
|
)
|
||||||
|
|
||||||
|
if address is not None:
|
||||||
|
|
||||||
|
candidates.append(
|
||||||
|
address
|
||||||
|
)
|
||||||
|
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_nmea_stream(output):
|
||||||
|
|
||||||
|
if isinstance(output, bytes):
|
||||||
|
output = output.decode(
|
||||||
|
"ascii",
|
||||||
|
errors="replace"
|
||||||
|
)
|
||||||
|
|
||||||
|
valid_types = set()
|
||||||
|
valid_count = 0
|
||||||
|
total_count = 0
|
||||||
|
|
||||||
|
for line in output.splitlines():
|
||||||
|
|
||||||
|
line = line.strip()
|
||||||
|
|
||||||
|
if not line.startswith("$"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
total_count += 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
message = pynmea2.parse(
|
||||||
|
line,
|
||||||
|
check=True
|
||||||
|
)
|
||||||
|
|
||||||
|
except (
|
||||||
|
pynmea2.ParseError,
|
||||||
|
ValueError,
|
||||||
|
TypeError
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
message_type = getattr(
|
||||||
|
message,
|
||||||
|
"sentence_type",
|
||||||
|
""
|
||||||
|
)
|
||||||
|
|
||||||
|
if message_type not in VALID_NMEA_TYPES:
|
||||||
|
continue
|
||||||
|
|
||||||
|
valid_count += 1
|
||||||
|
valid_types.add(message_type)
|
||||||
|
|
||||||
|
ratio = (
|
||||||
|
valid_count / total_count
|
||||||
|
if total_count
|
||||||
|
else 0
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"valid_count": valid_count,
|
||||||
|
"valid_types": valid_types,
|
||||||
|
"valid_ratio": ratio,
|
||||||
|
"total_count": total_count
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _test_candidate(
|
||||||
|
nc_binary,
|
||||||
|
host,
|
||||||
|
port
|
||||||
|
):
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
nc_binary,
|
||||||
|
"-n",
|
||||||
|
host,
|
||||||
|
str(port)
|
||||||
|
],
|
||||||
|
capture_output=True,
|
||||||
|
timeout=NMEA_TIMEOUT_SECONDS,
|
||||||
|
check=False
|
||||||
|
)
|
||||||
|
|
||||||
|
output = result.stdout or b""
|
||||||
|
|
||||||
|
except subprocess.TimeoutExpired as error:
|
||||||
|
|
||||||
|
output = error.stdout or b""
|
||||||
|
|
||||||
|
except OSError:
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
quality = _validate_nmea_stream(
|
||||||
|
output
|
||||||
|
)
|
||||||
|
|
||||||
|
if (
|
||||||
|
quality["valid_count"]
|
||||||
|
< MIN_VALID_NMEA_SENTENCES
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
|
||||||
|
return quality
|
||||||
|
|
||||||
|
|
||||||
|
def discover_gpsrelay(port=DEFAULT_PORT):
|
||||||
|
|
||||||
|
if isinstance(port, bool):
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Некорректный порт GPSRelay."
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
port = int(port)
|
||||||
|
|
||||||
|
except (
|
||||||
|
TypeError,
|
||||||
|
ValueError
|
||||||
|
) as error:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Некорректный порт GPSRelay."
|
||||||
|
) from error
|
||||||
|
|
||||||
|
if not 1 <= port <= 65535:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Порт GPSRelay должен находиться в диапазоне 1–65535."
|
||||||
|
)
|
||||||
|
|
||||||
|
_require_tools()
|
||||||
|
|
||||||
|
ip_binary = shutil.which("ip")
|
||||||
|
nmap_binary = shutil.which("nmap")
|
||||||
|
nc_binary = shutil.which("nc")
|
||||||
|
|
||||||
|
networks = _get_local_networks(
|
||||||
|
ip_binary
|
||||||
|
)
|
||||||
|
|
||||||
|
if not networks:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Не найдены активные физические сетевые интерфейсы "
|
||||||
|
"с подходящими IPv4-подсетями."
|
||||||
|
)
|
||||||
|
|
||||||
|
discovered = []
|
||||||
|
scan_errors = []
|
||||||
|
|
||||||
|
for network in networks:
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
hosts = _scan_network(
|
||||||
|
nmap_binary,
|
||||||
|
network["network"],
|
||||||
|
port
|
||||||
|
)
|
||||||
|
|
||||||
|
except GPSRelayDiscoveryError as error:
|
||||||
|
|
||||||
|
scan_errors.append(
|
||||||
|
str(error)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
for host in hosts:
|
||||||
|
|
||||||
|
discovered.append({
|
||||||
|
"host": host,
|
||||||
|
"port": port,
|
||||||
|
"interface": network["interface"],
|
||||||
|
"priority": network["priority"]
|
||||||
|
})
|
||||||
|
|
||||||
|
if scan_errors:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Не удалось полностью просканировать все локальные сети:\n"
|
||||||
|
+ "\n".join(scan_errors)
|
||||||
|
)
|
||||||
|
|
||||||
|
if not discovered:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
f"Устройства с открытым TCP-портом {port} "
|
||||||
|
"в локальных сетях не найдены."
|
||||||
|
)
|
||||||
|
|
||||||
|
verified = []
|
||||||
|
|
||||||
|
for candidate in discovered:
|
||||||
|
|
||||||
|
quality = _test_candidate(
|
||||||
|
nc_binary,
|
||||||
|
candidate["host"],
|
||||||
|
port
|
||||||
|
)
|
||||||
|
|
||||||
|
if quality is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
verified.append({
|
||||||
|
**candidate,
|
||||||
|
**quality
|
||||||
|
})
|
||||||
|
|
||||||
|
if not verified:
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Порт найден, но ни одно устройство не передаёт "
|
||||||
|
"достаточное количество корректных NMEA-предложений."
|
||||||
|
)
|
||||||
|
|
||||||
|
verified.sort(
|
||||||
|
key=lambda item: (
|
||||||
|
item["priority"],
|
||||||
|
-item["valid_count"],
|
||||||
|
-len(item["valid_types"]),
|
||||||
|
-item["valid_ratio"]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
best = verified[0]
|
||||||
|
|
||||||
|
best_rank = (
|
||||||
|
best["priority"],
|
||||||
|
best["valid_count"],
|
||||||
|
len(best["valid_types"]),
|
||||||
|
best["valid_ratio"]
|
||||||
|
)
|
||||||
|
|
||||||
|
equally_suitable = [
|
||||||
|
item
|
||||||
|
for item in verified
|
||||||
|
if (
|
||||||
|
item["priority"],
|
||||||
|
item["valid_count"],
|
||||||
|
len(item["valid_types"]),
|
||||||
|
item["valid_ratio"]
|
||||||
|
) == best_rank
|
||||||
|
]
|
||||||
|
|
||||||
|
if len(equally_suitable) > 1:
|
||||||
|
|
||||||
|
hosts = ", ".join(
|
||||||
|
item["host"]
|
||||||
|
for item in equally_suitable
|
||||||
|
)
|
||||||
|
|
||||||
|
raise GPSRelayDiscoveryError(
|
||||||
|
"Обнаружено несколько равноценных GPSRelay: "
|
||||||
|
+ hosts
|
||||||
|
+ ". Автоматический выбор небезопасен."
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"host": best["host"],
|
||||||
|
"port": port,
|
||||||
|
"interface": best["interface"],
|
||||||
|
"valid_sentences": best["valid_count"],
|
||||||
|
"sentence_types": sorted(
|
||||||
|
best["valid_types"]
|
||||||
|
),
|
||||||
|
"candidate_count": len(verified)
|
||||||
|
}
|
||||||
+46
-6
@@ -148,6 +148,8 @@ def shutdown(signum=None, frame=None):
|
|||||||
f"WiFi stop error: {error}"
|
f"WiFi stop error: {error}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
parser_succeeded = False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
if parser and session:
|
if parser and session:
|
||||||
@@ -157,6 +159,8 @@ def shutdown(signum=None, frame=None):
|
|||||||
session_id
|
session_id
|
||||||
)
|
)
|
||||||
|
|
||||||
|
parser_succeeded = True
|
||||||
|
|
||||||
|
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
|
|
||||||
@@ -179,17 +183,31 @@ def shutdown(signum=None, frame=None):
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
database_close_safe = True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
if (db and session_id is not None):
|
if (db and session_id is not None):
|
||||||
|
|
||||||
db.flush_observations()
|
if parser_succeeded:
|
||||||
|
|
||||||
db.finalize_session(
|
db.flush_observations()
|
||||||
session_id
|
|
||||||
)
|
|
||||||
|
|
||||||
db.commit()
|
db.finalize_session(
|
||||||
|
session_id
|
||||||
|
)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
db.observation_buffer.clear()
|
||||||
|
|
||||||
|
db.rollback()
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
"Parser did not complete; session transaction rolled back"
|
||||||
|
)
|
||||||
|
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
|
|
||||||
@@ -197,6 +215,22 @@ def shutdown(signum=None, frame=None):
|
|||||||
f"Database finalize error: {error}"
|
f"Database finalize error: {error}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if db:
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
db.observation_buffer.clear()
|
||||||
|
|
||||||
|
db.rollback()
|
||||||
|
|
||||||
|
except Exception as rollback_error:
|
||||||
|
|
||||||
|
logger.error(
|
||||||
|
f"Database rollback error: {rollback_error}"
|
||||||
|
)
|
||||||
|
|
||||||
|
database_close_safe = False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -218,7 +252,13 @@ def shutdown(signum=None, frame=None):
|
|||||||
|
|
||||||
if db:
|
if db:
|
||||||
|
|
||||||
db.close()
|
if database_close_safe:
|
||||||
|
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
db.conn.close()
|
||||||
|
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
+13
-4
@@ -173,12 +173,21 @@ class Session:
|
|||||||
|
|
||||||
obj = cls.__new__(cls)
|
obj = cls.__new__(cls)
|
||||||
|
|
||||||
obj.start_time = datetime.now(
|
|
||||||
timezone.utc
|
|
||||||
)
|
|
||||||
|
|
||||||
obj.path = Path(path)
|
obj.path = Path(path)
|
||||||
|
|
||||||
|
try:
|
||||||
|
obj.start_time = datetime.strptime(
|
||||||
|
obj.path.name,
|
||||||
|
"%Y%m%d_%H%M%S"
|
||||||
|
).replace(
|
||||||
|
tzinfo=timezone.utc
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError(
|
||||||
|
"Invalid session directory timestamp: "
|
||||||
|
f"{obj.path.name}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
obj.capture_file = (
|
obj.capture_file = (
|
||||||
obj.path /
|
obj.path /
|
||||||
"capture.pcapng"
|
"capture.pcapng"
|
||||||
|
|||||||
+198
-33
@@ -49,6 +49,10 @@ class NetworkCommandError(WiFiConnectionError):
|
|||||||
self.timed_out = timed_out
|
self.timed_out = timed_out
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkCommandCancelled(WiFiConnectionError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class UnsupportedSecurityError(WiFiConnectionError):
|
class UnsupportedSecurityError(WiFiConnectionError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -98,6 +102,7 @@ class WiFiConnectionService:
|
|||||||
or
|
or
|
||||||
subprocess.run
|
subprocess.run
|
||||||
)
|
)
|
||||||
|
self._use_subprocess_popen = command_runner is None
|
||||||
|
|
||||||
self.command_timeout = command_timeout
|
self.command_timeout = command_timeout
|
||||||
self.scan_timeout = scan_timeout
|
self.scan_timeout = scan_timeout
|
||||||
@@ -128,25 +133,117 @@ class WiFiConnectionService:
|
|||||||
def _run(
|
def _run(
|
||||||
self,
|
self,
|
||||||
command,
|
command,
|
||||||
timeout=None
|
timeout=None,
|
||||||
|
cancel_event=None
|
||||||
):
|
):
|
||||||
|
|
||||||
|
command_timeout = (
|
||||||
|
timeout
|
||||||
|
or
|
||||||
|
self.command_timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
environment = {
|
||||||
|
**os.environ,
|
||||||
|
"LC_ALL": "C"
|
||||||
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
result = self.command_runner(
|
if (
|
||||||
command,
|
cancel_event is not None
|
||||||
capture_output=True,
|
and
|
||||||
text=True,
|
self._use_subprocess_popen
|
||||||
timeout=(
|
):
|
||||||
timeout
|
|
||||||
or
|
if cancel_event.is_set():
|
||||||
self.command_timeout
|
raise NetworkCommandCancelled(
|
||||||
),
|
"Wi-Fi verification was cancelled."
|
||||||
env={
|
)
|
||||||
**os.environ,
|
|
||||||
"LC_ALL": "C"
|
process = subprocess.Popen(
|
||||||
}
|
command,
|
||||||
)
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
env=environment
|
||||||
|
)
|
||||||
|
|
||||||
|
deadline = time.monotonic() + command_timeout
|
||||||
|
|
||||||
|
while True:
|
||||||
|
|
||||||
|
if cancel_event.is_set():
|
||||||
|
|
||||||
|
try:
|
||||||
|
process.terminate()
|
||||||
|
except ProcessLookupError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
stdout, stderr = process.communicate(
|
||||||
|
timeout=5
|
||||||
|
)
|
||||||
|
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
|
||||||
|
try:
|
||||||
|
process.kill()
|
||||||
|
except ProcessLookupError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
stdout, stderr = process.communicate()
|
||||||
|
|
||||||
|
raise NetworkCommandCancelled(
|
||||||
|
"Wi-Fi verification was cancelled."
|
||||||
|
)
|
||||||
|
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
|
||||||
|
if remaining <= 0:
|
||||||
|
|
||||||
|
process.kill()
|
||||||
|
stdout, stderr = process.communicate()
|
||||||
|
|
||||||
|
raise NetworkCommandError(
|
||||||
|
"NetworkManager command timed out.",
|
||||||
|
stdout=stdout or "",
|
||||||
|
stderr=stderr or "",
|
||||||
|
timed_out=True
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
stdout, stderr = process.communicate(
|
||||||
|
timeout=min(0.2, remaining)
|
||||||
|
)
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if cancel_event.is_set():
|
||||||
|
raise NetworkCommandCancelled(
|
||||||
|
"Wi-Fi verification was cancelled."
|
||||||
|
)
|
||||||
|
|
||||||
|
result = subprocess.CompletedProcess(
|
||||||
|
command,
|
||||||
|
process.returncode,
|
||||||
|
stdout,
|
||||||
|
stderr
|
||||||
|
)
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
result = self.command_runner(
|
||||||
|
command,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=command_timeout,
|
||||||
|
env=environment
|
||||||
|
)
|
||||||
|
|
||||||
except subprocess.TimeoutExpired as error:
|
except subprocess.TimeoutExpired as error:
|
||||||
|
|
||||||
@@ -191,14 +288,20 @@ class WiFiConnectionService:
|
|||||||
|
|
||||||
return result.stdout.strip()
|
return result.stdout.strip()
|
||||||
|
|
||||||
def _nmcli(self, *arguments, timeout=None):
|
def _nmcli(
|
||||||
|
self,
|
||||||
|
*arguments,
|
||||||
|
timeout=None,
|
||||||
|
cancel_event=None
|
||||||
|
):
|
||||||
|
|
||||||
return self._run(
|
return self._run(
|
||||||
[
|
[
|
||||||
"nmcli",
|
"nmcli",
|
||||||
*arguments
|
*arguments
|
||||||
],
|
],
|
||||||
timeout=timeout
|
timeout=timeout,
|
||||||
|
cancel_event=cancel_event
|
||||||
)
|
)
|
||||||
|
|
||||||
def _busctl(self, *arguments):
|
def _busctl(self, *arguments):
|
||||||
@@ -646,6 +749,44 @@ class WiFiConnectionService:
|
|||||||
|
|
||||||
return output
|
return output
|
||||||
|
|
||||||
|
def disconnect_active_connection(self, interface):
|
||||||
|
|
||||||
|
self._validate_interface(interface)
|
||||||
|
|
||||||
|
active_uuid = self._get_active_connection_uuid(
|
||||||
|
interface
|
||||||
|
)
|
||||||
|
|
||||||
|
if active_uuid is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
self._nmcli(
|
||||||
|
"connection",
|
||||||
|
"down",
|
||||||
|
"uuid",
|
||||||
|
active_uuid
|
||||||
|
)
|
||||||
|
|
||||||
|
except NetworkCommandError as error:
|
||||||
|
|
||||||
|
raise NetworkCleanupError(
|
||||||
|
f"Could not disconnect active Wi-Fi connection: {error}"
|
||||||
|
) from error
|
||||||
|
|
||||||
|
remaining_uuid = self._get_active_connection_uuid(
|
||||||
|
interface
|
||||||
|
)
|
||||||
|
|
||||||
|
if remaining_uuid is not None:
|
||||||
|
|
||||||
|
raise NetworkCleanupError(
|
||||||
|
f"Wi-Fi interface {interface} remains connected."
|
||||||
|
)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
def _list_connection_profiles(self):
|
def _list_connection_profiles(self):
|
||||||
|
|
||||||
output = self._nmcli(
|
output = self._nmcli(
|
||||||
@@ -1253,7 +1394,8 @@ class WiFiConnectionService:
|
|||||||
profile_uuid,
|
profile_uuid,
|
||||||
interface,
|
interface,
|
||||||
access_point,
|
access_point,
|
||||||
password=None
|
password=None,
|
||||||
|
cancel_event=None
|
||||||
):
|
):
|
||||||
|
|
||||||
arguments = [
|
arguments = [
|
||||||
@@ -1299,7 +1441,8 @@ class WiFiConnectionService:
|
|||||||
|
|
||||||
self._nmcli(
|
self._nmcli(
|
||||||
*arguments,
|
*arguments,
|
||||||
timeout=90
|
timeout=90,
|
||||||
|
cancel_event=cancel_event
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
@@ -1463,18 +1606,10 @@ class WiFiConnectionService:
|
|||||||
password,
|
password,
|
||||||
restore_connection=True,
|
restore_connection=True,
|
||||||
keep_profile=False,
|
keep_profile=False,
|
||||||
access_point=None
|
access_point=None,
|
||||||
|
cancel_event=None
|
||||||
):
|
):
|
||||||
|
|
||||||
if (
|
|
||||||
not restore_connection
|
|
||||||
and not keep_profile
|
|
||||||
):
|
|
||||||
raise WiFiConnectionError(
|
|
||||||
"A verification without connection restoration "
|
|
||||||
"must retain a successful temporary profile."
|
|
||||||
)
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
restore_connection
|
restore_connection
|
||||||
and keep_profile
|
and keep_profile
|
||||||
@@ -1549,7 +1684,8 @@ class WiFiConnectionService:
|
|||||||
profile_uuid,
|
profile_uuid,
|
||||||
interface,
|
interface,
|
||||||
access_point,
|
access_point,
|
||||||
password
|
password,
|
||||||
|
cancel_event=cancel_event
|
||||||
)
|
)
|
||||||
|
|
||||||
success = True
|
success = True
|
||||||
@@ -1617,9 +1753,38 @@ class WiFiConnectionService:
|
|||||||
error
|
error
|
||||||
)
|
)
|
||||||
|
|
||||||
if not (
|
profile_is_safe_to_delete = True
|
||||||
success
|
|
||||||
and keep_profile
|
if not restore_connection and not keep_profile:
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
active_uuid = self._get_active_connection_uuid(
|
||||||
|
interface
|
||||||
|
)
|
||||||
|
|
||||||
|
if active_uuid == profile_uuid:
|
||||||
|
|
||||||
|
self._nmcli(
|
||||||
|
"connection",
|
||||||
|
"down",
|
||||||
|
"uuid",
|
||||||
|
profile_uuid
|
||||||
|
)
|
||||||
|
|
||||||
|
except NetworkCommandError as error:
|
||||||
|
|
||||||
|
cleanup_error = str(
|
||||||
|
error
|
||||||
|
)
|
||||||
|
profile_is_safe_to_delete = False
|
||||||
|
|
||||||
|
if (
|
||||||
|
not (
|
||||||
|
success
|
||||||
|
and keep_profile
|
||||||
|
)
|
||||||
|
and profile_is_safe_to_delete
|
||||||
):
|
):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|||||||
Reference in New Issue
Block a user