637 lines
18 KiB
Python
637 lines
18 KiB
Python
import logging
|
|
import re
|
|
import select
|
|
import socket
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
|
|
from datetime import datetime, timezone
|
|
from logging.handlers import RotatingFileHandler
|
|
from pathlib import Path
|
|
|
|
from gps import GPSRelaySource, GpsdSource, parse_nmea
|
|
from logging_config import (
|
|
LOG_DATE_FORMAT,
|
|
LOG_FORMAT,
|
|
UTCFormatter,
|
|
)
|
|
|
|
|
|
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
|
|
|
POLL_INTERVAL_SECONDS = 0.5
|
|
RECONNECT_DELAY_SECONDS = 2.0
|
|
CONNECT_TIMEOUT_SECONDS = 3.0
|
|
GPSD_GREETING_MAX_BYTES = 65536
|
|
LOG_MAX_BYTES = 5 * 1024 * 1024
|
|
LOG_BACKUP_COUNT = 3
|
|
|
|
|
|
def _create_logger():
|
|
logger = logging.getLogger(
|
|
"wifi-gps-mapper.auto-verification"
|
|
)
|
|
|
|
logger.setLevel(logging.INFO)
|
|
logger.propagate = False
|
|
|
|
if not logger.handlers:
|
|
log_dir = PROJECT_ROOT / "logs"
|
|
log_dir.mkdir(
|
|
parents=True,
|
|
exist_ok=True
|
|
)
|
|
|
|
handler = RotatingFileHandler(
|
|
log_dir / "auto-verification.log",
|
|
maxBytes=LOG_MAX_BYTES,
|
|
backupCount=LOG_BACKUP_COUNT,
|
|
encoding="utf-8"
|
|
)
|
|
|
|
handler.setFormatter(
|
|
UTCFormatter(
|
|
LOG_FORMAT,
|
|
datefmt=LOG_DATE_FORMAT
|
|
)
|
|
)
|
|
|
|
logger.addHandler(handler)
|
|
|
|
return logger
|
|
|
|
|
|
def _get_gpsd_port():
|
|
"""Получает IPv4 TCP-порт из активной конфигурации gpsd.socket."""
|
|
try:
|
|
result = subprocess.run(
|
|
[
|
|
"systemctl",
|
|
"show",
|
|
"gpsd.socket",
|
|
"--property=Listen",
|
|
"--value",
|
|
],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=3,
|
|
)
|
|
except (OSError, subprocess.SubprocessError) as error:
|
|
raise RuntimeError(
|
|
f"Cannot read gpsd.socket configuration: {error}"
|
|
) from error
|
|
|
|
ports = set()
|
|
|
|
for line in result.stdout.splitlines():
|
|
endpoint = line.strip()
|
|
|
|
if "=" in endpoint:
|
|
endpoint = endpoint.split("=", 1)[1].strip()
|
|
|
|
match = re.fullmatch(
|
|
r"(?:127\.0\.0\.1|0\.0\.0\.0):(\d+)(?:\s+\(Stream\))?",
|
|
endpoint,
|
|
)
|
|
|
|
if match:
|
|
port = int(match.group(1))
|
|
|
|
if not 1 <= port <= 65535:
|
|
raise RuntimeError(
|
|
f"Invalid GPSD TCP port: {port}"
|
|
)
|
|
|
|
ports.add(port)
|
|
|
|
if not ports:
|
|
raise RuntimeError(
|
|
"No IPv4 TCP listener found in gpsd.socket"
|
|
)
|
|
|
|
if len(ports) != 1:
|
|
raise RuntimeError(
|
|
"gpsd.socket has multiple different IPv4 TCP ports: "
|
|
+ ", ".join(str(port) for port in sorted(ports))
|
|
)
|
|
|
|
return ports.pop()
|
|
|
|
|
|
logger = _create_logger()
|
|
|
|
|
|
class AutoGPSService:
|
|
|
|
def __init__(
|
|
self,
|
|
settings,
|
|
callback=None,
|
|
fix_callback=None,
|
|
position_callback=None
|
|
):
|
|
self.settings = dict(settings or {})
|
|
self.callback = callback
|
|
self.fix_callback = fix_callback
|
|
self.position_callback = position_callback
|
|
|
|
self.gps_source = self.settings.get("gps_source")
|
|
|
|
self.max_age_seconds = float(
|
|
self.settings.get(
|
|
"gnss_max_age_seconds",
|
|
10
|
|
)
|
|
)
|
|
|
|
if self.max_age_seconds <= 0:
|
|
raise ValueError(
|
|
"gnss_max_age_seconds must be positive"
|
|
)
|
|
|
|
if self.gps_source not in ("gpsd", "gpsrelay"):
|
|
raise ValueError(
|
|
"Auto GPS source must be 'gpsd' or 'gpsrelay'"
|
|
)
|
|
|
|
if self.gps_source == "gpsrelay":
|
|
host = self.settings.get("gpsrelay_host")
|
|
port = self.settings.get("gpsrelay_port")
|
|
|
|
if not isinstance(host, str) or not host.strip():
|
|
raise ValueError(
|
|
"GPS Relay host is required"
|
|
)
|
|
|
|
if (
|
|
isinstance(port, bool)
|
|
or not isinstance(port, int)
|
|
or not 1 <= port <= 65535
|
|
):
|
|
raise ValueError(
|
|
"GPS Relay port must be between 1 and 65535"
|
|
)
|
|
|
|
self.thread = None
|
|
self.stop_event = threading.Event()
|
|
|
|
self.source = None
|
|
self.source_lock = threading.Lock()
|
|
self.state_lock = threading.Lock()
|
|
|
|
self.running = False
|
|
self.state = "READY"
|
|
self.error = None
|
|
|
|
self.current_fix = None
|
|
self.last_fix_monotonic = None
|
|
self.connected_monotonic = None
|
|
|
|
def _emit(
|
|
self,
|
|
level,
|
|
code,
|
|
message
|
|
):
|
|
event = {
|
|
"level": level,
|
|
"code": code,
|
|
"message": message,
|
|
"state": self.state,
|
|
"timestamp": datetime.now(
|
|
timezone.utc
|
|
).isoformat()
|
|
}
|
|
|
|
log_method = getattr(
|
|
logger,
|
|
level.lower(),
|
|
logger.info
|
|
)
|
|
|
|
log_method(message)
|
|
|
|
if self.callback is not None:
|
|
try:
|
|
self.callback(event)
|
|
except Exception:
|
|
logger.exception(
|
|
"Auto GPS callback failed"
|
|
)
|
|
|
|
def _set_state(self, state):
|
|
with self.state_lock:
|
|
self.state = state
|
|
|
|
def _create_source(self):
|
|
if self.gps_source == "gpsd":
|
|
return GpsdSource(
|
|
host="127.0.0.1",
|
|
port=_get_gpsd_port()
|
|
)
|
|
|
|
if self.gps_source == "gpsrelay":
|
|
return GPSRelaySource(
|
|
self.settings["gpsrelay_host"].strip(),
|
|
self.settings["gpsrelay_port"]
|
|
)
|
|
|
|
raise ValueError(
|
|
f"Unsupported Auto GPS source: {self.gps_source}"
|
|
)
|
|
|
|
def _open_source(self, source):
|
|
# Поддержка тестовых источников с заранее созданным сокетом.
|
|
if getattr(source, "socket", None) is not None:
|
|
stream = source.open()
|
|
return source.socket, stream, b""
|
|
|
|
connection = socket.create_connection(
|
|
(source.host, source.port),
|
|
timeout=CONNECT_TIMEOUT_SECONDS
|
|
)
|
|
|
|
# Сохраняем сокет сразу после подключения, чтобы stop()
|
|
# мог закрыть его во время дальнейшей инициализации.
|
|
source.socket = connection
|
|
connection.settimeout(CONNECT_TIMEOUT_SECONDS)
|
|
|
|
pending = b""
|
|
|
|
if self.gps_source == "gpsd":
|
|
greeting = bytearray()
|
|
|
|
handshake_deadline = (
|
|
time.monotonic() + CONNECT_TIMEOUT_SECONDS
|
|
)
|
|
|
|
while b"\n" not in greeting:
|
|
if self.stop_event.is_set():
|
|
raise ConnectionError(
|
|
"Auto GPS stopped during GPSD handshake"
|
|
)
|
|
|
|
remaining = (
|
|
handshake_deadline - time.monotonic()
|
|
)
|
|
|
|
if remaining <= 0:
|
|
raise TimeoutError(
|
|
"GPSD handshake timed out"
|
|
)
|
|
|
|
connection.settimeout(remaining)
|
|
chunk = connection.recv(4096)
|
|
|
|
if not chunk:
|
|
raise ConnectionError(
|
|
"GPSD closed the connection during handshake"
|
|
)
|
|
|
|
greeting.extend(chunk)
|
|
|
|
if len(greeting) > GPSD_GREETING_MAX_BYTES:
|
|
raise ConnectionError(
|
|
"GPSD greeting exceeds the allowed size"
|
|
)
|
|
|
|
greeting_end = greeting.find(b"\n") + 1
|
|
pending = bytes(greeting[greeting_end:])
|
|
|
|
connection.sendall(
|
|
b'?WATCH={"enable":true,"json":false,"nmea":true};\n'
|
|
)
|
|
|
|
connection.setblocking(False)
|
|
|
|
return connection, None, pending
|
|
|
|
def start(self):
|
|
if (
|
|
self.thread is not None
|
|
and self.thread.is_alive()
|
|
):
|
|
return False
|
|
|
|
self.stop_event.clear()
|
|
|
|
with self.state_lock:
|
|
self.running = True
|
|
self.state = "STARTING"
|
|
self.error = None
|
|
self.current_fix = None
|
|
self.last_fix_monotonic = None
|
|
self.connected_monotonic = None
|
|
|
|
self.thread = threading.Thread(
|
|
target=self.worker,
|
|
name="auto-gps",
|
|
daemon=True
|
|
)
|
|
|
|
self.thread.start()
|
|
|
|
self._emit(
|
|
"INFO",
|
|
"GPS_STARTED",
|
|
f"Auto GPS started with source: {self.gps_source}"
|
|
)
|
|
|
|
return True
|
|
|
|
def stop(self):
|
|
self.stop_event.set()
|
|
|
|
with self.source_lock:
|
|
source = self.source
|
|
|
|
if source is not None:
|
|
connection = getattr(
|
|
source,
|
|
"socket",
|
|
None
|
|
)
|
|
|
|
if connection is not None:
|
|
try:
|
|
connection.shutdown(socket.SHUT_RDWR)
|
|
except OSError:
|
|
pass
|
|
|
|
try:
|
|
source.close()
|
|
except Exception:
|
|
logger.exception(
|
|
"Auto GPS source close failed"
|
|
)
|
|
|
|
def _set_fix(self, gps):
|
|
now = time.monotonic()
|
|
|
|
with self.state_lock:
|
|
had_fresh_fix = (
|
|
self.current_fix is not None
|
|
and self.last_fix_monotonic is not None
|
|
and now - self.last_fix_monotonic
|
|
<= self.max_age_seconds
|
|
)
|
|
|
|
self.current_fix = gps
|
|
self.last_fix_monotonic = now
|
|
self.state = "FIX"
|
|
self.error = None
|
|
|
|
if not had_fresh_fix:
|
|
self._emit(
|
|
"INFO",
|
|
"GPS_FIX_RESTORED",
|
|
"Auto GPS has a fresh valid FIX: "
|
|
f"lat={gps.latitude:.6f}, "
|
|
f"lon={gps.longitude:.6f}"
|
|
)
|
|
|
|
if self.fix_callback is not None:
|
|
try:
|
|
self.fix_callback(gps)
|
|
except Exception:
|
|
logger.exception(
|
|
"Auto GPS FIX callback failed"
|
|
)
|
|
|
|
if self.position_callback is not None:
|
|
try:
|
|
self.position_callback(gps)
|
|
except Exception:
|
|
logger.exception(
|
|
"Auto GPS position callback failed"
|
|
)
|
|
|
|
def _check_fix_freshness(self):
|
|
now = time.monotonic()
|
|
|
|
with self.state_lock:
|
|
if self.state in ("STOPPED", "RECONNECTING"):
|
|
return
|
|
|
|
reference = (
|
|
self.last_fix_monotonic
|
|
if self.last_fix_monotonic is not None
|
|
else self.connected_monotonic
|
|
)
|
|
|
|
if reference is None:
|
|
return
|
|
|
|
age = now - reference
|
|
|
|
if age <= self.max_age_seconds:
|
|
return
|
|
|
|
if self.state == "NO_FIX":
|
|
return
|
|
|
|
self.current_fix = None
|
|
self.state = "NO_FIX"
|
|
|
|
self._emit(
|
|
"WARNING",
|
|
"GPS_FIX_LOST",
|
|
"Auto GPS has no fresh valid FIX. "
|
|
f"Last valid position age: {age:.1f} seconds."
|
|
)
|
|
|
|
def get_status(self):
|
|
now = time.monotonic()
|
|
|
|
with self.state_lock:
|
|
fix = self.current_fix
|
|
last_fix = self.last_fix_monotonic
|
|
state = self.state
|
|
error = self.error
|
|
|
|
age = (
|
|
now - last_fix
|
|
if last_fix is not None
|
|
else None
|
|
)
|
|
|
|
fresh = (
|
|
fix is not None
|
|
and age is not None
|
|
and age <= self.max_age_seconds
|
|
and state == "FIX"
|
|
)
|
|
|
|
return {
|
|
"running": self.running,
|
|
"source": self.gps_source,
|
|
"state": state,
|
|
"has_fresh_fix": fresh,
|
|
"latitude": (
|
|
fix.latitude
|
|
if fresh
|
|
else None
|
|
),
|
|
"longitude": (
|
|
fix.longitude
|
|
if fresh
|
|
else None
|
|
),
|
|
"fix_age_seconds": age,
|
|
"max_age_seconds": self.max_age_seconds,
|
|
"error": error
|
|
}
|
|
|
|
def worker(self):
|
|
try:
|
|
while not self.stop_event.is_set():
|
|
source = None
|
|
stream = None
|
|
|
|
try:
|
|
source = self._create_source()
|
|
|
|
with self.source_lock:
|
|
self.source = source
|
|
|
|
if self.stop_event.is_set():
|
|
break
|
|
|
|
self._set_state("CONNECTING")
|
|
|
|
logger.info(
|
|
"Connecting Auto GPS to %s",
|
|
self.gps_source
|
|
)
|
|
|
|
connection, stream, pending = self._open_source(
|
|
source
|
|
)
|
|
|
|
if self.stop_event.is_set():
|
|
break
|
|
|
|
with self.state_lock:
|
|
self.connected_monotonic = time.monotonic()
|
|
self.state = "CONNECTED"
|
|
self.error = None
|
|
|
|
self._emit(
|
|
"INFO",
|
|
"GPS_CONNECTED",
|
|
f"Auto GPS connected to {self.gps_source}"
|
|
)
|
|
|
|
while not self.stop_event.is_set():
|
|
# Сначала обрабатываем уже полученные строки.
|
|
# Это исключает зависимость от готовности сокета,
|
|
# когда данные остались во внутреннем буфере.
|
|
while b"\n" in pending:
|
|
line, pending = pending.split(b"\n", 1)
|
|
|
|
gps = parse_nmea(
|
|
line.decode("ascii", errors="replace").strip(),
|
|
datetime.now(timezone.utc)
|
|
)
|
|
|
|
if gps is not None:
|
|
self._set_fix(gps)
|
|
else:
|
|
self._check_fix_freshness()
|
|
|
|
if len(pending) > GPSD_GREETING_MAX_BYTES:
|
|
raise ConnectionError(
|
|
"NMEA receive buffer exceeds the allowed size"
|
|
)
|
|
|
|
readable, _, _ = select.select(
|
|
[connection],
|
|
[],
|
|
[],
|
|
POLL_INTERVAL_SECONDS
|
|
)
|
|
|
|
if not readable:
|
|
self._check_fix_freshness()
|
|
continue
|
|
|
|
chunk = connection.recv(4096)
|
|
|
|
if not chunk:
|
|
raise ConnectionError(
|
|
"GPS source closed the NMEA stream"
|
|
)
|
|
|
|
pending += chunk
|
|
|
|
except Exception as error:
|
|
if self.stop_event.is_set():
|
|
break
|
|
|
|
with self.state_lock:
|
|
self.current_fix = None
|
|
self.state = "RECONNECTING"
|
|
self.error = str(error)
|
|
|
|
self._emit(
|
|
"WARNING",
|
|
"GPS_CONNECTION_LOST",
|
|
"Auto GPS connection lost: "
|
|
f"{error}. Reconnecting to the same source."
|
|
)
|
|
|
|
finally:
|
|
if stream is not None:
|
|
try:
|
|
stream.close()
|
|
except Exception:
|
|
logger.exception(
|
|
"Auto GPS stream close failed"
|
|
)
|
|
|
|
if source is not None:
|
|
try:
|
|
source.close()
|
|
except Exception:
|
|
logger.exception(
|
|
"Auto GPS source close failed"
|
|
)
|
|
|
|
with self.source_lock:
|
|
if self.source is source:
|
|
self.source = None
|
|
|
|
if not self.stop_event.is_set():
|
|
self.stop_event.wait(
|
|
RECONNECT_DELAY_SECONDS
|
|
)
|
|
|
|
except Exception as error:
|
|
with self.state_lock:
|
|
self.error = str(error)
|
|
self.state = "ERROR"
|
|
|
|
self._emit(
|
|
"ERROR",
|
|
"GPS_SERVICE_ERROR",
|
|
f"Auto GPS service error: {error}"
|
|
)
|
|
|
|
finally:
|
|
with self.state_lock:
|
|
self.current_fix = None
|
|
self.running = False
|
|
was_error = self.state == "ERROR"
|
|
|
|
if not was_error:
|
|
self.state = "STOPPED"
|
|
|
|
if not was_error:
|
|
self._emit(
|
|
"INFO",
|
|
"GPS_STOPPED",
|
|
"Auto GPS service stopped"
|
|
)
|