All files / src/hooks useGeoData.ts

90.58% Statements 77/85
64.28% Branches 27/42
93.75% Functions 15/16
95.65% Lines 66/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179                                                      5x 5x 5x 2x               5x 2x     5x 5x 5x             5x         5x 5x       5x 5x 8x 5x     5x 5x 5x 8x 8x   5x       5x 5x         5x 5x   5x 5x 5x   5x   3x       3x 3x 3x 3x 3x 3x 3x         3x 1x 3x 6x           1x 1x       3x           5x 4x 3x 3x   3x 4x 4x 3x 3x 3x         5x 3x 3x 6x 6x   3x     5x 5x       5x   5x   5x                                    
// File: src/hooks/useGeoData.ts
import { useApolloClient, useQuery } from '@apollo/client';
import { useEffect, useMemo, useState, useCallback } from 'react';
import {
  formatInputFormattedTemplate,
  useHostVariables,
  useWidgetRefreshRate,
  type TangoAttributeInput
} from '@ska-octopus-widget-sdk/widget-sdk';
import { layoutDocs, OP_POLL } from '../graphql/ops';
import {
  chunk,
  buildFullNames,
  buildAntennas,
  computePowerRange,
  computeTicks,
  LayoutRow,
  Row
} from '../utils/geomap';
import { normalizeEndpoints } from '../utils/endpoint';
 
export function useGeoData(opts: {
  stationId: string;
  instanceId?: string;
  mccsBatchSize?: number;
  endpoint?: string | string[] | TangoAttributeInput[];
}) {
  const { stationId, instanceId, mccsBatchSize, endpoint: rawEndpoint } = opts;
  const variables = useHostVariables();
  const resolvedStationId = useMemo(
    () =>
      formatInputFormattedTemplate({
        template: stationId,
        variables,
        fallback: stationId
      }),
    [stationId, variables]
  );
  const endpoints = useMemo(
    () => normalizeEndpoints(rawEndpoint, { variables }),
    [rawEndpoint, variables]
  );
  const selectedEndpoint = endpoints[0] ?? '1';
  const client = useApolloClient();
  const refreshSec = useWidgetRefreshRate(instanceId ?? 'geoMap');
 
  // 1) Fetch ALL antennas for the station
  const {
    data: layoutData,
    loading: layoutLoading,
    error: layoutError
  } = useQuery(layoutDocs, {
    variables: { station: resolvedStationId },
    fetchPolicy: 'cache-first'
  });
 
  const layoutRows: LayoutRow[] = useMemo(
    () => (layoutData?.antennaLocations?.antenna_locations ?? []) as any,
    [layoutData]
  );
 
  const smartboxes = useMemo(() => {
    const set = new Set<string>();
    for (const r of layoutRows) Eif (r.smartbox) set.add(String(r.smartbox).trim());
    return Array.from(set);
  }, [layoutRows]);
 
  const tpmIds = useMemo(() => {
    const set = new Set<string>();
    for (const r of layoutRows) {
      Iif (!r?.tpm) continue;
      set.add(`${resolvedStationId}-${String(r.tpm).trim()}`); // e.g., "s8-1-tpm01"
    }
    return Array.from(set);
  }, [layoutRows, resolvedStationId]);
 
  // 2) Build attribute fullNames for MCCS
  const fullNames = useMemo(
    () => buildFullNames(smartboxes, tpmIds, resolvedStationId),
    [smartboxes, tpmIds, resolvedStationId]
  );
 
  /** ============ Batched MCCS polling ============ */
  const batchSize = Math.max(1, Math.floor(mccsBatchSize ?? 5));
  const fullNameBatches = useMemo(() => chunk(fullNames, batchSize), [fullNames, batchSize]);
 
  const [rows, setRows] = useState<Row[]>([]);
  const [fetching, setFetching] = useState(false);
  const [fetchError, setFetchError] = useState<unknown>(null);
 
  const runFetchOnce = useCallback(
    async (cancelledRef: { v: boolean }) => {
      Iif (fullNameBatches.length === 0) {
        setRows([]);
        return;
      }
      setFetching(true);
      setFetchError(null);
      try {
        const all: Row[] = [];
        for (const names of fullNameBatches) {
          Iif (cancelledRef.v) return;
          const res = await client.query({
            query: OP_POLL,
            variables: { fullNames: names, endpoint: selectedEndpoint },
            fetchPolicy: 'network-only'
          });
          if (cancelledRef.v) return;
          const arr = (res.data?.attributes ?? []) as any[];
          for (const r of arr)
            all.push({
              device: String(r.device || ''),
              name: String(r.name || ''),
              value: r.value
            });
        }
        Iif (cancelledRef.v) return;
        setRows(all);
      } catch (e) {
        if (!cancelledRef.v) setFetchError(e);
      } finally {
        if (!cancelledRef.v) setFetching(false);
      }
    },
    [client, fullNameBatches, selectedEndpoint]
  );
 
  useEffect(() => {
    if (tpmIds.length === 0 && smartboxes.length === 0) return;
    const cancelled = { v: false };
    runFetchOnce(cancelled);
 
    const sec = Math.max(0, refreshSec ?? 0);
    let id: any = null;
    if (sec > 0) id = setInterval(() => runFetchOnce(cancelled), sec * 1000);
    return () => {
      cancelled.v = true;
      Eif (id) clearInterval(id);
    };
  }, [runFetchOnce, refreshSec, tpmIds.length, smartboxes.length]);
 
  // dev -> (name.lower -> value)
  const byDev = useMemo(() => {
    const m = new Map<string, Map<string, any>>();
    for (const r of rows) {
      if (!m.has(r.device)) m.set(r.device, new Map());
      m.get(r.device)!.set(r.name.toLowerCase(), r.value);
    }
    return m;
  }, [rows]);
 
  const antennas = useMemo(
    () => buildAntennas(layoutRows, byDev, resolvedStationId),
    [layoutRows, byDev, resolvedStationId]
  );
 
  const powerRange = useMemo(() => computePowerRange(antennas), [antennas]);
 
  const ticks = useMemo(() => computeTicks(powerRange), [powerRange]);
 
  return {
    // data
    layoutRows,
    antennas,
    powerRange,
    ticks,
 
    // states
    layoutLoading,
    layoutError,
    fetching,
    fetchError,
 
    // misc
    batchSize,
    refreshSec
  };
}