defmodule MicrowavepropWeb.WeatherMapLive do @moduledoc "`/weather` — HRRR-derived forecast fields (temp, Td, wind, refractivity) on a map." use MicrowavepropWeb, :live_view alias Microwaveprop.Weather alias Microwaveprop.Weather.MapLayers @layers MapLayers.all() @default_layer MapLayers.default_id() @impl true def mount(_params, _session, socket) do _ = if connected?(socket) do :ok = Phoenix.PubSub.subscribe(Microwaveprop.PubSub, "weather:updated") Phoenix.PubSub.subscribe(Microwaveprop.PubSub, "propagation:pipeline") end # Default the timeline cursor to the valid_time closest to "now" so # users land on current conditions, not a +11h forecast hour (which # the underlying cache can advance to while the worker is walking # f00→f18). # # Mount stays cheap — no grid materialisation. The dead render # would otherwise spend ~5–10 s materialising 92k cells through # `WeatherLayers.derive`, blocking the HTTP response and tripping # the LiveView socket join timeout. The client now paints weather # through a tile endpoint, so mount only needs the selected layer # and valid_time metadata. valid_times = recent_valid_times(Weather.available_weather_valid_times()) initial_vt = pick_initial_valid_time(valid_times) {:ok, assign(socket, page_title: "Weather Map", layers: @layers, selected_layer: @default_layer, valid_time: initial_vt, valid_times: valid_times, initial_valid_times_json: Jason.encode!(Enum.map(valid_times, &DateTime.to_iso8601/1)), initial_selected_time: initial_vt && DateTime.to_iso8601(initial_vt), initial_utc_clock: Calendar.strftime(DateTime.utc_now(), "%H:%M UTC"), grid_visible: false, radar_visible: false )} end @impl true def handle_params(params, _uri, socket) do selected = pick_layer(params["layer"], socket.assigns[:selected_layer]) {:noreply, assign(socket, :selected_layer, selected)} end defp pick_layer(layer, current) when is_binary(layer) do if MapLayers.valid_id?(layer), do: layer, else: pick_layer(nil, current) end defp pick_layer(_layer, current) when is_binary(current), do: current defp pick_layer(_layer, _current), do: @default_layer defp pick_initial_valid_time([]), do: nil defp pick_initial_valid_time(valid_times) do now = DateTime.utc_now() Enum.min_by(valid_times, fn vt -> abs(DateTime.diff(vt, now, :second)) end) end # Drop valid_times older than one hour ago. The HRRR scalar cache can # hold the previous run's forecast hours past their useful life; # showing 3-hour-old "current conditions" on the map is more # misleading than helpful. defp recent_valid_times(valid_times) do cutoff = DateTime.add(DateTime.utc_now(), -3600, :second) Enum.filter(valid_times, fn vt -> DateTime.compare(vt, cutoff) != :lt end) end @impl true def handle_event("select_layer", %{"layer" => layer_id}, socket) do if MapLayers.valid_id?(layer_id) do {:noreply, push_patch(socket, to: ~p"/weather?layer=#{layer_id}")} else {:noreply, socket} end end def handle_event("toggle_grid", _params, socket) do visible = !socket.assigns.grid_visible socket = socket |> assign(:grid_visible, visible) |> push_event("toggle_grid", %{visible: visible}) {:noreply, socket} end def handle_event("toggle_radar", _params, socket) do visible = !socket.assigns.radar_visible socket = socket |> assign(:radar_visible, visible) |> push_event("toggle_radar", %{visible: visible}) {:noreply, socket} end def handle_event("select_time", %{"time" => time_str}, socket) do with {:ok, time, _} <- DateTime.from_iso8601(time_str), true <- time in socket.assigns.valid_times do socket = socket |> assign(:valid_time, time) |> push_event("update_weather_overlay", %{selected: DateTime.to_iso8601(time)}) {:noreply, socket} else _ -> {:noreply, socket} end end def handle_event("point_detail", %{"lat" => lat, "lon" => lon}, socket) do detail = if socket.assigns.valid_time do Weather.weather_point_detail(lat, lon, socket.assigns.valid_time) end payload = detail || %{} {:noreply, push_event(socket, "point_detail", payload)} end @impl true def handle_info({:weather_updated, _valid_time}, socket) do valid_times = recent_valid_times(Weather.available_weather_valid_times()) # Keep whatever the user has scrubbed to if it's still available, # otherwise fall back to the latest on-disk time (GridCache-backed # hot path). Never block mount/refresh on a ProfilesFile read for # the happy path. selected = cond do socket.assigns.valid_time in valid_times -> socket.assigns.valid_time valid_times != [] -> List.last(valid_times) true -> nil end socket = socket |> assign(:valid_times, valid_times) |> assign(:valid_time, selected) |> push_event("update_weather_overlay", %{selected: selected && DateTime.to_iso8601(selected)}) |> push_event("update_timeline", %{ times: Enum.map(valid_times, &DateTime.to_iso8601/1), selected: selected && DateTime.to_iso8601(selected) }) {:noreply, socket} end # A new forecast hour has landed. Re-enumerate the available times # so the timeline picks up the extra hour, but keep the currently # selected time where it is. def handle_info({:propagation_pipeline_progress, _progress}, socket) do valid_times = recent_valid_times(Weather.available_weather_valid_times()) if valid_times == socket.assigns.valid_times do {:noreply, socket} else socket = socket |> assign(:valid_times, valid_times) |> push_event("update_timeline", %{ times: Enum.map(valid_times, &DateTime.to_iso8601/1), selected: socket.assigns.valid_time && DateTime.to_iso8601(socket.assigns.valid_time) }) {:noreply, socket} end end @group_order ["Surface", "Upper Air", "Ducting"] defp group_layers(layers) do layers |> Enum.group_by(& &1.group) |> Enum.sort_by(fn {group, _} -> Enum.find_index(@group_order, &(&1 == group)) || 99 end) end defp layer_description(layers, selected_id) do case Enum.find(layers, &(&1.id == selected_id)) do %{desc: desc} -> desc _ -> nil end end defp selected_layer_label(layers, selected_id) do case Enum.find(layers, &(&1.id == selected_id)) do %{label: label} -> label _ -> "" end end defp selected_layer_group_label(layers, selected_id) do case Enum.find(layers, &(&1.id == selected_id)) do %{group: group} -> group _ -> "" end end @impl true def render(assigns) do ~H"""