import type { PatternData, ComputeParams, ScanParams } from './types'; const BASE_URL = ''; export async function fetchPattern(params: ComputeParams): Promise { const resp = await fetch(`${BASE_URL}/api/pattern/compute`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params), }); if (!resp.ok) { const body = await resp.text(); throw new Error(`Compute failed (${resp.status}): ${body}`); } return resp.json(); } export async function scanPattern(params: ScanParams): Promise { const resp = await fetch(`${BASE_URL}/api/pattern`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params), }); if (!resp.ok) { const body = await resp.text(); throw new Error(`Scan failed (${resp.status}): ${body}`); } return resp.json(); } export async function getStatus(): Promise<{ connected: boolean; device?: string }> { const resp = await fetch(`${BASE_URL}/api/status`); if (!resp.ok) throw new Error(`Status check failed (${resp.status})`); return resp.json(); } export async function getBands(): Promise> { const resp = await fetch(`${BASE_URL}/api/bands`); if (!resp.ok) throw new Error(`Bands fetch failed (${resp.status})`); return resp.json(); } export type PatternCallback = (data: PatternData) => void; export type StatusCallback = (connected: boolean) => void; export function connectWebSocket( onPattern: PatternCallback, onStatus: StatusCallback ): { close: () => void } { let ws: WebSocket | null = null; let reconnectTimer: ReturnType | null = null; let closed = false; function connect() { if (closed) return; const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const url = `${protocol}//${window.location.host}/ws/pattern`; ws = new WebSocket(url); ws.onopen = () => { onStatus(true); }; ws.onmessage = (event) => { try { const data = JSON.parse(event.data) as PatternData; onPattern(data); } catch { // non-pattern message, ignore } }; ws.onclose = () => { onStatus(false); if (!closed) { reconnectTimer = setTimeout(connect, 3000); } }; ws.onerror = () => { ws?.close(); }; } connect(); return { close() { closed = true; if (reconnectTimer) clearTimeout(reconnectTimer); ws?.close(); }, }; }