mirror of
https://github.com/zvx-echo6/meshai.git
synced 2026-05-21 23:24:44 +02:00
- Environmental feed system with tick-based adapters - NWS Active Alerts: polls api.weather.gov, zone-based filtering - NOAA SWPC: Kp, SFI, R/S/G scales, band assessment, alert detection - Tropospheric ducting: Open-Meteo GFS refractivity profile, duct classification - !alerts command for active weather warnings - !solar / !hf commands for RF propagation (HF + UHF ducting) - Alert engine integration: severe weather, R3+ blackout, ducting events - LLM context injection for weather/propagation queries - Dashboard RF Propagation card with HF + UHF ducting display - EnvironmentalConfig with per-feed toggles in config.yaml
168 lines
6 KiB
Python
168 lines
6 KiB
Python
"""Environmental data store with tick-based adapter polling."""
|
|
|
|
import logging
|
|
import time
|
|
from typing import TYPE_CHECKING
|
|
|
|
if TYPE_CHECKING:
|
|
from ..config import EnvironmentalConfig
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class EnvironmentalStore:
|
|
"""Cache and tick-driver for all environmental feed adapters."""
|
|
|
|
def __init__(self, config: "EnvironmentalConfig"):
|
|
self._adapters = {} # name -> adapter instance
|
|
self._events = {} # (source, event_id) -> event dict
|
|
self._swpc_status = {} # Kp/SFI/scales snapshot
|
|
self._ducting_status = {} # tropo ducting assessment
|
|
self._mesh_zones = config.nws_zones or []
|
|
|
|
# Create adapter instances based on config
|
|
if config.nws.enabled:
|
|
from .nws import NWSAlertsAdapter
|
|
self._adapters["nws"] = NWSAlertsAdapter(config.nws)
|
|
|
|
if config.swpc.enabled:
|
|
from .swpc import SWPCAdapter
|
|
self._adapters["swpc"] = SWPCAdapter(config.swpc)
|
|
|
|
if config.ducting.enabled:
|
|
from .ducting import DuctingAdapter
|
|
self._adapters["ducting"] = DuctingAdapter(config.ducting)
|
|
|
|
logger.info(f"EnvironmentalStore initialized with {len(self._adapters)} adapters")
|
|
|
|
def refresh(self) -> bool:
|
|
"""Called every second from main loop. Ticks each adapter.
|
|
|
|
Returns:
|
|
True if any data changed
|
|
"""
|
|
changed = False
|
|
for name, adapter in self._adapters.items():
|
|
try:
|
|
if adapter.tick():
|
|
changed = True
|
|
self._ingest(name, adapter)
|
|
except Exception as e:
|
|
logger.warning("Env adapter %s error: %s", name, e)
|
|
|
|
self._purge_expired()
|
|
return changed
|
|
|
|
def _ingest(self, name: str, adapter):
|
|
"""Ingest data from an adapter after it ticks."""
|
|
if name == "swpc":
|
|
self._swpc_status = adapter.get_status()
|
|
# Also ingest any alert events (R-scale >= 3)
|
|
for evt in adapter.get_events():
|
|
self._events[(evt["source"], evt["event_id"])] = evt
|
|
elif name == "ducting":
|
|
self._ducting_status = adapter.get_status()
|
|
else:
|
|
for evt in adapter.get_events():
|
|
self._events[(evt["source"], evt["event_id"])] = evt
|
|
|
|
def _purge_expired(self):
|
|
"""Remove expired events."""
|
|
now = time.time()
|
|
expired = [
|
|
k for k, v in self._events.items()
|
|
if v.get("expires") and v["expires"] < now
|
|
]
|
|
for k in expired:
|
|
del self._events[k]
|
|
|
|
def get_active(self, source: str = None) -> list:
|
|
"""Get active events, optionally filtered by source.
|
|
|
|
Args:
|
|
source: Filter to specific source (nws, swpc, etc.)
|
|
|
|
Returns:
|
|
List of event dicts sorted by fetched_at (newest first)
|
|
"""
|
|
events = list(self._events.values())
|
|
if source:
|
|
events = [e for e in events if e["source"] == source]
|
|
return sorted(events, key=lambda e: e.get("fetched_at", 0), reverse=True)
|
|
|
|
def get_for_zones(self, zones: list) -> list:
|
|
"""Get events affecting specific NWS zones.
|
|
|
|
Args:
|
|
zones: List of UGC zone codes (e.g., ["IDZ016", "IDZ030"])
|
|
|
|
Returns:
|
|
List of events with overlapping zone coverage
|
|
"""
|
|
zone_set = set(zones)
|
|
return [
|
|
e for e in self._events.values()
|
|
if set(e.get("areas", [])) & zone_set
|
|
]
|
|
|
|
def get_swpc_status(self) -> dict:
|
|
"""Get current SWPC space weather status."""
|
|
return self._swpc_status
|
|
|
|
def get_ducting_status(self) -> dict:
|
|
"""Get current tropospheric ducting status."""
|
|
return self._ducting_status
|
|
|
|
def get_rf_propagation(self) -> dict:
|
|
"""Combined HF + UHF propagation summary for dashboard/LLM."""
|
|
return {
|
|
"hf": self._swpc_status,
|
|
"uhf_ducting": self._ducting_status,
|
|
}
|
|
|
|
def get_summary(self) -> str:
|
|
"""Compact text block for LLM context injection."""
|
|
lines = []
|
|
lines.append(f"### Current Conditions (as of {time.strftime('%H:%M:%S MT')}):")
|
|
|
|
# NWS alerts
|
|
nws = self.get_active(source="nws")
|
|
if nws:
|
|
lines.append(f"NWS: {len(nws)} active alert(s):")
|
|
for a in nws[:3]:
|
|
lines.append(f" - {a['event_type']}: {a['headline'][:120]}")
|
|
else:
|
|
lines.append("NWS: No active alerts for mesh area.")
|
|
|
|
# HF
|
|
s = self._swpc_status
|
|
if s:
|
|
kp = s.get("kp_current", "?")
|
|
sfi = s.get("sfi", "?")
|
|
assessment = s.get("band_assessment", "Unknown")
|
|
lines.append(f"HF: {assessment} -- SFI {sfi}, Kp {kp}")
|
|
warnings = s.get("active_warnings", [])
|
|
if warnings:
|
|
for w in warnings[:2]:
|
|
lines.append(f" Warning: {w}")
|
|
else:
|
|
lines.append("HF: Space weather data not available.")
|
|
|
|
# UHF ducting
|
|
d = self._ducting_status
|
|
if d:
|
|
condition = d.get("condition", "unknown")
|
|
if condition == "normal":
|
|
lines.append("UHF Ducting: Normal propagation, no ducting detected.")
|
|
elif condition in ("super_refraction", "ducting", "surface_duct", "elevated_duct"):
|
|
gradient = d.get("min_gradient", "?")
|
|
thickness = d.get("duct_thickness_m", "?")
|
|
lines.append(f"UHF Ducting: {condition.replace('_', ' ').title()} detected")
|
|
lines.append(f" dM/dz: {gradient} M-units/km, duct ~{thickness}m thick")
|
|
lines.append(" Extended range likely on 906 MHz -- expect distant nodes")
|
|
|
|
return "\n".join(lines)
|
|
|
|
def get_source_health(self) -> list:
|
|
"""Get health status for all adapters."""
|
|
return [a.health_status for a in self._adapters.values()]
|