Source code for openworld_radio_twin.providers.local_antennas

"""Antennas from a user-supplied GeoJSON or CSV file, such as one's own network layout.

GeoJSON is a FeatureCollection of Point features whose properties use the names of
:class:`~openworld_radio_twin.models.AntennaFeature`: ``id`` is required; ``site_id``,
``operator``, ``plmn``, ``radios`` (or ``radio``), ``height_agl_m``, ``azimuth_deg``,
``downtilt_deg``, ``power_dbm`` and ``bands`` (a list of ``{"label", "low_mhz",
"high_mhz"}``) are optional. CSV has one row per antenna with ``id``, ``latitude``,
``longitude``, the same optional columns, and ``band_label``, ``band_low_mhz`` and
``band_high_mhz`` for one band. The file's SHA-256 enters the source identity.
"""

from __future__ import annotations

import csv
import hashlib
import io
import json
from pathlib import Path

import httpx
from pydantic import ValidationError

from openworld_radio_twin.config import Settings
from openworld_radio_twin.models import AntennaFeature, FrequencyBand
from openworld_radio_twin.providers.base import AntennaProviderError, AntennaQueryResult
from openworld_radio_twin.providers.snapshots import query_bounds

TITLE = "Local antenna file"
CONFIGURATION_HINT = "set OWRT_LOCAL_ANTENNAS to a GeoJSON or CSV antenna file"
VALUE_FIELDS = ("height_agl_m", "azimuth_deg", "downtilt_deg", "power_dbm")


def _path(settings: Settings) -> Path | None:
    return None if settings.local_antennas is None else Path(settings.local_antennas).expanduser()


[docs] def configured(settings: Settings) -> bool: path = _path(settings) return path is not None and path.is_file()
[docs] def configuration_identity(settings: Settings) -> dict[str, str]: path = _path(settings) if path is None or not path.is_file(): return {"file": "missing"} return {"sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
def _number(value: object) -> float | None: if value is None or (isinstance(value, str) and not value.strip()): return None return float(value) def _record(properties: dict, latitude: float, longitude: float, release: str) -> AntennaFeature: identifier = str(properties.get("id") or "").strip() if not identifier: raise ValueError("every antenna needs an id") radios = properties.get("radios") or ([properties["radio"]] if properties.get("radio") else []) bands = [FrequencyBand.model_validate(band) for band in properties.get("bands") or []] values = {name: _number(properties.get(name)) for name in VALUE_FIELDS} basis = {"position": "source"} basis.update({name: "source" for name, value in values.items() if value is not None}) if bands: basis["bands"] = "source" return AntennaFeature( feature_id=f"local:{identifier}", source="local", source_release=release, site_id=str(properties.get("site_id") or identifier), operator=properties.get("operator") or None, plmn=properties.get("plmn") or None, radios=[str(radio).upper() for radio in radios], bands=bands, latitude=latitude, longitude=longitude, basis=basis, **values, )
[docs] def parse_antenna_file(content: bytes, suffix: str, release: str) -> list[AntennaFeature]: """Antenna records of a GeoJSON or CSV file; errors name the offending entry.""" records = [] if suffix in {".geojson", ".json"}: document = json.loads(content) for index, feature in enumerate(document.get("features", []), start=1): geometry = feature.get("geometry") or {} if geometry.get("type") != "Point": raise ValueError(f"feature {index} is not a Point") longitude, latitude = geometry["coordinates"][:2] try: properties = feature.get("properties") or {} records.append(_record(properties, latitude, longitude, release)) except (ValidationError, ValueError, TypeError) as exc: raise ValueError(f"feature {index}: {exc}") from None elif suffix == ".csv": for index, row in enumerate(csv.DictReader(io.StringIO(content.decode("utf-8-sig"))), 2): properties = dict(row) if row.get("band_label"): properties["bands"] = [ { "label": row["band_label"], "low_mhz": row.get("band_low_mhz"), "high_mhz": row.get("band_high_mhz"), } ] try: records.append( _record(properties, float(row["latitude"]), float(row["longitude"]), release) ) except (ValidationError, ValueError, TypeError, KeyError) as exc: raise ValueError(f"row {index}: {exc}") from None else: raise ValueError("antenna files must be GeoJSON (.geojson, .json) or CSV (.csv)") return records
[docs] class LocalAntennaProvider: def __init__(self, settings: Settings, client: httpx.AsyncClient): self.path = _path(settings)
[docs] async def antennas( self, latitude: float, longitude: float, radius_m: float ) -> AntennaQueryResult: if self.path is None: raise AntennaProviderError(f"No local antenna file; {CONFIGURATION_HINT}") try: content = self.path.read_bytes() release = f"sha256:{hashlib.sha256(content).hexdigest()[:12]}" records = parse_antenna_file(content, self.path.suffix.lower(), release) except (OSError, ValueError) as exc: raise AntennaProviderError(f"Cannot read {self.path}: {exc}") from exc west, south, east, north = query_bounds(latitude, longitude, radius_m) inside = [ record for record in records if west <= record.longitude <= east and south <= record.latitude <= north ] return AntennaQueryResult(antennas=inside, provider=TITLE, release=release)