import type { DynamicData, InitData, RotatorConfig, RotatorState, Setpoint } from './types.js'; const ROTATOR_PORT = 88; const POLL_INTERVAL_MS = 1000; const REQUEST_TIMEOUT_MS = 2000; type NumType = 'string' | 'int' | 'float'; const INIT_ENDPOINTS: ReadonlyArray<[keyof InitData, string, NumType]> = [ ['azShift', 'readStart', 'int' ], ['azRange', 'readMax', 'int' ], ['antRadiationAngle', 'readAnt', 'int' ], ['antName', 'readAntName', 'string'], ['mapUrl', 'readMapUrl', 'string'], ['mac', 'readMAC', 'string'], ['elevation', 'readElevation', 'int' ], ]; /** * Client for the simple_rotator_interface_v protocol. * @see https://remoteqth.com/w/doku.php?id=simple_rotator_interface_v */ export default class RotClient { readonly label: string; private readonly ip: string; private readonly bands: number[]; private initData: InitData | null = null; private initDataLoading = false; private dynamicData: DynamicData | null = null; private setpoint: Setpoint | null = null; private readonly dynamicHandlers: Array<(data: DynamicData) => void> = []; private readonly initDataHandlers: Array<(data: InitData) => void> = []; constructor(label: string, { ip, bands }: RotatorConfig) { this.label = label; this.ip = ip; this.bands = bands; } /** Starts polling the controller. Init data is loaded once the rotator is reachable. */ start(): void { const poll = async () => { await this.fetchDynamicData(); setTimeout(() => void poll(), POLL_INTERVAL_MS); }; void poll(); } onDynamicDataUpdate(handler: (data: DynamicData) => void): void { this.dynamicHandlers.push(handler); } onInitDataLoaded(handler: (data: InitData) => void): void { this.initDataHandlers.push(handler); } hasBand(band: number): boolean { return this.bands.includes(band); } getState(): RotatorState { return { initData: this.initData, dynamic: this.dynamicData, bands: this.bands, setpoint: this.setpoint, }; } turn(setpoint: Setpoint): void { this.setpoint = setpoint; console.log(`Turning ${this.label} to ${setpoint.targetAz}° (by ${setpoint.station ?? setpoint.sourceIp})`); fetch(`${this.baseUrl()}/`, { body: `ROT=${setpoint.targetAz}`, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }).catch((ex: Error) => console.error(`${this.label}: Failed to send turn command: ${ex.cause ?? ex.message}`)); } private baseUrl(): string { return `http://${this.ip}:${ROTATOR_PORT}`; } private async loadInitData(): Promise { if (this.initData || this.initDataLoading) return; this.initDataLoading = true; try { const values = await Promise.all(INIT_ENDPOINTS.map(([, url, type]) => this.readKey(url, type))); // The rotator may have dropped off mid-read; retry on the next successful poll. if (values.every(v => v === null)) return; const data = Object.fromEntries(INIT_ENDPOINTS.map(([key], i) => [key, values[i]])) as unknown as InitData; this.initData = data; console.log(`${this.label}: Loaded init data (azimuth offset ${data.azShift}°).`); this.initDataHandlers.forEach(h => h(data)); } finally { this.initDataLoading = false; } } private async fetchDynamicData(): Promise { const [adc, azimuth, status] = await Promise.all([ this.readKey('readADC', 'float'), this.readKey('readAZ', 'int'), this.readKey('readStat', 'int'), ]); const data: DynamicData = { adc: adc as number | null, azimuth: azimuth as number | null, status: status as number | null, online: azimuth !== null, }; const old = this.dynamicData; const changed = !old || (Object.keys(data) as Array).some(k => old[k] !== data[k]); this.dynamicData = data; if (old?.online !== data.online) { console.log(`${this.label}: ${data.online ? 'online' : 'offline'}`); } if (data.online) void this.loadInitData(); if (changed) this.dynamicHandlers.forEach(h => h(data)); } private async readKey(endpoint: string, type: NumType): Promise { try { const resp = await fetch(`${this.baseUrl()}/${endpoint}`, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }); if (!resp.ok) return null; const text = await resp.text(); if (type === 'string') return text; const value = type === 'int' ? parseInt(text, 10) : parseFloat(text); return Number.isFinite(value) ? value : null; } catch { // Unreachable rotators are reported via the `online` flag rather than logged every second. return null; } } }